# Query Builder Overview

> A fluent, type-safe API for querying your graph

Canonical: https://typegraph.dev/queries/overview/

TypeGraph provides a fluent, type-safe query builder for traversing and filtering your graph. This
page introduces the query categories and how they compose together.

## Query Categories

Every query builder method falls into one of these categories:

| Category | Purpose | Key Methods |
|----------|---------|-------------|
| [Source](https://typegraph.dev/queries/source.md) | Entry point - where to start | `from()` |
| [Filter](https://typegraph.dev/queries/filter.md) | Reduce the result set | `whereNode()`, `whereEdge()` |
| [Traverse](https://typegraph.dev/queries/traverse.md) | Navigate relationships | `traverse()`, `optionalTraverse()`, `to()` |
| [Recursive](https://typegraph.dev/queries/recursive.md) | Variable-length paths | `recursive()` |
| [Shape](https://typegraph.dev/queries/shape.md) | Transform output structure | `select()`, `project()`, `map()`, `aggregate()` |
| [Expressions](https://typegraph.dev/queries/expressions.md) | Typed database calculations | `expr`, `project()`, expression callbacks |
| [Aggregate](https://typegraph.dev/queries/aggregate.md) | Summarize data | `groupBy()`, `count()`, `sum()`, `avg()` |
| [Order](https://typegraph.dev/queries/order.md) | Control result ordering/size | `orderBy()`, `limit()`, `offset()` |
| [Temporal](https://typegraph.dev/queries/temporal.md) | Time-based queries | `temporal()` |
| [Compose](https://typegraph.dev/queries/compose.md) | Reusable query parts | `pipe()`, `createFragment()` |
| [Combine](https://typegraph.dev/queries/combine.md) | Set operations | `union()`, `intersect()`, `except()` |
| [Execute](https://typegraph.dev/queries/execute.md) | Run and retrieve | `execute()`, `first()`, `count()`, `exists()`, `paginate()`, `stream()`, `batch()` |

## Query Flow

A typical query follows this flow:

```text
Source → Filter → Traverse → Filter → Shape → Order → Execute
         ↑__________________|
           (repeat as needed)
```

Each step is optional except Source and Execute. You can filter, traverse, and filter again as many
times as needed before shaping and executing.

## Basic Example

```typescript
const results = await store
  .query()
  .from("Person", "p")                              // Source
  .whereNode("p", (p) => p.status.eq("active"))     // Filter
  .traverse("worksAt", "e")                         // Traverse
  .to("Company", "c")                               // Traverse (target)
  .whereNode("c", (c) => c.industry.eq("Tech"))     // Filter
  .select((ctx) => ({                               // Shape
    person: ctx.p.name,
    company: ctx.c.name,
    role: ctx.e.role,
  }))
  .orderBy("p", "name", "asc")                      // Order
  .limit(50)                                        // Order
  .execute();                                       // Execute
```

## Type Safety

The query builder is fully typed. TypeScript infers result types based on your schema and selection:

```typescript
// TypeScript infers: Array<{ name: string; email: string | undefined }>
const results = await store
  .query()
  .from("Person", "p")
  .select((ctx) => ({
    name: ctx.p.name,    // string (required in schema)
    email: ctx.p.email,  // string | undefined (optional in schema)
  }))
  .execute();

// Invalid property access is caught at compile time:
.select((ctx) => ({
  invalid: ctx.p.nonexistent,  // TypeScript error!
}))
```

For new database-side projections and calculations, use typed
[database expressions](https://typegraph.dev/queries/expressions.md). `project()` compiles its callback to SQL, while
`map()` transforms decoded rows in JavaScript. Existing `select()` callbacks retain their
compatibility behavior.

## When to Use Queries vs Store API

**Use the query builder** when you need:

- Filtering based on node properties
- Traversing relationships between nodes
- Aggregating data across multiple nodes
- Complex predicates with AND/OR logic

**Use the [Store API](https://typegraph.dev/schemas-stores.md#store-api)** for simple operations:

- Get a node by ID
- Create a new node
- Update a node's properties
- Delete a node

## Predicates Reference

Predicates are the building blocks for filtering. Each data type has its own set of predicates:

| Type | Documentation |
|------|--------------|
| String | [String Predicates](https://typegraph.dev/queries/predicates.md#string) |
| Number | [Number Predicates](https://typegraph.dev/queries/predicates.md#number) |
| Date | [Date Predicates](https://typegraph.dev/queries/predicates.md#date) |
| Array | [Array Predicates](https://typegraph.dev/queries/predicates.md#array) |
| Object | [Object Predicates](https://typegraph.dev/queries/predicates.md#object) |
| Embedding | [Embedding Predicates](https://typegraph.dev/queries/predicates.md#embedding) |

## Performance Tips

### Filter Early

Apply predicates as early as possible to reduce the working set:

```typescript
// Good: Filter at source
store
  .query()
  .from("Person", "p")
  .whereNode("p", (p) => p.active.eq(true))
  .traverse("worksAt", "e")
  .to("Company", "c");

// Less efficient: Filter after traversal
store
  .query()
  .from("Person", "p")
  .traverse("worksAt", "e")
  .to("Company", "c")
  .whereNode("p", (p) => p.active.eq(true));
```

### Be Specific with Kinds

Querying a kind with subclasses is polymorphic **by default** — `from`/`to`/
`fromDynamic`/`toDynamic` include subtype rows unless you narrow. If you only
want the exact kind, say so:

```typescript
// Exact kind by construction — no subclasses to expand
.from("Podcast", "p")

// Polymorphic by default: includes every Media subclass (Podcast, Article, ...)
.from("Media", "m")

// Narrow it back to exactly Media rows
.from("Media", "m", { expansion: "exact" })
```

### Always Paginate Large Results

```typescript
const page = await store
  .query()
  .from("Event", "e")
  .orderBy("e", "date", "desc")
  .limit(100)
  .select((ctx) => ctx.e)
  .execute();
```

## Next Steps

Start with the fundamentals:

1. [Source](https://typegraph.dev/queries/source.md) - Starting queries with `from()`
2. [Filter](https://typegraph.dev/queries/filter.md) - Reducing results with predicates
3. [Traverse](https://typegraph.dev/queries/traverse.md) - Navigating relationships
4. [Shape](https://typegraph.dev/queries/shape.md) - Transforming output with `select()`
