Read data ========= .. meta:: :description: Covers reading and filtering data with matches, conditions, projections, ordering, grouping and comprehensions Reading starts with ``match`` or ``optional_match`` and ends with ``returning``. Filters belong to the :ref:`clause ` they constrain, conditions are :ref:`expressions `, and projections can compute values instead of only naming variables. .. _match-several-patterns: Match several patterns at once ------------------------------ ``match`` accepts any number of comma-separated patterns: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node person = node("Person", name="p") movie = node("Movie", name="m") statement = match(person, movie).returning(person, movie) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person), (m:Movie) RETURN p, m A later ``match`` call extends the statement. The library renders the clauses in the order given and leaves the query-part rule to the server: the `WITH manual `_ states when a write-to-read boundary needs a ``WITH``. .. _optional-match: Keep rows that have no match ---------------------------- ``optional_match`` keeps the incoming rows when its pattern finds nothing, and a filter attached after it belongs to the optional match. The clause can start at a bound node, written as an unlabelled :ref:`reference `: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node("Person", name="p") movie = node("Movie", name="m") statement = ( match(person) .optional_match(node(name="p") .relationship_to(movie, "ACTED_IN", name="r")) .where(movie["title"] == param("title")) .returning(person["display_name"], movie["title"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) OPTIONAL MATCH (p)-[r:ACTED_IN]->(m:Movie) WHERE m.title = $title RETURN p.display_name, m.title .. _condition-builders: Build conditions with DSL operators ----------------------------------- Python cannot overload ``and``, ``or`` and ``not``, so conditions use ``&``, ``|``, ``^`` and ``~``. The table lists every condition builder: .. list-table:: :header-rows: 1 * - Python - Renders * - ``==``, ``!=`` - ``=``, ``<>`` * - ``<``, ``<=``, ``>``, ``>=`` - ``<``, ``<=``, ``>``, ``>=`` * - ``== None``, ``!= None`` - ``IS NULL``, ``IS NOT NULL`` * - ``&``, ``|``, ``^``, ``~`` - ``AND``, ``OR``, ``XOR``, ``NOT`` * - ``in_(value, collection)`` - ``value IN collection`` * - ``starts_with(value, prefix)`` - ``value STARTS WITH prefix`` * - ``ends_with(value, suffix)`` - ``value ENDS WITH suffix`` * - ``contains(value, substring)`` - ``value CONTAINS substring`` * - ``matches(value, pattern)`` - ``value =~ pattern`` * - ``condition(value)`` - ``value`` unchanged, for a boolean read from a parameter These conditions also stand inside a node or relationship pattern through ``predicate=``, which filters while the pattern matches. See :ref:`Test an element while the pattern matches ` for that placement and its effect on a path selector. Keep each comparison in its own parentheses, because Python binds ``&`` tighter than ``>``: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node("Person", name="p") statement = ( match(person) .where( (person["rating"] > param("min_rating", 4.0)) & (person["kind"] == "actor") ) .returning(person["display_name"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WHERE p.rating > $min_rating AND p.kind = 'actor' RETURN p.display_name The renderer adds parentheses where Cypher precedence requires them, so the text follows the Cypher precedence rules rather than the layout of the Python source. ``^`` builds ``XOR``, which is true when exactly one side is true. Python and Cypher give ``&``, ``^`` and ``|`` the same relative order, so grouping carries over between the two: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node("Person", name="p") statement = ( match(person) .where( (person["age"] > param("min_age", 30)) ^ (person["kind"] == "actor") ) .returning(person["display_name"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WHERE p.age > $min_age XOR p.kind = 'actor' RETURN p.display_name Comparing an expression with ``None`` builds ``IS NULL`` and ``IS NOT NULL``: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node("Person", name="p") statement = ( match(person) .where( (person["nickname"] == None) & (person["rating"] > param("min_rating", 4.0)) ) .returning(person["display_name"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WHERE p.nickname IS NULL AND p.rating > $min_rating RETURN p.display_name For a membership test, ``in_`` accepts a :ref:`literal ` collection, a parameter or a list of variables: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, in_, lit, list_, match, name, node, param, ) person = node("Person", name="p") left = node("Person", name="a") right = node("Person", name="b") renderer = Renderer.get(Configuration(server_version="5.26")) literal = ( match(person) .where(in_(person["kind"], lit(["actor", "director"]))) .returning(person) ) bound = ( match(person) .where(in_(person["kind"], param("kinds"))) .returning(person) ) variables = ( match(person, left, right) .where(in_(person["uid"], list_(left, right))) .returning(person) ) print(renderer.render(literal).cypher) print(renderer.render(bound).cypher) print(renderer.render(variables).cypher) .. code-block:: cypher MATCH (p:Person) WHERE p.kind IN ['actor', 'director'] RETURN p MATCH (p:Person) WHERE p.kind IN $kinds RETURN p MATCH (p:Person), (a:Person), (b:Person) WHERE p.uid IN [a, b] RETURN p String predicates build with ``starts_with``, ``ends_with`` and ``contains``. Each takes the expression to test and the text to look for, which may be a :ref:`literal `, a parameter or any expression: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, contains, ends_with, match, node, param, starts_with, ) person = node("Person", name="p") statement = ( match(person) .where(starts_with(person["uid"], param("prefix"))) .returning(person["uid"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WHERE p.uid STARTS WITH $prefix RETURN p.uid A regular expression match builds with ``matches``. The pattern is an ordinary :ref:`literal `, a parameter or any expression: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, match, matches, node, param, ) person = node("Person", name="p") statement = ( match(person) .where(matches(person["email"], param("pattern"))) .returning(person["uid"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WHERE p.email =~ $pattern RETURN p.uid A parameter that already holds a boolean needs ``condition()``. The library does not infer server-side types, so the caller states that the value is a predicate: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, condition, match, node, param, ) person = node("Person", name="p") statement = ( match(person) .where(condition(param("active"))) .returning(person) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WHERE $active RETURN p ``boolean_operation(operator, left, right)`` joins two predicates when the operator is not written out. It takes ``"AND"``, ``"OR"`` or ``"XOR"`` and applies the same coercion and parenthesisation as ``&``, ``|`` and ``^``. Use it when the operator is data, or when a list of caller-supplied filters is folded with ``functools.reduce``: .. code-block:: python from functools import reduce from cypher_dsl import ( Configuration, Renderer, boolean_operation, match, node, param, ) person = node("Person", name="p") filters = [person["rating"] > param("min_rating"), person["uid"] != None] combined = reduce( lambda left, right: boolean_operation("AND", left, right), filters ) statement = ( match(person) .where(combined) .returning(person["display_name"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WHERE p.rating > $min_rating AND p.uid IS NOT NULL RETURN p.display_name .. _label-expression-predicate: Test labels and types --------------------- A :ref:`label expression ` also works in an expression position. ``has_label`` takes the element to test and one label or type name, or a label expression built from ``label()`` terms. The element is a named pattern or any expression, and a relationship is tested the same way as a node: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, has_label, label, match, node, ) person = node("Person", name="p") report = node("Person", name="c").relationship_to(person, name="r") statement = ( match(report) .where(has_label(person, label("Manager") | label("Director"))) .returning( person["uid"], has_label(report, "WORKS_FOR").alias("reports") ) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (c:Person)-[r]->(p:Person) WHERE p:Manager|Director RETURN p.uid, r:WORKS_FOR AS reports The predicate is an ordinary condition, so ``&``, ``|``, ``^`` and ``~`` combine it with other predicates, and a projection can return it under an alias. A dynamic term in the colon form is Cypher 25 only and arrived in Neo4j 2025.07. A 5.26 target and a ``CYPHER 5`` pin are refused, while ``Language.AUTO`` selects ``CYPHER 25`` once the declared release meets the floor. See :ref:`dynamic labels `: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, has_label, label_any, match, node, param, ) person = node("Person", name="p") statement = ( match(person) .where(has_label(person, label_any(param("tags")))) .returning(person["uid"]) ) renderer = Renderer.get( Configuration(server_version="2025.07", pretty_print=True) ) print(renderer.render(statement).cypher) .. code-block:: cypher CYPHER 25 MATCH (p:Person) WHERE p:$any($tags) RETURN p.uid ``is_labeled`` and ``is_not_labeled`` render the ``IS [NOT] LABELED`` form, which Neo4j 2026.04 introduced for Cypher 25. ``IS NOT LABELED`` negates the whole label expression, which differs from ``~`` on one term: ``p IS NOT LABELED A&B`` is false for a node with both labels, while ``p:!A&B`` asks for ``B`` without ``A``: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, is_labeled, is_not_labeled, match, node, ) person = node("Person", name="p") statement = ( match(person) .where(is_not_labeled(person, "CEO")) .returning(is_labeled(person, "Manager").alias("isManager")) ) renderer = Renderer.get( Configuration(server_version="2026.10", pretty_print=True) ) print(renderer.render(statement).cypher) .. code-block:: cypher CYPHER 25 MATCH (p:Person) WHERE p IS NOT LABELED CEO RETURN p IS LABELED Manager AS isManager A statement that uses one of the two selects the ``CYPHER 25`` prefix under ``Language.AUTO`` and is refused against an older release or a ``CYPHER 5`` pin. See :doc:`targets`. .. _type-predicate: Test a value's type ------------------- ``is_type`` and ``is_not_type`` render the ``IS [NOT] :: type`` predicate. The type name is a name, not Cypher text: one of the server's simple type names or their synonyms, such as ``INTEGER``, ``PROPERTY VALUE`` or ``LOCAL DATETIME``, rendered as written and never quoted. A closed union, a parametrised or postfix list type such as ``LIST<...>``, ``INTEGER LIST`` or ``VECTOR<...>``, and the ``IS TYPED`` spelling are refused at construction. ``raw()`` builds them. ``not_null=True`` appends ``NOT NULL``, which makes the tested type non-nullable: it excludes null, so a missing value fails the positive form: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, is_type, match, node, ) person = node("Person", name="p") statement = ( match(person) .where(is_type(person["uid"], "STRING", not_null=True)) .returning(person["uid"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (p:Person) WHERE p.uid IS :: STRING NOT NULL RETURN p.uid The negated form is the complement: with ``not_null`` it is true for a null value, because null is outside the non-nullable type. The predicate is a comparison-level condition, so ``&``, ``|``, ``^`` and ``~`` combine it with other predicates without extra parentheses, and a projection returns it under an alias. The operand is an expression read in the enclosing scope, such as a variable or a property read. .. _path-pattern-expression: Test whether a path exists -------------------------- A relationship chain can also act as a condition: ``path_pattern`` is true when the chain matches at least once. It is the concise counterpart of ``exists``, which can do everything a path pattern expression can and more, at the cost of a subquery body: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, lit, match, node, path_pattern, ) person = node("Person", name="p") works_for = person.relationship_to( node("Person", properties={"uid": lit("p1")}), "WORKS_FOR" ) statement = ( match(person) .where(~path_pattern(works_for) & (person["age"] > 30)) .returning(person["uid"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) WHERE NOT (p:Person)-[:WORKS_FOR]->(:Person {uid: 'p1'}) AND p.age > 30 RETURN p.uid Every named node and relationship in the chain must already be bound by an earlier clause. The expression declares no names, so a bare node pattern is not a path pattern expression at all. Test a node's labels with ``has_label`` instead. A path pattern is a condition here, so ``~`` negates it and ``&``, ``|`` and ``^`` combine it with other predicates. Name the path in ``MATCH`` when the paths are the result, and write ``~`` or a comparison when a boolean is the point. The renderer writes the bare pattern wherever the caller places it, including a projection. The `path pattern expression manual `_ defines the syntax for a boolean position. ``path_pattern`` refuses three forms: - A quantifier. The boolean pattern grammar has none, so build the quantified relationship or path pattern with ``match`` and wrap it in ``exists``. - An inline element predicate. Use ``exists`` over a ``MATCH`` body. - A pattern that binds its own names or holds clauses of its own. Use ``exists``. See :ref:`Test whether a subquery matches `. .. _unwind-with: Filter an UNWIND through WITH ----------------------------- ``unwind(values, name("item"))`` turns a collection into one row per element. The source is any expression, so a Python list is accepted as it stands, and the second argument is the ``name()`` each row binds. The clause may start a statement or follow one. ``WHERE`` attaches to a preceding ``MATCH``, ``OPTIONAL MATCH``, ``WITH`` or procedure call with ``YIELD``, so a predicate on unwound rows is added after a ``WITH`` projects the row variable: .. code-block:: python from cypher_dsl import Configuration, Renderer, name, param, unwind statement = ( unwind(param("rows"), name("item")) .with_(name("item")) .where(name("item") != None) .returning(name("item")) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher UNWIND $rows AS item WITH item WHERE item IS NOT NULL RETURN item .. _functions: Call functions -------------- ``fn`` calls a function by name, including dot-qualified names. Arguments accept literal values and expressions, and a bare string argument stays a literal: .. code-block:: python from cypher_dsl import Configuration, Renderer, fn, match, node person = node("Person", name="p") statement = ( match(person) .returning( fn("coalesce", person["nickname"], "unknown"), fn("point.distance", person["here"], person["there"]), ) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN coalesce(p.nickname, 'unknown'), point.distance(p.here, p.there) The library does not inspect installed procedures, and an unknown name may be a user-defined function, so ``fn()`` renders the name and arguments it is given. ``count`` and ``element_id`` have their own constructors, and ``count`` takes the explicit ``asterisk()``: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, asterisk, count, element_id, match, node, ) person = node("Person", name="p") statement = ( match(person) .returning( count(asterisk()), count(person["email"], distinct=True), element_id(person), ) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN count(*), count(DISTINCT p.email), elementId(p) ``element_id`` always renders ``elementId(n)``. ``fn("id", ...)`` keeps whatever name the caller supplied. For a function or operand the DSL does not model, :ref:`raw-expression` renders trusted text unchanged. ``nodes(path)``, ``relationships(path)`` and ``length(path)`` build the three path readers. Each takes exactly one argument, which the Python signature enforces: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, length, match, name, node, nodes, path_phrase, relationships, ) route = name("route") acted = node("Person", name="a").relationship_to(node("Movie"), "ACTED_IN") statement = match(path_phrase(acted, variable=route)).returning( nodes(route), relationships(route), length(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 nodes(route), relationships(route), length(route) ``nodes()``, ``relationships()`` and ``length()`` each take exactly one argument and refuse a different arity. The library checks the name is bound, not that it holds a path: a node variable passes and Neo4j rejects the call. A path passed to any other function goes through ``fn()`` unchecked. :ref:`raw-expression` covers syntax the library does not model. :ref:`Path names ` explain how a name keeps the path kind. .. _projection: Project, alias and widen ------------------------ A projection lists expressions in order. A bare string is a :ref:`variable ` name, a string value needs ``lit()``, and ``alias`` names a computed column: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node("Person", name="p") statement = ( match(person) .returning( "p", person["display_name"].alias("who"), param("requested_at"), ) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN p, p.display_name AS who, $requested_at ``asterisk()`` projects every name in scope, and ``returning`` can start a statement on its own, which renders a standalone ``RETURN``: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, asterisk, lit, match, node, returning, ) person = node("Person", name="p") widened = match(person).returning(asterisk()) constant = returning(lit(1)) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(widened).cypher) print(renderer.render(constant).cypher) .. code-block:: cypher MATCH (p:Person) RETURN * RETURN 1 .. _raw-projection: Use raw text in a projection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``raw()`` renders trusted Cypher text unchanged. The library does not parse the text or check the names, types or syntax inside it. A ``$name`` inside ``raw()`` is not collected in either ``parameters`` or ``unbound_parameters``, because the text is opaque. Use a parameter for values supplied by a caller. A bare raw item, such as ``with_(raw("p, true AS flag"))``, states no output name and makes the name list unknown. Structured items beside it keep the names they state. In that scope an unknown name passes the reference check, while a masked name is still rejected. The allowance belongs to that scope only: a later structured ``WITH`` states its names again and the checks resume. An independent ``CALL ()`` still checks its own body, and parameter and target checks on structured syntax still apply. The projection also forgets the earlier declarations. For example, a write endpoint that would render as ``(p)`` after ``with_(name("p"))`` renders as ``(p:Person)`` after ``with_(raw("p"))``, because the raw item left no visible name for the write to reference. Use a structured projection when a later write needs to reuse a bound endpoint. ``raw("true").alias("flag")`` states the output name separately from the raw text. The alias keeps the projection's output list known when every other item has a known name. It does not tell the library what the value is. .. _ordering-and-pagination: Deduplicate, order and paginate ------------------------------- ``distinct`` marks the projection, ``order_by`` appends ordering items, and one ``SKIP`` and one ``LIMIT`` position exist per projection: .. code-block:: python from cypher_dsl import Configuration, Renderer, desc, match, node, param person = node("Person", name="p") statement = ( match(person) .returning(person["display_name"], person["rating"]) .distinct() .order_by(desc(person["rating"])) .skip(param("offset")) .limit(param("limit")) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN DISTINCT p.display_name, p.rating ORDER BY p.rating DESC SKIP $offset LIMIT $limit ``DISTINCT`` marks the projection. Ordering and pagination items are expressions read in the projection's own output scope: they can name a projected item or its alias as well as a name visible before the projection. Cypher rejects an ordering that is invalid for the projection, as after ``DISTINCT`` or an aggregation, and the library does not check that. A bare expression in ``order_by`` sorts ascending without an ``ASC`` token, and a bare string names a projected or incoming name, as in a projection position. Use ``asc()`` when the token should appear: .. code-block:: python from cypher_dsl import Configuration, Renderer, asc, match, node person = node("Person", name="p") statement = ( match(person) .returning(person["display_name"]) .order_by(asc(person["rating"])) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN p.display_name ORDER BY p.rating ASC Pagination accepts an integer literal, including a negative one, or any expression whose runtime value the server decides. The sign is Neo4j's to assess, so a page size is usually a parameter. .. _group-by: Group explicitly ---------------- Cypher groups implicitly: every non-aggregating projection item is a grouping key. ``group_by`` names the keys instead, and ``group_by_all`` states that every non-aggregating item is a key. Both arrived in Neo4j 2026.07 for Cypher 25, so a statement that uses one selects the ``CYPHER 25`` prefix under ``Language.AUTO``: .. code-block:: python from cypher_dsl import Configuration, Renderer, count, match, node movie = node("Movie", name="m") statement = ( match(movie) .returning(movie["genre"].alias("genre"), count(movie).alias("films")) .group_by("genre") .order_by("genre") ) renderer = Renderer.get( Configuration(server_version="2026.10", pretty_print=True) ) print(renderer.render(statement).cypher) .. code-block:: cypher CYPHER 25 MATCH (m:Movie) RETURN m.genre AS genre, count(m) AS films GROUP BY genre ORDER BY genre A key may be a name the projection does not return, which implicit grouping cannot express. Such a key is not returned, so the result carries the aggregate alone: .. code-block:: python statement = ( match(movie) .returning(count(movie).alias("films")) .group_by(movie["year"]) ) print(renderer.render(statement).cypher) .. code-block:: cypher CYPHER 25 MATCH (m:Movie) RETURN count(m) AS films GROUP BY m.year A bare string in ``group_by`` is a variable name, as in a projection position. ``group_by`` and ``group_by_all`` work on both ``RETURN`` and ``WITH``. Repeated ``group_by`` calls append keys, and a projection takes one grouping form. The key is an expression. ``group_by`` refuses ``*``, an alias and an item that is not an expression, because those are not keys in any statement. It does not inspect what the expression contains: an aggregate, a path pattern expression or a qualified projected alias all render, and Neo4j rejects the combinations its grammar forbids. The projected alias ``genre`` is a key as a whole name, while ``GROUP BY genre.code`` is a key expression Neo4j accepts or rejects by its own rules. ``GROUP BY ALL`` without an aggregate is not the same as omitting the grouping: it removes duplicate rows over the projected items, which implicit grouping leaves in place. .. code-block:: python statement = ( match(movie) .returning(movie["genre"].alias("genre"), count(movie).alias("films")) .group_by_all() ) print(renderer.render(statement).cypher) .. code-block:: cypher CYPHER 25 MATCH (m:Movie) RETURN m.genre AS genre, count(m) AS films GROUP BY ALL Grouping makes the projection aggregating, so Cypher restricts ``ORDER BY``, ``SKIP``, ``LIMIT`` and the owning ``WITH`` filter to the projected names. The library closes the scope after the projection, so a later clause cannot read a name the projection dropped. It does not model aggregation, so an ungrouped filter beside an aggregate renders and Neo4j rejects it. Check such a statement with ``EXPLAIN`` before relying on it. .. _computed-values: Compute values in the projection -------------------------------- Arithmetic and string concatenation build expressions through the Python operators, and ``+`` concatenates strings in Cypher as well: .. code-block:: python from cypher_dsl import Configuration, Renderer, match, node, param person = node("Person", name="p") statement = match(person).returning( person["rating"] + 1, person["first_name"] + " " + person["last_name"], person["tags"][0], person["tags"][param("index")], ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN p.rating + 1, p.first_name + ' ' + p.last_name, p.tags[0], p.tags[$index] A string index on an expression reads a static property. An integer or expression index builds a subscript, which keeps a parameter a parameter instead of interpolating its text. ``concat`` renders the ``||`` operator, which the grammar groups with ``+`` and ``-``. Unlike ``+``, ``||`` joins only strings and converts nothing, which makes it the GQL-conformant form: .. code-block:: python from cypher_dsl import Configuration, Renderer, concat, match, node person = node("Person", name="p") statement = match(person).returning( concat(concat(person["first_name"], " "), person["last_name"]) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN p.first_name || ' ' || p.last_name ``map_`` builds a map value whose entries are expressions, which is how a projection shapes a result object: .. code-block:: python from cypher_dsl import Configuration, Renderer, lit, map_, match, node person = node("Person", name="p") statement = match(person).returning( map_({"uid": person["uid"], "kind": lit("person")}) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN {uid: p.uid, kind: 'person'} Map keys are names and keep their insertion order. A bare string as a map value stays a literal, so a variable value needs ``name()`` or a property read. See :doc:`parameters` for how literal and map values are snapshotted. .. _conditional-expression: Choose between values with CASE ------------------------------- A conditional expression chooses between values. ``case_when`` builds one ``WHEN condition THEN value`` branch, and ``case`` tests the branches in order and falls back to ``else_``, or to null when no fallback is given: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, case, case_when, match, node, ) person = node("Person", name="p") statement = match(person).returning( case( case_when(person["age"] < 18, "minor"), else_="adult", ) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: text MATCH (p:Person) RETURN CASE WHEN p.age < 18 THEN 'minor' ELSE 'adult' END The branch condition is a predicate, built with the DSL operators or wrapped with ``condition()``, and the branch value is an expression. A name that a preceding ``WITH`` no longer provides is rejected, except where a ``raw()`` projection leaves the names unknown. A CASE is an atom in the expression grammar, so it nests inside a branch without parentheses and needs none of its own. Only the searched form is built. The form that compares one operand against each branch is refused at construction, and ``raw()`` builds it. .. _map-projection: Project selected properties into a map -------------------------------------- ``map_projection`` reads a variable, which may hold a node, a relationship or a map at run time, and returns a map of the properties and entries it selects. The library checks the name rather than the value type. Property names are quoted by the identifier rules, entry values are expressions, and ``all_properties=True`` adds the ``.*`` selector before the others: .. code-block:: python from cypher_dsl import Configuration, Renderer, map_projection, match, node person = node("Person", name="p") statement = match(person).returning( map_projection( person, properties=("uid", "name"), entries={"total": person["a"] + person["b"] + person["c"]}, ) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN p{.uid, .`name`, total: p.a + p.b + p.c} The base is built from a named node or relationship pattern, or from a variable returned by ``name()``, and it reads the name the earlier clause bound. At least one selector is required. Cypher's bare variable selector renders here as the literal entry that maps the variable to itself, so ``entries={"m": name("m")}`` renders ``m: m``. Duplicate keys are rejected at construction, and a reserved key such as ``name`` is quoted in the rendered selector. .. _comprehensions: Iterate a list inside an expression ----------------------------------- ``list_comprehension`` and ``reduce`` iterate a list inside one expression. The comprehension binds its element variable, ``reduce`` binds an accumulator and an element variable, and neither name is visible outside the expression: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, list_comprehension, match, name, node, ) person = node("Person", name="p") statement = match(person).returning( list_comprehension( name("x"), person["roles"], where=name("x")["kind"] == "lead", result=name("x")["title"], ) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) RETURN [x IN p.`roles` WHERE x.kind = 'lead' | x.title] The predicate and the mapping expression are optional: without a mapping the kept element itself is the result. With neither option, the comprehension renders ``[x IN list]``, with no ``WHERE`` clause and no mapping expression, and does not filter anything. ``reduce`` folds a list into one value through a combining expression: .. code-block:: python from cypher_dsl import ( Configuration, Renderer, assign, match, name, node, reduce, ) person = node("Person", name="p") statement = match(person).set_( assign( person["score"], reduce( name("total"), 0, name("n"), person["ratings"], name("total") + name("n"), ), ) ) renderer = Renderer.get(Configuration(server_version="5.26")) print(renderer.render(statement).cypher) .. code-block:: cypher MATCH (p:Person) SET p.`score` = reduce(total = 0, n IN p.ratings | total + n) The source list is read in the enclosing scope. The comprehension's element name is visible only in the filter and the mapping. In ``reduce``, the initial value and source list are read in the enclosing scope, and the accumulator and element are visible only in the combining expression. .. _quantified-list-predicates: Test the elements of a list --------------------------- ``all_``, ``any_``, ``none`` and ``single`` build a quantified list predicate, which tests the elements of a list against a condition. Each renders as ``quantifier(x IN list WHERE condition)``, and the four differ in how many elements must satisfy the condition: - ``all_`` requires every element to satisfy it. - ``any_`` requires at least one element to satisfy it. - ``none`` requires no element to satisfy it. - ``single`` requires exactly one element to satisfy it. ``all_`` and ``any_`` carry a trailing underscore because ``all`` and ``any`` are Python builtins. The other two keep their Cypher spelling. The condition is required: a predicate answers a boolean, so it filters in ``WHERE`` and combines with ``&``, ``|``, ``^`` and ``~``. The source list is read in the enclosing scope, and the element variable is bound in the condition only, so it stays invisible to the clauses around the predicate and a source that reads the same name refers to the outer one. Neo4j evaluates the condition once per element. The library renders the predicate and does not evaluate it, so the cost of the condition is paid on the server for every element of the list. .. code-block:: python from cypher_dsl import ( Configuration, Renderer, all_, any_, name, node, none, returning, single, ) person = node("Person", name="p") ratings = person["ratings"] rating = name("rating") renderer = Renderer.get(Configuration(server_version="5.26")) every_high = match(person).returning(all_(rating, ratings, rating >= 4)) print(renderer.render(every_high).cypher) some_high = match(person).returning(any_(rating, ratings, rating >= 4)) print(renderer.render(some_high).cypher) no_high = match(person).returning(none(rating, ratings, rating >= 4)) print(renderer.render(no_high).cypher) one_high = match(person).returning(single(rating, ratings, rating >= 4)) print(renderer.render(one_high).cypher) .. code-block:: cypher MATCH (p:Person) RETURN all(rating IN p.ratings WHERE rating >= 4) MATCH (p:Person) RETURN any(rating IN p.ratings WHERE rating >= 4) MATCH (p:Person) RETURN none(rating IN p.ratings WHERE rating >= 4) MATCH (p:Person) RETURN single(rating IN p.ratings WHERE rating >= 4)