Cypher

SynergyDB has two separate Cypher implementations. They share no code and do not see each other's data.

  Bolt executor Engine-side analyzer
Code src/protocol/bolt/ src/query/cypher/ plus graph operators in src/query/engine.rs
Reached from Bolt listener (Neo4j drivers) Any SQL wire through text detection, HTTP /api/v1/query with "language": "cypher", HTTP /api/v1/graph/query, Studio with protocol: bolt, gRPC
Translation Native evaluator over an in-memory graph CypherParser to AST, CypherPlanner to LogicalPlan, QueryEngine::execute_plan
Storage _bolt_nodes, _bolt_relationships, _bolt_schema __graph_nodes__, __graph_edges__
Coverage Wide; differential-tested against Neo4j 5.26 Narrow; see the gaps in section 2.5

(source: src/protocol/bolt/mod.rs, GraphStore::with_storage; src/query/cypher/mod.rs, CypherAnalyzer::parse_query; src/query/cypher/planner.rs, CypherPlanner::node_to_insert; src/query/engine.rs, QueryEngine::detect_language)

A node created over Bolt is not visible to a MATCH sent over the PostgreSQL wire, and the reverse also holds, because the two implementations write different tables (source: src/protocol/bolt/mod.rs, GraphStore::with_storage; src/query/cypher/planner.rs, CypherPlanner::plan_create).

1. Bolt executor

The Bolt wire evaluates Cypher itself. Statement routing, patterns, expressions and functions, procedures, indexes and constraints, storage mapping, error codes and tests are documented in Neo4j Bolt and Cypher, section 6 and are not repeated here.

The translation summary for this path:

  • execute_cypher splits multi-statement text and UNION branches, then routes each statement either to the write pipeline (run_clauses) when any clause updates, or to the read pipeline (source: src/protocol/bolt/mod.rs, execute_single_cypher).
  • Clauses run over an in-memory GraphStore. Writes are mirrored to SQL tables _bolt_nodes and _bolt_relationships through QueryEngine, and schema to _bolt_schema (source: src/protocol/bolt/mod.rs, GraphStore::with_storage).
  • No LogicalPlan is built, so the SQL optimizer, plan cache and SQL row-level security path do not apply; the Bolt executor has its own row-level security hook (source: src/protocol/bolt/mod.rs, execute_single_cypher; see section 6.4 of the Bolt page).

Tested by tests/protocol_bolt.rs, the unit tests in src/protocol/bolt/, and the differential harness test-scripts/diff-cypher/diff_cypher.py (source: Bolt page, section 9).

2. Engine-side analyzer

2.1 Pipeline

flowchart LR T["Cypher text"] --> L["CypherLexer"] L --> P["CypherParser"] P --> A["CypherQuery (clauses)"] A --> PL["CypherPlanner::plan"] PL --> LP["LogicalPlan"] LP --> X["QueryEngine::execute_plan"] X -->|"graph leaf under Project, Filter, Sort, Distinct, Limit"| G["execute_graph_query"] X -->|"Join of Inserts"| I["inserts run in order"] X -->|"anything else"| S["SQL operators"]

(source: src/query/cypher/mod.rs, CypherAnalyzer::parse_query; src/query/engine.rs, plan_leaf_is_graph, is_insert_only_join, execute_graph_query)

CypherPlanner::plan folds the clause list from left to right: each clause receives the plan built so far as its input (source: src/query/cypher/planner.rs, CypherPlanner::plan, plan_clause).

2.2 Accepted syntax

Keywords recognised by the lexer: MATCH, OPTIONAL, WHERE, RETURN, WITH, CREATE, MERGE, DELETE, SET, REMOVE, UNWIND, UNION, ORDER, BY, ASC, DESC, ASCENDING, DESCENDING, SKIP, LIMIT, AS, DISTINCT, AND, OR, XOR, NOT, IN, IS, NULL, TRUE, FALSE, CALL, YIELD, FOREACH, ON, CASE, WHEN, THEN, ELSE, END, EXISTS, ALL, ANY, NONE, SINGLE, STARTS, ENDS, CONTAINS, SHORTESTPATH, ALLSHORTESTPATHS, DETACH, INDEX, FOR, DROP, CONSTRAINT, UNIQUE, IF (source: src/query/cypher/lexer.rs, CypherLexer).

Clauses accepted by the parser (source: src/query/cypher/parser.rs, CypherParser::parse_clause):

Clause Forms
MATCH, OPTIONAL MATCH Comma-separated patterns, optional WHERE
CREATE Patterns; also CREATE INDEX [name] [IF NOT EXISTS] FOR (n:Label) ON (n.p, ...)
MERGE Pattern with ON CREATE SET and ON MATCH SET
DELETE, DETACH DELETE Expression list
SET n.prop = expr, n = map, n += map, n:Label
REMOVE n.prop, n:Label
WITH DISTINCT, items with AS, WHERE, ORDER BY, SKIP, LIMIT
RETURN DISTINCT, items with AS, ORDER BY, SKIP, LIMIT
UNWIND expr AS x  
CALL proc(args) YIELD a, b  
FOREACH (x IN list \| clauses)  
UNION, UNION ALL  
DROP INDEX name [IF EXISTS]  

Patterns: node (v:L1:L2 {k: v}), relationship -[r:T1|T2 {k: v}]->, <-[...]- and -[...]-, and variable length *, *n, *a..b (source: src/query/cypher/parser.rs, parse_pattern, parse_pattern_path).

Expressions, from lowest to highest precedence: OR, XOR, AND, NOT, comparison (=, <>, <, <=, >, >=, =~, IN, IS [NOT] NULL, STARTS WITH, ENDS WITH, CONTAINS), additive, multiplicative, power, unary, postfix (.prop, [i], [a..b], :Label), primary. Primary covers literals, $param, lists, maps, parentheses, CASE, EXISTS, all/any/none/single list predicates, shortestPath and allShortestPaths, and function calls (source: src/query/cypher/parser.rs, parse_expression and the precedence chain under it).

2.3 Clause translation

Clause LogicalPlan produced
MATCH (n:L) GraphMatch with a node pattern; a {k: v} map on a standalone node adds a Filter
MATCH (a)-[:T]->(b) GraphMatch with an EdgePattern (types, direction)
Variable length *a..b GraphTraverse whose start is a Scan of a SQL table named after the first label, or nodes when there is no label. *n gives (n, n), a range with no lower bound gives min 1, * gives (1, unbounded)
Several paths in one pattern Inner Join; separate comma patterns are a Cross Join
A second MATCH Cross Join with the earlier plan; OPTIONAL MATCH is a Left Join
CREATE One Insert into __graph_nodes__ (_id a v4 UUID, _labels, _properties as JSON) per new node variable, and one Insert into __graph_edges__ (_id, _from_id, _to_id, _type, _properties) per relationship, combined in a Join tree
MERGE Same as CREATE; ON CREATE and ON MATCH are dropped
DELETE v Delete on a table named v with filter _variable = 'v'
SET Update on a table named after the variable, with no filter; SET n:L assigns _labels
REMOVE n.p Update setting column p to NULL; REMOVE n:L adds no assignment
WITH, RETURN Project, or Aggregate when an aggregate appears, then Distinct, Sort, Limit; SKIP and LIMIT take integer literals only
UNWIND e AS x Project of e; the variable x is not bound
FOREACH Input returned unchanged
UNION Input returned unchanged
CALL db.labels() and others db.indexes, db.labels, db.relationshipTypes, db.propertyKeys, db.schema.nodeTypeProperties, db.constraints become scans of _graph_indexes, _graph_labels, _graph_relationship_types, _graph_property_keys, _graph_node_type_properties and _graph_constraints, tables that no code creates; dbms.components returns a fixed row; any other name becomes a Project of a function call of that name
CREATE INDEX B-tree CreateIndex on the label's table; IF NOT EXISTS is ignored
DROP INDEX DropIndex

(source: src/query/cypher/planner.rs, plan_match, pattern_to_plan, path_to_plan, node_to_plan, relationship_to_plan, variable_length_path_plan, plan_create, node_to_insert, plan_merge, plan_delete, plan_set, plan_remove, plan_with, plan_return, plan_unwind, plan_foreach, plan_call, plan_create_index, plan_drop_index, plan_clause)

Properties written by CREATE are converted by expr_to_json_value, which handles literals, lists and maps; a $param or any computed expression is stored as JSON null (source: src/query/cypher/planner.rs, expr_to_json_value). Properties on nodes inside a relationship pattern, and properties on relationships in MATCH, are not turned into filters (source: src/query/cypher/planner.rs, relationship_to_plan).

2.4 Expression mapping

Cypher Engine expression
$name Column named $name
List, map array(...), map(...) function calls
x IS NULL x = NULL
x IN list InList holding the list as one element
=~ LIKE
STARTS WITH, ENDS WITH, CONTAINS starts_with, ends_with, contains function calls
x[i], x[a..b] array_get, array_slice
n:Label labels(n) contains Label
EXISTS { ... } Exists subquery
shortestPath(...) Function call with no arguments
count, sum, avg, min, max, collect Matching aggregates; any other aggregate name (for example stdev, percentileCont) becomes Count
List comprehensions, pattern comprehensions, list predicates and other unhandled forms NULL literal

(source: src/query/cypher/planner.rs, expr_to_plan, extract_aggregates)

2.5 Execution in the engine

QueryEngine::execute_plan checks two shapes before normal SQL execution (source: src/query/engine.rs, plan_leaf_is_graph, is_insert_only_join):

  • A plan whose leaf is GraphMatch, GraphTraverse or ShortestPath, wrapped only in Project, Filter, Sort, Distinct or Limit, goes to execute_graph_query.
  • A Join tree whose leaves are all Insert (a multi-entity CREATE) is flattened and its inserts run left to right, so nodes are written before the edges that reference them.

Graph operators (source: src/query/engine.rs, execute_graph_node_match, execute_graph_relationship_match, execute_graph_traverse):

  • Node match scans __graph_nodes__ and keeps a node if it has any of the requested labels. Each row holds one column per variable with the node as JSON {"_id", "_labels", "_properties"}.
  • Relationship match loads all nodes and edges, keeps edges whose type is in the requested list and whose endpoints carry any of the requested labels, and adds the reverse direction for an undirected pattern.
  • Traversal runs a breadth-first search over __graph_edges__ from the first column of each start row, with a default maximum depth of 10 and one visited set shared by all start nodes. It returns columns path (a -> b -> c) and length.

Known gaps, all visible in the code:

  • WHERE is not applied to graph results: filter_graph_result returns its input unchanged. This also discards inline property maps such as MATCH (n:Person {name: 'A'}) (source: src/query/engine.rs, filter_graph_result).
  • ORDER BY over a graph result passes rows through in scan order (source: src/query/engine.rs, execute_graph_query).
  • RETURN n and RETURN * work; RETURN n.prop and any other expression return NULL (source: src/query/engine.rs, project_graph_result).
  • RETURN count(n) plans an Aggregate, which is not a graph wrapper, so it runs on the SQL path over a GraphMatch input (source: src/query/engine.rs, plan_leaf_is_graph). Not verified: no test runs a Cypher aggregate through the engine.
  • SET, REMOVE and DELETE target a table named after the Cypher variable rather than __graph_nodes__, so they do not modify nodes created by CREATE (source: src/query/cypher/planner.rs, plan_set, plan_delete).
  • MERGE always creates (source: src/query/cypher/planner.rs, plan_merge).
  • Variable-length traversal starts from a SQL table named after the label, not from __graph_nodes__ (source: src/query/cypher/planner.rs, variable_length_path_plan). Not verified: no test runs a variable-length pattern through the engine.

2.6 Unsupported

FOREACH, UNION, UNWIND variable binding, MERGE matching, CALL { } subqueries, EXPLAIN/PROFILE, constraints (CONSTRAINT and UNIQUE are lexed but no clause parses them), path variables, and shortestPath evaluation are not implemented on this path (source: src/query/cypher/parser.rs, parse_clause; src/query/cypher/planner.rs, plan_clause, expr_to_plan).

2.7 Tests

  • Engine round trips in src/query/engine.rs: test_engine_cypher_create_emits_one_wellformed_row, test_engine_cypher_create_then_match_roundtrip, test_engine_cypher_two_same_label_nodes_no_collision, test_engine_cypher_create_edge_then_match_traverses.
  • Cross-model transactions in src/query/engine.rs: test_cross_model_txn_with_graph_backing_relation_atomic, test_cross_model_rel_plus_cypher_create_atomic; results recorded in test-scripts/cross-model-acid/RESULTS.md.
  • Parser and lexer unit tests: src/query/cypher/mod.rs (test_simple_match_return, test_match_with_labels, test_relationship_pattern, test_create_node, test_where_clause, test_aggregation), src/query/cypher/parser.rs (4), src/query/cypher/lexer.rs (3). src/query/cypher/planner.rs has no tests.
  • tests/integration_showcase.rs exercises Cypher but prints [OK] or [PARTIAL] and asserts nothing, so it does not count as a test of behaviour.

(source: the files named)