Build graph patterns ==================== .. meta:: :description: Explains how to describe nodes and relationships with labels, properties, variables, inline element predicates, chains, quantified path patterns and path selectors .. _variable: ``node()`` builds a node pattern, and the three relationship factories connect patterns into a chain. The variable is the pattern's identity: other code refers to the node through it, and a write clause can reuse an already-bound pattern as a relationship endpoint. ``name("p")`` builds that variable on its own, without a pattern. Every factory that takes a variable accepts it, so a clause can read a name that another clause introduced, and a later ``name("p")`` is the same variable as the ``name="p"`` on the pattern. The name is checked as an identifier, which is why a keyword or a name with a space renders backticked rather than failing. .. _expression: An expression is anything that can stand where Cypher expects a value: a variable, a property read such as ``person["display_name"]``, a parameter, a :ref:`literal ` or a function call. Expressions appear in filters, projections, function arguments and property maps. A pattern is not itself an expression. A named pattern stands in for its variable wherever one is needed, and an anonymous pattern has nothing to stand in. A project that wants each graph name declared once can use the opt-in :doc:`model guide `. Its declarations subclass the pattern classes described here, so every builder and rule on this page still applies. Build a node pattern -------------------- ``node()`` takes an optional primary label or label expression, an optional variable, an optional property map and an optional inline element predicate: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node("Person", name="p", properties={"email": param("email")}) statement = match(person).returning(person["display_name"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person {email: $email}) RETURN p.display_name The variable is optional. ``node("Movie")`` renders ``(:Movie)``, and using a pattern with no variable where an expression is expected raises ``DslError`` rather than generating a name: .. code-block:: python from cypher_dsl import node from cypher_dsl.errors import DslError try: node("Movie").as_expression() except DslError as error: print(error) .. code-block:: text An anonymous node pattern has no variable. Give the pattern a name before using it as an expression. Property values are expressions. ``param("email")`` renders ``$email``, and a bare string stays a literal value: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node( "Person", name="p", properties={"email": param("email"), "kind": "actor"}, ) statement = match(person).returning(person["display_name"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person {email: $email, kind: 'actor'}) RETURN p.display_name The map is snapshotted when the pattern is built, so changing the caller's dictionary afterwards does not change the pattern. A value that should read a variable needs ``name()`` or a property access, not a bare string. .. _reference-a-bound-node: Refer to a node without its label --------------------------------- Leave the label out to write ``(p)`` or ``()``. An unlabelled pattern matches a node of any label, so it is the form for a node the query does not filter by label. ``node(name="p")`` is the way to render a bare reference to a node the clause already holds. A repeated read occurrence is not treated as a reference by the renderer, so ``node("Person", name="p")`` states the label again rather than referencing the bound node. The first pattern declares the node and a later pattern names it: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node person = node("Person", name="p") acted = node(name="p").relationship_to(node("Movie"), "ACTED_IN") statement = match(person).match(acted).returning("p") renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (p:Person) MATCH (p)-[:ACTED_IN]->(:Movie) RETURN p A repeated read occurrence renders the label it carries, so ``node("Person", name="p")`` states the label again rather than referencing the bound node. The server decides whether the restatement is legal. To test a label on the bound node without restating it, use :func:`~cypher_dsl.has_label`: in ``MATCH`` the test can sit inline on the reference with :ref:`predicate= `, or in a clause ``WHERE``. A path selector can make the two differ. :ref:`Test a label on a bound node ` explains when. .. code-block:: python from cypher_dsl import Configuration, Renderer, has_label, match, node person = node("Person", name="p") statement = ( match(person) .optional_match(node(name="p").relationship_to(node("Movie"), "DIRECTED")) .where(has_label(person, "Director")) .returning("p") ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (p:Person) OPTIONAL MATCH (p)-[:DIRECTED]->(:Movie) WHERE p:Director RETURN p A dynamic label needs a newer release in this position than in the pattern: :ref:`Test labels and types in a filter or projection ` states the floor. Reading and writing differ here: a read pattern renders the label each occurrence carries, while a write pattern sends only the name of a bound node. :ref:`Reuse a bound pattern in a write ` states that rule, including the case where a ``WITH`` drops the name. .. _test-a-bound-node-label: Test a label on a bound node ---------------------------- A label reaches a query in two positions, and its placement decides when it runs. A label written on the pattern occurrence that introduces a node is tested while the pattern matches. :func:`~cypher_dsl.has_label` builds a predicate expression: placed in a clause ``WHERE`` it is applied to the rows the clause returns, while the inline :ref:`predicate= ` placement applies it while the pattern matches. Without a path selector the pattern label and the clause ``WHERE`` return the same rows. With a selector they can differ: the pattern label is applied before the selector picks a path, and a ``WHERE`` is applied afterwards, so it can discard the path the selector picked even though another path would have satisfied the filter. An inline :ref:`element predicate ` is applied while matching, like the pattern label. For ``ANY 1``, take a path from ``a`` to ``b`` whose interior ``p`` is written ``(p:Station)`` and then ``(p:Hub)``. Cypher reads the second label as a predicate applied while matching, so only a hub path competes for selection. ``WHERE p:Hub`` is applied to the chosen path instead, so a non-hub path can be picked and then discarded even though a hub path between the same endpoints exists. When the node is introduced by an earlier pattern, a label that must be tested before selection belongs on the occurrence that introduces it. When one path introduces the node and repeats it, write every term on the first occurrence and leave the later occurrence unlabelled: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, any_paths, label, match, name, node, path_phrase, ) start = node("Station", name="a") hub = node(label("Station") & label("Hub"), name="p") middle = node("Station", name="q") loop = ( start.relationship_to(hub, "LINK") .relationship_to(middle, "LINK") .relationship_to(node(name="p"), "LINK") .relationship_to(node("Station", name="b"), "LINK") ) statement = match( path_phrase(loop, variable=name("route"), selector=any_paths(1)) ).returning(name("route")) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH route = ANY 1 (a:Station)-[:LINK]->(p:Station&Hub)-[:LINK]->(q:Station)-[:LINK]->(p)-[:LINK]->(b:Station) RETURN route The first occurrence carries both label terms, so the pattern still requires a hub before the selector picks. The later ``node(name="p")`` is an unlabelled reference to the same interior node, and the endpoints ``a`` and ``b`` stay distinct. When the node is already bound before the selective path, test its label on the reference occurrence as an inline :ref:`element predicate ` built with :func:`~cypher_dsl.has_label`, so the label is applied while matching and before the selector picks. A quantified path pattern is the other place a predicate runs inside the pattern, because ``quantified(..., where=...)`` takes one over the whole repetition. :func:`~cypher_dsl.has_label` takes label terms, not the colon list ``with_labels()`` builds, so write the terms with ``&``. This example tests the two static labels on the same ``OPTIONAL MATCH``: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, has_label, label, match, node, ) person = node("Person", name="p") statement = ( match(person) .optional_match( node(name="p").relationship_to(node("Movie"), "ACTED_IN") ) .where(has_label(name("p"), label("Person") & label("Premium"))) .returning("p") ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (p:Person) OPTIONAL MATCH (p)-[:ACTED_IN]->(:Movie) WHERE p:Person&Premium RETURN p ``label("Person") & label("Premium")`` renders as ``p:Person&Premium``, which requires both labels. The ``Person`` term repeats the label the first clause bound. .. _element-predicate: Test an element during the match -------------------------------- ``predicate=`` attaches an inline filter to a node pattern or a relationship. It renders inside the delimiters, after the name, labels and property map. ``with_predicate`` returns a copy with one more predicate, so the original pattern is unchanged. Repeated calls combine the predicates in order with ``AND``: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, name, node, param person = node( "Person", name="p", properties={"uid": param("uid")}, predicate=name("p")["age"] >= 18, ) statement = match(person).returning(person["display_name"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person {uid: $uid} WHERE p.age >= 18) RETURN p.display_name A relationship takes the same argument after ``quantifier``. On a chain, ``with_predicate`` adds the predicate to its last relationship only: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, name, node person = node("Person", name="p") movie = node("Movie", name="m") series = node("Series", name="s") path = person.relationship_to(movie, "LIKED").relationship_to( series, name="r" ).with_predicate(name("r")["lead"]) statement = match(path).returning(name("p")) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person)-[:LIKED]->(m:Movie)-[r WHERE r.lead]->(s:Series) RETURN p A label on a repeated read occurrence renders as written. To test the label of a bound node without restating it while the pattern matches, put the test on the reference occurrence: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, has_label, match, name, node, ) person = node("Person", name="p") statement = ( match(person) .match( node(name="p").with_predicate(has_label(name("p"), "Director")) ) .returning(person["display_name"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (p:Person) MATCH (p WHERE p:Director) RETURN p.display_name The same argument sits on a relationship, where it renders inside the brackets. A quantified relationship keeps the predicate inside its arrows, so ``-[r:LINK WHERE r.delayed]->+`` renders, and the name remains a list outside the quantifier. On a node or relationship with no name, labels, type or property map, the delimiter holds ``WHERE`` alone, so ``(WHERE ...)`` and ``-[WHERE ...]->`` render with no leading space. The predicate reads the element's own name and every name the clause has in scope, including another element of the same pattern. A name outside that set is rejected when the statement is built. It filters while the pattern matches, before a path selector chooses paths. Without a selector the same condition in a clause ``WHERE`` returns the same rows, which covers ``ALL``. Under ``SHORTEST``, ``ALL SHORTEST`` or ``ANY`` the two can differ, because the clause ``WHERE`` is applied to the paths the selector returned: it can discard the chosen path even though another path would have satisfied it. ``MATCH`` and ``OPTIONAL MATCH`` accept an inline element predicate, including on a pattern with a path selector and on an element inside a quantified path pattern. ``CREATE`` and ``MERGE`` render one as written, and Neo4j decides whether the write accepts it. A path pattern expression built by :func:`~cypher_dsl.path_pattern` refuses one, because that grammar has no such position. Use ``EXISTS { MATCH ... }`` for a boolean test that needs one. A clause ``.where()`` and ``quantified(..., where=...)`` remain separate: they filter the clause's rows and the repetition respectively. The `fixed-length path manual `_ documents the syntax, and the `shortest path manual `_ states how a selector applies a pattern filter before it picks a path. Add labels to an existing pattern --------------------------------- ``with_labels`` returns a copy with additional labels, so two statements can share a base pattern and extend it differently: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node person = node("Person", name="p") statement = match(person.with_labels("Premium")).returning( person["display_name"] ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person:Premium) RETURN p.display_name Only static label names are de-duplicated: a duplicate or a label already present is ignored. A ``$()`` term is appended in call order and is never de-duplicated. The original pattern is unchanged. .. _label-expression: Match labels with an expression ------------------------------- A label expression is a predicate over a node's labels or a relationship's type, built from :func:`~cypher_dsl.label` terms and the dynamic label factories with ``&`` (both), ``|`` (either) and ``~`` (not, which renders as ``!``), plus the ``ANY_LABEL`` wildcard for ``%``. Python's operator precedence matches Cypher's: ``~`` binds tightest, then ``&``, then ``|``. Parentheses in Python group exactly the way they render: .. list-table:: :header-rows: 1 * - Python - Renders in a node pattern * - ``label("A")`` - ``:A`` * - ``label("A") & label("B")`` - ``:A&B`` * - ``label("A") | label("B")`` - ``:A|B`` * - ``~label("A")`` - ``:!A`` * - ``ANY_LABEL`` - ``:%`` * - ``label("A") & (label("B") | label("C"))`` - ``:A&(B|C)`` * - ``(label("A") & label("B")) & ~(label("B") & label("C"))`` - ``:A&B&!(B&C)`` * - ``~(~label("A"))`` - ``:!!A`` In a relationship detail the same term text follows the colon inside the brackets, so ``label("R") | label("S")`` renders ``-[:R|S]->``. .. code-block:: python from cypher_dsl import Configuration, Renderer, label, match, node pattern = node(label("Movie") | label("Person"), name="n") statement = match(pattern).returning(pattern["title"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (n:Movie|Person) RETURN n.title The same terms express relationship types. A relationship has exactly one type, so a union is the useful form, and ``ANY_LABEL`` matches any typed relationship: .. code-block:: python from cypher_dsl import Configuration, Renderer, label, match, node credits = node("Person", name="p").relationship_to( node("Movie"), label("ACTED_IN") | label("DIRECTED"), name="r" ) statement = match(credits).returning(credits["character"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person)-[r:ACTED_IN|DIRECTED]->(:Movie) RETURN r.character .. _dynamic-label: Dynamic labels decide the label or the relationship type at run time. ``dynamic_label`` writes ``$(...)``. ``label_any`` and ``label_all`` write ``$any(...)`` and ``$all(...)``: .. list-table:: :header-rows: 1 * - Python - Renders in a node pattern * - ``dynamic_label(param("label"))`` - ``:$($label)`` * - ``label_any(name("tags"))`` - ``:$any(tags)`` * - ``label_all(name("tags"))`` - ``:$all(tags)`` * - ``label("Person") & label_any(name("tags"))`` - ``:Person&$any(tags)`` Each factory takes an expression, never a bare string: wrap the value with ``param()``, ``name()`` or ``lit()``. ``$any()`` and ``$all()`` are read forms. In a read pattern a dynamic label combines with ``&`` or ``|``, while a write uses the colon form described in :doc:`writing`: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, label, label_any, match, node, param, ) pattern = node(label("Person") & label_any(param("tags")), name="n") statement = match(pattern).returning(pattern["display_name"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (n:Person&$any($tags)) RETURN n.display_name - ``node("A")`` and ``with_labels`` keep the colon form, ``:A`` and ``:A:B``, for label names. ``with_labels`` rejects a pattern whose labels are already a predicate expression. Combine the terms with ``&`` or ``|`` instead. - ``CREATE`` and ``MERGE`` attach labels, so they usually take label names and ``$()`` terms. A ``&``, ``|``, ``!`` or ``%`` term renders as given too, and Neo4j decides whether the write accepts it. ``$any()`` and ``$all()`` render as read forms. - The legacy ``:A|:B`` spelling is not a union: it is one type name, so it renders quoted and matches only a type with that literal name. The same terms test an element that is already bound, in an expression position such as ``WHERE`` or ``RETURN``: see :ref:`label expression predicates `. Connect two patterns -------------------- The three factories differ only in the arrow they render. ``relationship_to`` points away from the node they are called on, ``relationship_from`` points towards it, and ``relationship_with`` renders no arrow: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node("Person", name="p") movie = node("Movie", name="m") acted_in = person.relationship_to( movie, "ACTED_IN", name="r", properties={"since": param("since")} ) directed = person.relationship_from(movie, "DIRECTED", name="d") related = person.relationship_with(movie, "ACTED_IN") renderer = Renderer.get(Configuration(server_version="5.26")) outgoing = match(acted_in).returning(person["display_name"]) incoming = match(directed).returning(person["display_name"]) undirected = match(related).returning(person["display_name"]) print(renderer.render(outgoing).cypher) print(renderer.render(incoming).cypher) print(renderer.render(undirected).cypher) .. code-block:: cypher MATCH (p:Person)-[r:ACTED_IN {since: $since}]->(m:Movie) RETURN p.display_name MATCH (p:Person)<-[d:DIRECTED]-(m:Movie) RETURN p.display_name MATCH (p:Person)-[:ACTED_IN]-(m:Movie) RETURN p.display_name A chain is built from relationships. The variable is optional in read and write patterns alike, as the third line shows. The type is optional in a read pattern. Several types are written as one :ref:`label expression `. The three methods are the fluent form of ``relationship_pattern()``, which takes the same ``target``, ``relationship_type``, ``name``, ``properties``, ``quantifier`` and ``predicate`` arguments after a ``direction`` of ``RelationshipDirection.OUTGOING``, ``RelationshipDirection.INCOMING`` or ``RelationshipDirection.UNDIRECTED``. Use the factory when the direction is data, such as a table of edges or a request field, so the three cases stay one call site. .. _untyped-relationship: Omit ``relationship_type`` to match a relationship of any type. The arrow then renders bare, and the variable and property map stay optional inside the brackets: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node person = node("Person", name="p") movie = node("Movie", name="m") any_type = person.relationship_with(movie) named = person.relationship_to(movie, name="r") dated = person.relationship_from(movie, properties={"since": 1}) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(match(any_type).returning(movie["title"])).cypher) print(renderer.render(match(named).returning(movie["title"])).cypher) print(renderer.render(match(dated).returning(movie["title"])).cypher) .. code-block:: text MATCH (p:Person)--(m:Movie) RETURN m.title MATCH (p:Person)-[r]->(m:Movie) RETURN m.title MATCH (p:Person)<-[{since: 1}]-(m:Movie) RETURN m.title Extend a chain across relationships ----------------------------------- The factories on a relationship pattern extend the chain from its current endpoint, which is how a path across multiple relationships stays one pattern instead of several: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node person = node("Person", name="p") movie = node("Movie", name="m") series = node("Series", name="s") path = ( person.relationship_to(movie, "ACTED_IN") .relationship_to(series, "IN_SERIES") ) statement = match(path).returning(movie["title"], series["title"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person)-[:ACTED_IN]->(m:Movie)-[:IN_SERIES]->(s:Series) RETURN m.title, s.title Adjacent relationships must meet at the same node pattern object, so a chain cannot accidentally describe two different nodes with one name. Build chains by extending from the endpoint rather than by constructing relationships separately. .. _quantified-relationship: Quantify a relationship ----------------------- A relationship pattern followed by a quantifier repeats that relationship pattern a variable number of times. A supplied type constraint repeats with it, and an untyped relationship repeats without one. ``Quantifier`` builds the quantifier and the trailing ``quantifier`` argument attaches it. The quantifier follows the closing direction marker, ``->`` or ``-``, and applies to the relationship, not to the node patterns on either side. .. list-table:: :header-rows: 1 * - Python - Renders * - ``Quantifier.exactly(3)`` - ``{3}`` * - ``Quantifier.between(1, 5)`` - ``{1,5}`` * - ``Quantifier.at_least(2)`` - ``{2,}`` * - ``Quantifier.at_most(4)`` - ``{,4}`` * - ``Quantifier.zero_or_more()`` - ``*`` * - ``Quantifier.one_or_more()`` - ``+`` ``Quantifier.source_text()`` returns that text directly, so a caller that needs the quantifier's spelling does not repeat the factory rules. It is the text a pattern renderer writes. .. code-block:: python from cypher_dsl import Quantifier print(Quantifier.between(2, 2).source_text()) print(Quantifier(2, 2).source_text()) .. code-block:: text {2,2} {2} Every bound must be a non-negative integer that fits a Cypher integer, and a finite upper bound must be positive, so ``{0}`` and ``{0,0}`` are refused. A lower bound of zero stays valid, so ``{,4}`` repeats up to four times or not at all, and ``zero_or_more()`` writes the zero-or-more range in its short form. ``between`` keeps the closed-range spelling at equal bounds, so ``between(2, 2)`` renders ``{2,2}``. .. code-block:: python from cypher_dsl import Configuration, Quantifier, Renderer, match, node person = node("Person", name="p") friend = node("Person", name="f") knows = person.relationship_to( friend, "KNOWS", quantifier=Quantifier.between(1, 5) ) statement = match(knows).returning(person["name"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (p:Person)-[:KNOWS]->{1,5}(f:Person) RETURN p.`name` The same argument sits on ``relationship_from`` and ``relationship_with``, so an incoming or undirected quantified relationship renders ``<-[:KNOWS]-{2}`` or ``-[:KNOWS]-{,3}``. A quantified relationship can also sit in the middle of a chain, between two unquantified relationships. An inline :ref:`element predicate ` renders inside the brackets and stays inside the quantifier. A named quantified relationship is a group variable: it is a list of the relationships matched in each repetition. Use it in a list expression such as ``reduce`` or a comprehension. A later ``MATCH`` may name it again as a node or relationship. The server decides whether that is legal. A write clause renders the name as a plain reference, and Neo4j rejects an endpoint or an update target that holds a list. .. _quantified-path-pattern: Quantify a path pattern ----------------------- ``quantified`` wraps a whole relationship chain in parentheses and applies a quantifier to the repetition. The optional ``where`` argument is the quantified path pattern predicate, evaluated for each repetition. It reads the names inside the chain as singletons and may read names from the enclosing scope. .. code-block:: python from cypher_dsl import ( Configuration, Quantifier, Renderer, match, name, node, ) source = node("Station", name="s") target = node("Station", name="t") segment = source.relationship_to(target, "LINK") route = segment.quantified( Quantifier.between(1, 3), where=source["departs"] < target["departs"], ) statement = match(route).returning(name("s"), name("t")) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH ((s:Station)-[:LINK]->(t:Station) WHERE s.departs < t.departs){1,3} RETURN s, t Every named node and relationship inside the parentheses is a group variable outside them. In the example ``s`` and ``t`` are lists of the nodes matched in each repetition. The quantified path pattern predicate is the place where the same names are single nodes. A nested ``EXISTS``, comprehension or ``reduce`` can read them there, and the next clause sees the lists. Inside the pattern, each name stands for a single element. Every inner name becomes one list outside the parentheses. A name declared twice, or one an earlier clause bound, is written as given, and the server decides whether the repetition may restate it. To write one, start from the fixed path you would write without a quantifier. Identify the segment that repeats, build that segment as a chain, call ``quantified`` on it, and place it between the segments that do not repeat with ``path_phrase``. The nodes at the two ends of the repeated segment are the boundary nodes. Leave them anonymous unless you need the group list. Three points follow from the grammar: - Cypher does not allow a quantified path pattern to contain another quantified relationship. Put the repetition on the outer pattern. The DSL renders the nested form as written, and the server rejects it. - A name may repeat inside one quantified path pattern, including across two quantified relationships in the same statement. Each inner name is one list outside its parentheses, and an equijoin belongs outside a quantified path pattern. The server decides whether a repeated declaration is legal. - The complete path pattern should match at least one element. A path whose segments all allow zero repeats renders as written, and the server rejects it. A quantified path pattern with a lower bound of zero is useful when another segment anywhere in the same path has a positive minimum: a simple segment, or a quantified segment with a positive lower bound. Adjacent quantified segments are allowed, and the minimum is taken over the whole path. ``CREATE`` and ``MERGE`` render a quantified relationship or a quantified path pattern as written. Whether Neo4j accepts a quantified write is its check, so use a ``MATCH`` to traverse a variable-length path. .. _path-variable: Name a path ----------- ``path_phrase`` builds one path pattern. Its positional arguments are that pattern's segments, rendered next to each other in the order given. Each is a node pattern, a relationship chain or a quantified path pattern. ``variable`` names the whole path, and ``selector`` chooses which of its matches a ``MATCH`` returns. A single segment is a path pattern too, so naming a plain chain is the same call. A phrase without a selector renders none, so it returns every matching path. ``variable`` takes a ``name()``, never a bare string, so a later ``name("route")`` reads the same path: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, match, name, node, nodes, path_phrase, ) route = name("route") acted = node("Person", name="a").relationship_to(node("Movie"), "ACTED_IN") statement = match(path_phrase(acted, variable=route)).returning( route, nodes(route) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH route = (a:Person)-[:ACTED_IN]->(:Movie) RETURN route, nodes(route) ``nodes()``, ``relationships()`` and ``length()`` take the path. Any other function receives it through ``fn()`` unchecked. Two named paths may share one ``MATCH`` clause. Each phrase binds its own path, and a simple segment may refer to a node an earlier pattern in the same clause bound. That :ref:`reference ` carries no label: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, name, node, path_phrase person = node("Person", name="a") acted = person.relationship_to(node("Movie"), "ACTED_IN") statement = match( path_phrase(acted, variable=name("p")), path_phrase(node(name="a").relationship_to(node("Movie"), "ACTED_IN"), variable=name("q")), ).returning(name("p"), name("q")) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH p = (a:Person)-[:ACTED_IN]->(:Movie), q = (a)-[:ACTED_IN]->(:Movie) RETURN p, q .. _path-phrase: Trace a path across segments ---------------------------- A path pattern can concatenate a simple pattern, a quantified path pattern and another simple pattern. .. code-block:: python from cypher_dsl import ( Configuration, Quantifier, Renderer, match, node, path_phrase, ) start = node("Station", name="a") link = node("Station").relationship_to(node("Station"), "LINK") end = node("Station", name="d") statement = match( path_phrase(start, link.quantified(Quantifier.between(1, 2)), end) ).returning(end["name"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (a:Station) ((:Station)-[:LINK]->(:Station)){1,2} (d:Station) RETURN d.`name` A named node inside a quantified segment is a group variable. A name an earlier clause bound is not rejected, and Neo4j decides whether that restatement is legal. Leave it anonymous or give it a fresh name. A simple segment may refer to a node an earlier clause bound, without a label. Two simple path patterns can sit next to each other and render as written. The server rejects the result. Put them in one chain, or place a quantified path pattern between them. A node pattern is a simple segment, so a lower bound of zero can be written with a node segment beside it: .. code-block:: python from cypher_dsl import ( Configuration, Quantifier, Renderer, match, node, path_phrase, ) start = node("Station", name="s") optional = ( node("Station") .relationship_to(node("Station"), "LINK") .quantified(Quantifier.at_most(1)) ) end = node("Station", name="e") statement = match(path_phrase(start, optional, end)).returning(end["name"]) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (s:Station) ((:Station)-[:LINK]->(:Station)){,1} (e:Station) RETURN e.`name` .. _path-selector: Select which paths a ``MATCH`` returns -------------------------------------- A path selector decides which paths the pattern returns. ``selector`` takes one, and the selector comes after the name and before the segments. Every form but ``ALL`` must be the only pattern of its ``MATCH`` clause. .. list-table:: :header-rows: 1 * - Python - Renders * - ``shortest(2)`` - ``SHORTEST 2`` * - ``shortest(3, groups=True)`` - ``SHORTEST 3 GROUPS`` * - ``shortest(param("k"))`` - ``SHORTEST $k`` * - ``shortest(param("k"), groups=True)`` - ``SHORTEST $k GROUPS`` * - ``all_shortest()`` - ``ALL SHORTEST`` * - ``any_paths(3)`` - ``ANY 3`` * - ``any_paths(param("k"))`` - ``ANY $k`` * - ``all_paths()`` - ``ALL`` A count is a positive integer literal that fits a Cypher integer or a value built with :doc:`param() `. A literal renders inline. A parameter renders as ``$name`` and is recorded like any other parameter, bound or unbound. The selector does not validate the binding. The parameterised forms require Neo4j 2025.06 or later and Cypher 25. ``Language.AUTO`` selects the ``CYPHER 25`` prefix, ``Language.CYPHER_5`` refuses the statement, and ``Language.NONE`` omits the prefix while keeping the release floor. See :doc:`targets` for the language rules and the `shortest path manual `_ for how a selector chooses paths. .. code-block:: python from cypher_dsl import ( Configuration, Quantifier, Renderer, match, name, node, path_phrase, shortest, ) knows = node("Person", name="a").relationship_to( node("Person"), "KNOWS", quantifier=Quantifier.one_or_more() ) statement = match( path_phrase(knows, variable=name("p"), selector=shortest(2)) ).returning(name("p")) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH p = SHORTEST 2 (a:Person)-[:KNOWS]->+(:Person) RETURN p ``CREATE`` and ``MERGE`` render a path phrase as written, including its variable and selector. Neo4j decides whether the write accepts that form. .. _reuse-in-write: Reuse a bound pattern in a write -------------------------------- A pattern bound by a ``MATCH`` can be an endpoint of a relationship a ``CREATE`` or ``MERGE`` writes: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node person = node("Person", name="p") movie = node("Movie", name="m") statement = match(person).create(person.relationship_to(movie, "ACTED_IN")) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) CREATE (p)-[:ACTED_IN]->(m:Movie) A write pattern decides reference or declaration from the name alone. A node is a reference when its name is visible at the clause or was already written earlier in the same graph pattern. Any other node declares its name. A declaration renders its own labels and property map. A reference renders the bare name only. Because the decision is lexical, a repeat inside one ``CREATE`` renders the first occurrence as a declaration and the second as a reference: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node router = node("Router", name="a") peer = node("Router", name="b") link = router.relationship_to(peer, "LINK") statement = match(router).create(link, link) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (a:Router) CREATE (a)-[:LINK]->(b:Router), (a)-[:LINK]->(b) A standalone write pattern follows the same rule. A name the preceding clauses bound is a reference, so the person stays a bare name while the company is declared: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node person = node("Person", name="p") company = node("Company", name="c") statement = match(person).merge(person.relationship_to(company, "WORKS_AT")) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) MERGE (p)-[:WORKS_AT]->(c:Company) A ``WITH`` that drops a name removes it from the visible set, so a write pattern after that ``WITH`` declares the name again and writes its labels: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node person = node("Person", name="p") movie = node("Movie", name="m") statement = ( match(person) .with_(person["uid"].alias("uid")) .create(person.relationship_to(movie, "LINK")) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WITH p.uid AS uid CREATE (p:Person)-[:LINK]->(m:Movie) The second ``(p:Person)`` is a new declaration, not the ``p`` from before the ``WITH``. That ``WITH`` dropped the name, so the write declares it again with the syntax the node carries. Keep the variable in the ``WITH`` when the write must reference the earlier ``p``. In a read pattern, every occurrence renders the name and label it was given. A repeated name is written as it appears, so ``MATCH (p:Person) MATCH (p:Person)`` restates the variable in the second pattern. The server decides whether that is legal. Write ``node(name="p")`` for a reference, and :ref:`test the label ` with ``has_label()`` in ``WHERE``. In a write pattern, a later occurrence of a bound name is a reference and sends only the name, so any labels or property map on that occurrence are not part of the query. The DSL drops that syntax before Neo4j sees the statement. What to watch out for --------------------- - A node pattern takes an optional label, and a name that cannot be an identifier is rejected when the pattern is built. A label on a name the clause already holds renders as given, or write an unlabelled reference and :ref:`test the label ` with an inline element predicate or in ``WHERE``. - A read pattern may leave the relationship type out (:ref:`untyped relationship `). A write pattern renders the type and direction it carries: an untyped relationship renders ``-->`` and an undirected one renders ``-[:TYPE]-``. The `CREATE manual `_ and the `MERGE manual `_ state the write rules. - A write pattern decides reference or declaration by name. A name visible at the clause, or already written earlier in the same graph pattern, renders as the bare reference, so its labels and property map are not sent. A new name declares its labels and property map. Endpoint legality is Neo4j's check on the text it receives. - A name that matches a Cypher keyword, such as ``role``, renders backticked. The renderer decides that, so the text stays valid without the caller tracking keywords. - A group variable is a list. A later ``MATCH`` may name it as an element again, and a write clause writes the name as a reference. Neo4j rejects an endpoint or update target that holds a list. - A quantified path pattern that nests a quantified relationship, or repeats a name inside itself, renders as written. The server decides whether the repetition is legal. - A quantified path pattern with a lower bound of zero needs another segment that always matches: a simple segment or a quantified segment with a positive lower bound. The minimum is taken over the complete path, and adjacent quantified segments are allowed. - ``CREATE`` and ``MERGE`` render both quantified forms as written. Whether the write accepts them is Neo4j's check, so use a ``MATCH`` to traverse. With pretty printing on, the layout keeps a group flat while it fits the 120-column width, so a pattern that fits stays on one line. A path phrase offers a break before each later segment, a relationship chain before each later relationship, and a ``MATCH`` pattern list before each later comma item. Each continuation is indented by two spaces per nesting level of the fragment that owns the break. A top-level ``MATCH`` chain sits at nesting level 0, so an overflowing chain continues at column 0. A comma list inside that clause adds one level, so its continuation starts two spaces in. A quantified path pattern writes its inline element predicate after the inner chain with spaces only, so the predicate is not a break position.