Skip to content

graflo.db.cypher

Shared Cypher query fragments (no drivers; safe string builders only).

Modules:

Name Description
bulk

Create-only Cypher for a bulk load, and the counts that verify it.

delete

Cypher statements that remove nodes and relationships by their keys or scope.

direction

Relationship-pattern direction for Cypher-family backends.

escape

Cypher string and identifier escaping for safe query fragments.

introspection

Sampling introspection for the Cypher family.

rel_merge

Relationship MERGE map fragments for parallel edges (property-graph backends).

scan

Read every relationship between two labels, whatever its endpoints' keys.

sync

Cypher for record sync: ensure vertices, then replace what changed owners wrote.

targets

The Cypher read behind fetch_edge_targets: the stored targets of each source.

traversal

Native variable-length traversal for the Cypher family.

union

Cypher upserts that union list fields with what a node or relationship holds.

Attributes

__all__ = ['cypher_map_key', 'cypher_name', 'cypher_names', 'cypher_neighbors_query', 'cypher_rel_pattern', 'cypher_string_literal', 'partition_by_absent_merge_props', 'rel_absent_upsert_clause', 'rel_merge_props_map_from_row_index', 'rel_merge_props_map_from_row_props', 'rel_union_rows', 'rel_upsert_clause'] module-attribute

Functions:

cypher_map_key(name)

Return a backtick-quoted map-key / property name for Cypher patterns.

Surrounding whitespace is dropped first; embedded backticks are doubled, so two names differing only by a backtick stay two keys.

Source code in graflo/db/cypher/escape.py
def cypher_map_key(name: str) -> str:
    """Return a backtick-quoted map-key / property name for Cypher patterns.

    Surrounding whitespace is dropped first; embedded backticks are doubled,
    so two names differing only by a backtick stay two keys.
    """
    key = name.strip()
    if not key:
        raise ValueError("Cypher property name must be non-empty")
    return cypher_name(key, quoted=True)

cypher_name(name, *, quoted=False)

A label, relationship type, property key or alias as one Cypher token.

An identifier that is not a reserved word is written as is unless quoted; any other name is backtick-quoted with embedded backticks doubled, so a name taken from a schema can never end the token and add query text of its own.

Raises:

Type Description
ValueError

if name is empty.

Source code in graflo/db/cypher/escape.py
def cypher_name(name: str, *, quoted: bool = False) -> str:
    """A label, relationship type, property key or alias as one Cypher token.

    An identifier that is not a reserved word is written as is unless
    *quoted*; any other name is backtick-quoted with embedded backticks doubled,
    so a name taken from a schema can never end the token and add query text of
    its own.

    Raises:
        ValueError: if *name* is empty.
    """
    if not name:
        raise ValueError("a Cypher name must be non-empty")
    if not quoted and _IDENTIFIER.fullmatch(name) and name.upper() not in _RESERVED:
        return name
    return "`" + name.replace("`", "``") + "`"

cypher_names(names)

One relationship type, or several joined with |, each one token.

Source code in graflo/db/cypher/escape.py
def cypher_names(names: str | Sequence[str]) -> str:
    """One relationship type, or several joined with ``|``, each one token."""
    if isinstance(names, str):
        return cypher_name(names)
    return "|".join(cypher_name(name) for name in names)

cypher_neighbors_query(*, anchor_label, anchor_key_field='id', edge_type, far_label, direction, hops, limit, conditions=())

Render a bounded neighbourhood query.

The anchor values are not part of the text: bind the first as $anchor_id and each further one as $anchor_id_<n> (:func:anchor_param) when running the query.

Returns one row per reached node: its properties (far), its labels, and the relationships of every path that reached it (edges: type, properties, and each end's properties and labels). Grouping by the node is load-bearing: a graph with a cycle reaches the same node by several paths, and without it the row count, and what LIMIT counts, grows with path multiplicity rather than with neighbourhood size. The anchor itself is excluded, since a walk in both directions can come back to it.

Parameters:

Name Type Description Default
anchor_label str

Storage label of the anchor node.

required
anchor_key_field str | Sequence[str]

Property, or properties, the anchor is matched on.

'id'
edge_type str | Sequence[str] | None

Relationship type to follow, several to follow any of them, or None for any type.

required
far_label str | None

Storage label the reached node must carry, or None for any.

required
direction EdgeDirection

Orientation followed from the anchor.

required
hops int

Maximum hop distance.

required
limit int | None

Maximum reached nodes.

required
conditions Sequence[str]

Further predicates over path, anchor and far, ANDed into the WHERE clause.

()
Source code in graflo/db/cypher/traversal.py
def cypher_neighbors_query(
    *,
    anchor_label: str,
    anchor_key_field: str | Sequence[str] = "id",
    edge_type: str | Sequence[str] | None,
    far_label: str | None,
    direction: EdgeDirection,
    hops: int,
    limit: int | None,
    conditions: Sequence[str] = (),
) -> str:
    """Render a bounded neighbourhood query.

    The anchor values are not part of the text: bind the first as
    ``$anchor_id`` and each further one as ``$anchor_id_<n>``
    (:func:`anchor_param`) when running the query.

    Returns one row per reached node: its properties (``far``), its labels, and
    the relationships of every path that reached it (``edges``: ``type``,
    ``properties``, and each end's properties and labels). Grouping by the node
    is load-bearing: a graph with a cycle reaches the same node by several
    paths, and without it the row count, and what ``LIMIT`` counts, grows with
    path multiplicity rather than with neighbourhood size. The anchor itself is
    excluded, since a walk in both directions can come back to it.

    Args:
        anchor_label: Storage label of the anchor node.
        anchor_key_field: Property, or properties, the anchor is matched on.
        edge_type: Relationship type to follow, several to follow any of
            them, or None for any type.
        far_label: Storage label the reached node must carry, or None for any.
        direction: Orientation followed from the anchor.
        hops: Maximum hop distance.
        limit: Maximum reached nodes.
        conditions: Further predicates over ``path``, ``anchor`` and ``far``,
            ANDed into the ``WHERE`` clause.
    """
    if hops < 1:
        raise ValueError(f"hops must be >= 1, got {hops}")
    where = " AND ".join(["far <> anchor", *conditions])
    pattern = cypher_rel_pattern(edge_type, direction, min_hops=1, max_hops=hops)
    far = f"(far:{cypher_name(far_label)})" if far_label else "(far)"
    limit_clause = f"\nLIMIT {int(limit)}" if limit is not None else ""
    fields = (
        [anchor_key_field] if isinstance(anchor_key_field, str) else anchor_key_field
    )
    key = ", ".join(
        f"{cypher_name(field, quoted=True)}: ${anchor_param(i)}"
        for i, field in enumerate(fields)
    )
    anchor = cypher_name(anchor_label)
    far_column, labels_column, edges_column = NEIGHBOR_COLUMNS
    return (
        f"MATCH path = (anchor:{anchor} {{{key}}})"
        f"{pattern}{far}\n"
        f"WHERE {where}\n"
        "UNWIND relationships(path) AS _r\n"
        "WITH far, collect(DISTINCT _r) AS _rs\n"
        f"RETURN properties(far) AS {far_column}, labels(far) AS {labels_column}, "
        "[_e IN _rs | {type: type(_e), properties: properties(_e), "
        "start: properties(startNode(_e)), start_labels: labels(startNode(_e)), "
        "end: properties(endNode(_e)), end_labels: labels(endNode(_e))}] "
        f"AS {edges_column}"
        f"{limit_clause}"
    )

cypher_rel_pattern(edge_type, direction=EdgeDirection.OUT, *, variable='r', min_hops=None, max_hops=None)

Render the relationship pattern between two node patterns.

Parameters:

Name Type Description Default
edge_type str | Sequence[str] | None

Relationship type to filter on, several to match any of them, or None for any type. Each is written as one token.

required
direction EdgeDirection

Orientation followed from the left-hand (anchor) node.

OUT
variable str

Relationship variable name bound in the pattern.

'r'
min_hops int | None

Lower bound for a variable-length pattern. Defaults to 1 when only max_hops is given.

None
max_hops int | None

Upper bound for a variable-length pattern. Omitting both keeps the single-hop form, which is what every existing caller wants.

None

Returns:

Name Type Description
str str

e.g. -[r:KNOWS]-> (OUT), <-[r:KNOWS]- (IN),

str

-[r:KNOWS]- (ANY), -[r:KNOWS*1..3]-> (variable length).

Raises:

Type Description
ValueError

if the hop bounds are non-positive or inverted — an unbounded * pattern is a full-graph scan and is never emitted.

Source code in graflo/db/cypher/direction.py
def cypher_rel_pattern(
    edge_type: str | Sequence[str] | None,
    direction: EdgeDirection = EdgeDirection.OUT,
    *,
    variable: str = "r",
    min_hops: int | None = None,
    max_hops: int | None = None,
) -> str:
    """Render the relationship pattern between two node patterns.

    Args:
        edge_type: Relationship type to filter on, several to match any of
            them, or None for any type. Each is written as one token.
        direction: Orientation followed from the left-hand (anchor) node.
        variable: Relationship variable name bound in the pattern.
        min_hops: Lower bound for a variable-length pattern. Defaults to 1 when
            only *max_hops* is given.
        max_hops: Upper bound for a variable-length pattern. Omitting both keeps
            the single-hop form, which is what every existing caller wants.

    Returns:
        str: e.g. ``-[r:KNOWS]->`` (OUT), ``<-[r:KNOWS]-`` (IN),
        ``-[r:KNOWS]-`` (ANY), ``-[r:KNOWS*1..3]->`` (variable length).

    Raises:
        ValueError: if the hop bounds are non-positive or inverted — an
            unbounded ``*`` pattern is a full-graph scan and is never emitted.
    """
    left, right = _ARROWS[direction]
    quantifier = _hop_quantifier(min_hops, max_hops)
    body = (
        f"[{variable}:{cypher_names(edge_type)}{quantifier}]"
        if edge_type
        else f"[{variable}{quantifier}]"
    )
    return f"{left}{body}{right}"

cypher_string_literal(value)

Return a single-quoted Cypher string literal with escapes.

Source code in graflo/db/cypher/escape.py
def cypher_string_literal(value: str) -> str:
    """Return a single-quoted Cypher string literal with escapes."""
    return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"

partition_by_absent_merge_props(rows, prop_names, *, props_of, ends_of, union=())

Group edge rows by the identity properties each one lacks.

prop_names are the properties the edge's identity names beside its endpoints. Cypher refuses MERGE on a null property, so a row missing one (absent or None) cannot use the property MERGE. As on PostgreSQL (NULLS NOT DISTINCT), absence is part of the key: such a row matches an existing edge lacking the same properties. Rows lacking some are deduplicated on their endpoints and present merge values, later properties winning, because :func:rel_absent_upsert_clause cannot see edges created earlier in its own batch.

With union fields the complete group is deduplicated as well: one row per edge carries the union of its rows' members, so no MERGE has to see a row written earlier in its own batch.

Returns:

Type Description
list[tuple[tuple[str, ...], list[Any]]]

(absent names, rows) pairs; the group lacking nothing comes first.

Source code in graflo/db/cypher/rel_merge.py
def partition_by_absent_merge_props(
    rows: Sequence[Any],
    prop_names: Sequence[str],
    *,
    props_of: Callable[[Any], Mapping[str, Any] | None],
    ends_of: Callable[[Any], tuple[Any, Any]],
    union: Collection[str] = (),
) -> list[tuple[tuple[str, ...], list[Any]]]:
    """Group edge rows by the identity properties each one lacks.

    *prop_names* are the properties the edge's identity names beside its
    endpoints. Cypher refuses ``MERGE`` on a null property, so a row missing
    one (absent or ``None``) cannot use the property ``MERGE``. As on
    PostgreSQL (``NULLS NOT DISTINCT``), absence is part of the key: such a row
    matches an existing edge lacking the same properties. Rows lacking some are
    deduplicated on their endpoints and present merge values, later properties
    winning, because :func:`rel_absent_upsert_clause` cannot see edges created
    earlier in its own batch.

    With *union* fields the complete group is deduplicated as well: one row per
    edge carries the union of its rows' members, so no ``MERGE`` has to see a row
    written earlier in its own batch.

    Returns:
        ``(absent names, rows)`` pairs; the group lacking nothing comes first.
    """
    keys = _normalized_prop_names(prop_names)
    groups: dict[tuple[str, ...], list[Any]] = {}
    position: dict[tuple[tuple[str, ...], str], int] = {}
    for row in rows:
        props = props_of(row) or {}
        absent = tuple(k for k in keys if props.get(k) is None)
        group = groups.setdefault(absent, [])
        if not absent and not union:
            group.append(row)
            continue
        source, target = ends_of(row)
        ident = _key_text(
            [source, target, [props.get(k) for k in keys if k not in absent]]
        )
        at = position.get((absent, ident))
        if at is None:
            position[(absent, ident)] = len(group)
            group.append(row)
        else:
            group[at] = _merged_row(group[at], row, props_of, union)
    return sorted(groups.items(), key=lambda item: len(item[0]))

rel_absent_upsert_clause(relation_name, prop_names, absent, *, props_expr, source='source', target='target', union=(), union_expr='row[3]')

Upsert a relationship whose identity properties absent are missing.

Matches an existing relation_name edge between source and target whose present identity properties equal the row's and whose absent ones are unset, and updates it; creates one when none matches. Follows a MATCH binding source, target and row. union fields are read from union_expr and unioned with what the edge holds.

Source code in graflo/db/cypher/rel_merge.py
def rel_absent_upsert_clause(
    relation_name: str,
    prop_names: Sequence[str],
    absent: Sequence[str],
    *,
    props_expr: str,
    source: str = "source",
    target: str = "target",
    union: Sequence[str] = (),
    union_expr: str = "row[3]",
) -> str:
    """Upsert a relationship whose identity properties *absent* are missing.

    Matches an existing ``relation_name`` edge between *source* and *target*
    whose present identity properties equal the row's and whose *absent* ones are
    unset, and updates it; creates one when none matches. Follows a ``MATCH``
    binding *source*, *target* and ``row``. *union* fields are read from
    *union_expr* and unioned with what the edge holds.
    """
    rel = cypher_name(relation_name)
    conditions = []
    for key in _normalized_prop_names(prop_names):
        bk = cypher_map_key(key)
        if key in absent:
            conditions.append(f"existing.{bk} IS NULL")
        else:
            conditions.append(
                f"existing.{bk} = {props_expr}[{cypher_string_literal(key)}]"
            )
    return (
        f"OPTIONAL MATCH ({source})-[existing:{rel}]->({target})\n"
        f"WHERE {' AND '.join(conditions)}\n"
        "FOREACH (_ IN CASE WHEN existing IS NULL THEN [1] ELSE [] END |\n"
        f"    CREATE ({source})-[r:{rel}]->({target}) SET r += {props_expr}"
        f"{_union_set('r', union, union_expr)})\n"
        "FOREACH (_ IN CASE WHEN existing IS NULL THEN [] ELSE [1] END |\n"
        f"    SET existing += {props_expr}"
        f"{_union_set('existing', union, union_expr)})"
    )

rel_merge_props_map_from_row_index(prop_names, *, row_index=2)

Build `k`: row[n]['k'], ... for MERGE relationship properties.

Matches batches shaped as row = [source_doc, target_doc, props] (Neo4j, FalkorDB-style row[2]).

Source code in graflo/db/cypher/rel_merge.py
def rel_merge_props_map_from_row_index(
    prop_names: Sequence[str], *, row_index: int = 2
) -> str:
    """Build `` `k`: row[n]['k'], ... `` for MERGE relationship properties.

    Matches batches shaped as ``row`` = ``[source_doc, target_doc, props]`` (Neo4j,
    FalkorDB-style ``row[2]``).
    """
    row_access = f"row[{row_index}]"
    parts: list[str] = []
    for key in _normalized_prop_names(prop_names):
        bk = cypher_map_key(key)
        lit = cypher_string_literal(key)
        parts.append(f"{bk}: {row_access}[{lit}]")
    return ", ".join(parts)

rel_merge_props_map_from_row_props(prop_names, *, props_expr='row.props')

Build `k`: row.props['k'], ... (Memgraph-style batch rows).

Source code in graflo/db/cypher/rel_merge.py
def rel_merge_props_map_from_row_props(
    prop_names: Sequence[str], *, props_expr: str = "row.props"
) -> str:
    """Build `` `k`: row.props['k'], ... `` (Memgraph-style batch rows)."""
    parts: list[str] = []
    for key in _normalized_prop_names(prop_names):
        bk = cypher_map_key(key)
        lit = cypher_string_literal(key)
        parts.append(f"{bk}: {props_expr}[{lit}]")
    return ", ".join(parts)

rel_union_rows(rows, union)

[source, target, props] rows as [source, target, replaced, unioned].

The union fields move out of row[2] into row[3], so r += row[2] can never overwrite a stored list (:func:rel_upsert_clause).

Source code in graflo/db/cypher/rel_merge.py
def rel_union_rows(rows: Sequence[Any], union: Sequence[str]) -> list[list[Any]]:
    """``[source, target, props]`` rows as ``[source, target, replaced, unioned]``.

    The union fields move out of ``row[2]`` into ``row[3]``, so ``r += row[2]``
    can never overwrite a stored list (:func:`rel_upsert_clause`).
    """
    out: list[list[Any]] = []
    for row in rows:
        props = (row[2] if len(row) > 2 else None) or {}
        out.append(
            [
                row[0],
                row[1],
                {k: v for k, v in props.items() if k not in union},
                {k: props[k] for k in union if k in props},
            ]
        )
    return out

rel_upsert_clause(relation_name, prop_names, absent, *, union=(), props_expr='row[2]', union_expr='row[3]')

Upsert one group of :func:partition_by_absent_merge_props rows.

MERGE on the endpoints (and prop_names when the group has them all), or :func:rel_absent_upsert_clause when it lacks some. Follows a MATCH binding source, target and row. union fields are read from union_expr (:func:rel_union_rows) and written as the union of the stored list and the row's.

Source code in graflo/db/cypher/rel_merge.py
def rel_upsert_clause(
    relation_name: str,
    prop_names: Sequence[str],
    absent: Sequence[str],
    *,
    union: Sequence[str] = (),
    props_expr: str = "row[2]",
    union_expr: str = "row[3]",
) -> str:
    """Upsert one group of :func:`partition_by_absent_merge_props` rows.

    ``MERGE`` on the endpoints (and *prop_names* when the group has them all),
    or :func:`rel_absent_upsert_clause` when it lacks some. Follows a ``MATCH``
    binding ``source``, ``target`` and ``row``. *union* fields are read from
    *union_expr* (:func:`rel_union_rows`) and written as the union of the
    stored list and the row's.
    """
    if absent:
        return rel_absent_upsert_clause(
            relation_name,
            prop_names,
            absent,
            props_expr=props_expr,
            union=union,
            union_expr=union_expr,
        )
    rel = cypher_name(relation_name)
    if prop_names:
        map_clause = rel_merge_props_map_from_row_index(prop_names)
        pattern = f"MERGE (source)-[r:{rel} {{{map_clause}}}]->(target)"
    else:
        pattern = f"MERGE (source)-[r:{rel}]->(target)"
    return f"{pattern}\nSET r += {props_expr}" + _union_set("r", union, union_expr)