Query language AST
The query language AST is the shared data model for building graph queries and sending them to the planner or a client-facing query boundary. It represents graph sources, chained traversal steps, expressions, result shaping, batch control, runtime values, and stable validation outcomes in one serializable form. The parent page, Query planning and execution, describes how this model moves into planning and execution; Planner and optimizer and Interpreter execution describe the later stages.
Query representation
The AST uses an operation tree. A query starts at a node or edge source, and each later traversal operation wraps the previous stream as its input; a branch stores its own sub-traversal that can begin at the parent Context. This shape preserves query order while giving planning one stable tree to inspect.
The model supports these broad operation groups:
| Group | Purpose |
|---|---|
| Sources | Select nodes or edges by ID, variable, parameter, label, predicate, or search input. |
| Graph movement | Move between nodes and edges in outgoing, incoming, or both directions. |
| Filters and stream control | Apply property or predicate filters, deduplicate results, select saved streams, and set limits or ranges. |
| Result terminals | Produce IDs, labels, values, maps, projections, counts, existence checks, groups, aggregates, paths, or edge properties. |
| Branches and loops | Combine alternatives, choose a branch, use an optional branch, or repeat a sub-traversal with bounds and emit rules. |
| Graph and index changes | Add or remove graph data, change properties, and manage index operations in write-capable queries. |
The serialized operation names use snake case. A traversal builder therefore acts as a client-side way to create the same tree that the planner receives. The tree can also be read from the query wire format, so clients do not need to share the builder language with the planner.
This diagram shows how a chained graph pattern becomes a nested AST and then travels through the shared query boundary.
flowchart LR
A[Node or edge source] --> B[Traversal and filter steps]
B --> C[Branch or repeat sub-traversal]
C --> D[Terminal result operation]
D --> E[Batch query request]
E --> F[Planner]
F --> G[Runtime execution]
References: crates/…/lib.rs• L1-12 crates/…/traversal.rs• L115-659 crates/…/traversal.rs• L1083-1106
Graph references and traversal states
Graph references identify the starting or target elements without forcing the query to know the values at build time. A NodeRef or EdgeRef can mean all elements, a finite ID set, a named variable, or a runtime parameter that supplies IDs.
Traversal construction follows the type of stream being processed. The public builder distinguishes an empty traversal from node, edge, and terminal results. It also tracks whether a traversal is read-only or can contain a persistent mutation. These states guide valid query construction and make the read/write boundary visible before a request is sent.
The main traversal relationships are:
- Node streams can move to adjacent nodes or to matching edges.
- Edge streams can move to their source, target, or other endpoint.
- Search sources and within-stream search rank node or edge candidates by text or vector input.
Contextlets a branch inherit the element stream supplied by its parent operation.- A terminal operation ends a traversal and defines the shape returned to the batch.
References: crates/…/graph.rs• L3-20 crates/…/traversal.rs• L14-60 crates/…/traversal.rs• L72-114 crates/…/traversal.rs• L1342-1402 crates/…/traversal.rs• L1434-1667
Expressions and predicates
Expressions describe values that the query computes or reads while it runs. They can refer to a property, element ID, current time, a literal, or a runtime parameter. Arithmetic and conditional expressions let filters, mutations, bounds, and projections use values that depend on the current row.
Predicates describe conditions over expressions. They cover comparisons, inclusive ranges, null and property checks, string tests, membership, and boolean combinations. Source predicates use the same predicate shape as later filters, which keeps source selection and in-stream filtering consistent.
Stream bounds such as limits, skips, ranges, and search result counts can be fixed values or expressions. A PropertyInput follows the same idea for mutation values: it is either a literal property value or an expression evaluated at runtime.
References: crates/…/expr.rs• L3-40 crates/…/expr.rs• L42-49 crates/…/expr.rs• L170-239 crates/…/expr.rs• L242-310 crates/…/value.rs• L258-295
Values and parameters
PropertyValue is the value model used by graph properties and literal query inputs. It includes nulls, booleans, signed integers, floating-point values, strings, bytes, typed arrays, nested arrays, objects, and datetimes stored as UTC epoch milliseconds. QueryValue is the JSON-safe request value model; it carries the values that a client sends as runtime parameters and can be converted to property values for query use.
The request can use untyped parameters or a declared parameter schema. Typed parameters name an expected value family, support nested array schemas, and normalize permitted numeric forms before planning. The two modes cannot be mixed in one request. Datetime parameters use RFC3339 strings at the JSON boundary, while bytes are not accepted by this JSON parameter route.
The value model separates data that is valid in the graph from data that is safe on the JSON request path. This distinction lets the planner and database retain richer property values without making every client encode those values in the same way.
References: crates/…/value.rs• L7-44 crates/…/value.rs• L85-100 crates/…/value.rs• L222-256 crates/…/query.rs• L44-64 crates/…/query.rs• L574-627
Projections and result shape
Projections define named fields in a terminal result. A property projection selects a property and can rename it. An expression projection gives a computed expression an output alias. Endpoint property references allow an edge result to expose data from its source or target node.
Row bindings support patterns that need more than the current traverser element. A bind captures the current element under a name. A binding projection can read from the current element or a named binding, and a coalesce projection returns the first present non-null candidate. Distinct binding projection removes duplicate projected rows.
The choice of terminal matters to downstream consumers. Values returns selected property values, ValueMap returns property maps, ordinary Project returns named fields, and binding projection returns fields assembled from row-local context.
References: crates/…/projection.rs• L1-80 crates/…/projection.rs• L95-164 crates/…/projection.rs• L166-240 crates/…/traversal.rs• L394-442 crates/…/traversal.rs• L404-444
Batches and query requests
A batch is the request-level unit that groups named traversals in execution order and declares which variables to return. A batch entry is either a named query with an optional condition or a for_each body that runs for each object in a parameter array. Conditions can depend on a saved variable, its size, or whether the previous query returned a result.
Read and write batches express different safety contracts. A read batch accepts only read-only roots, including every nested branch, repeat body, and for_each body. A write batch can contain graph and index changes. QueryRequest wraps one closed batch, derives its read or write request kind from that batch, and carries an optional query name plus runtime parameters.
The request lifecycle is therefore split into clear responsibilities:
- A client builds or decodes a traversal tree.
- The tree is placed in a read or write batch.
- The request adds runtime values and optional type declarations.
- The request is serialized or passed to the planner as a closed query and parameter map.
References: crates/…/batch.rs• L5-44 crates/…/batch.rs• L46-103 crates/…/batch.rs• L124-169 crates/…/batch.rs• L183-268 crates/…/query.rs• L34-42 crates/…/query.rs• L211-283
Validation and error contracts
Validation protects the shared boundary from query trees that cannot be planned or have unclear meaning. It checks request tags, parameter names and shapes, duplicate map keys, typed schema matches, and the read-only rule across all nested query positions. Builder helpers also reject empty binding names and empty binding projection sets.
Query errors have two roles. QueryError reports local request construction and serialization problems with useful paths such as a nested parameter location. QueryErrorCode is the stable machine-readable catalog used by query boundaries for caller decisions. Error messages can gain context, but clients should branch on the code rather than on display text.
Important validation groups include:
- Request and JSON shape errors.
- Parameter name, mode, type, numeric, datetime, and JSON-safety errors.
- Invalid batch conditions, branch structure, repeat bounds, ranges, order keys, and projections.
- Illegal operations in read batches, branches, or after row binding.
- Planning-specific search, index, and runtime input errors reported through the stable code catalog.
References: crates/…/query.rs• L88-126 crates/…/query.rs• L470-536 crates/…/query.rs• L538-627 crates/…/batch.rs• L56-78 crates/…/batch.rs• L183-194 crates/…/projection.rs• L242-259 crates/…/error_code.rs• L1-22 crates/…/error_code.rs• L279-370
Planning boundary
The AST is the contract between client query construction and planning. The planner receives the query tree together with runtime parameter bindings and a planning context that describes available indexes, statistics, feedback, storage costs, and guardrails. It can then choose a physical strategy without changing the meaning of the original graph pattern.
The AST does not describe storage access or execution scheduling. It describes intent and result shape. The planner and interpreter pages explain how that intent is analyzed, optimized, lowered, and run against the graph engine.
References: crates/…/planner.rs• L8-38 crates/…/planner.rs• L40-125 crates/…/Cargo.toml• L1-17 crates/…/Cargo.toml• L6-11 crates/…/Cargo.toml• L6-15
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the serialized AST variant names and field shapes aligned with client SDK builders and planner input decoding.
- When adding an AST operation, make an explicit read-safety decision so nested read-batch validation cannot silently accept a mutation.
- Keep terminal result shapes aligned with projection materialization and client response decoding.
- When changing
QueryValueorQueryParamType, preserve typed and untyped parameter rules and the JSON boundary for datetimes, bytes, and non-finite numbers. - When changing branch, repeat, or context rules, check both builder construction and recursive validation in nested batch entries.
- Add a stable
QueryErrorCodewhen callers need to distinguish a new failure; do not make clients parse display messages. - When changing index or search AST fields, review planner parameter binding and index-selection contracts together.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A read batch contains a mutation inside a branch, repeat body, or for_each body. | A query with a read request kind could change persistent graph or index state. | ReadBatch recursively checks every nested AST root with is_read_only. |
| The request kind tag disagrees with the closed batch variant. | A client or server could treat a write as a read or the reverse. | QueryRequest rejects mismatched request_type and batch tags during decode. |
| Typed parameter names differ from runtime value names. | Planning receives an incomplete or ambiguous parameter environment. | Request validation reports missing and extra names before the request is accepted. |
| A typed array contains a value that does not match its inner type. | A parameter may reach an expression or index operation with the wrong shape. | Typed normalization validates array elements recursively and reports the nested path. |
| A branch operation has no usable parent context. | A sub-traversal cannot resolve the element stream it must process. | Branch roots use Context, and planner validation reports an unbound context. |
| A projection has an empty binding name, source, alias, or candidate list. | Result fields cannot be addressed consistently by clients or the runtime. | Binding builders reject empty names and empty coalesce or projection lists. |
| A search count, repeat depth, or shortest-path depth is invalid. | The planner cannot form a bounded search or traversal plan. | The stable error catalog exposes dedicated validation codes for these bounds. |
Key files
| File | Why to read it |
|---|---|
| crates/…/lib.rs | Establishes the AST crate’s role as the shared JSON contract and shows the basic builder-to-tree relationship. |
| crates/…/traversal.rs | Defines graph operations, branch structure, terminals, mutation capability, and the traversal builder surface. |
| crates/…/expr.rs | Defines computed values, predicates, comparisons, and stream bounds used across the query model. |
| crates/…/value.rs | Defines graph property values, mutation inputs, and datetime representation. |
| crates/…/projection.rs | Defines ordinary projections and row-binding result fields. |
| crates/…/batch.rs | Defines ordered query batches, conditions, for_each, and recursive read-only validation. |
| crates/…/query.rs | Defines request envelopes, parameter schemas, JSON values, serialization, and request validation. |
| crates/…/error_code.rs | Defines stable machine-readable query failure codes for client and server boundaries. |
| crates/…/planner.rs | Shows the planning context that consumes the AST with parameters and graph metadata. |