QueryingExpressions

Expressions

The following sections describe some of the other supported features.

String operators

Apart from comparison and concatenation operators Cypher provides special string operators for easier matching of substrings:

OperatorDescription
a STARTS WITH bReturns true if the prefix of string a is equal to string b.
a ENDS WITH bReturns true if the suffix of string a is equal to string b.
a CONTAINS bReturns true if some substring of string a is equal to string b.

For example, if you want to return the names of all Person nodes where the name starts with Joh the query would be:

MATCH (p:Person)
WHERE p.name STARTS WITH 'Joh'
RETURN p.name;

List operators

Cypher has operators to combine lists, check whether a list contains a value, and read one element or a range of elements:

OperatorDescription
a + bConcatenates lists a and b. If one side is a single value, it’s added to the start or end.
x IN listReturns true if list contains a value equal to x.
list[i]Returns the element at index i. Indexes start at 0, and negative indexes count from the end.
list[from..to]Returns the elements from index from up to, but not including, to. One bound can be omitted.

Concatenate lists

+ joins two lists, or adds a single value to the start or end of a list:

RETURN [1, 2] + [3, 4] AS combined, [1, 2] + 3 AS appended, 0 + [1, 2] AS prepended;
+--------------+--------------+--------------+
| combined     | appended     | prepended    |
+--------------+--------------+--------------+
| [1, 2, 3, 4] | [1, 2, 3]    | [0, 1, 2]    |
+--------------+--------------+--------------+

If either side is null, the result is null. To add a list as a single element, wrap it in another list:

RETURN [1, 2] + [[3, 4]] AS nested;
+----------------+
| nested         |
+----------------+
| [1, 2, [3, 4]] |
+----------------+

Check list membership

IN checks whether a list contains a value:

WITH ['admin', 'editor'] AS roles
RETURN 'editor' IN roles AS isEditor, 'owner' IN roles AS isOwner;
+----------+----------+
| isEditor | isOwner  |
+----------+----------+
| true     | false    |
+----------+----------+

If the value isn’t in the list and the list contains null, IN returns null instead of false. For how that affects filters, see comparisons with null.

RETURN 'owner' IN ['admin', null] AS notFound, 'admin' IN ['admin', null] AS found;
+----------+----------+
| notFound | found    |
+----------+----------+
| Null     | true     |
+----------+----------+

Access list elements

list[i] returns one element. An index outside the list returns null instead of raising an error:

WITH ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] AS days
RETURN days[0] AS first, days[-1] AS last, days[10] AS missing;
+---------+---------+---------+
| first   | last    | missing |
+---------+---------+---------+
| "Mon"   | "Fri"   | Null    |
+---------+---------+---------+

The index must be an integer or null. A null list or index returns null, and any other type raises an error:

WITH ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] AS days
RETURN days[1.5] AS day;
Expected an integer as a list index, got double.

Slice lists

list[from..to] returns a new list with the elements from index from up to, but not including, to. Leave out from to start at the beginning, or to to go to the end. Negative bounds count from the end:

WITH ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] AS days
RETURN days[1..3] AS middle, days[..2] AS firstTwo, days[-2..] AS lastTwo;
+----------------+----------------+----------------+
| middle         | firstTwo       | lastTwo        |
+----------------+----------------+----------------+
| ["Tue", "Wed"] | ["Mon", "Tue"] | ["Thu", "Fri"] |
+----------------+----------------+----------------+

Bounds outside the list are clamped to its ends, so a slice with no elements in range returns []:

WITH ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] AS days
RETURN days[3..10] AS clamped, days[7..9] AS empty;
+----------------+----------------+
| clamped        | empty          |
+----------------+----------------+
| ["Thu", "Fri"] | []             |
+----------------+----------------+

If the list or a bound is null, the slice returns null. Each bound must be an integer or null, and at least one bound is required. Otherwise, the query raises an error such as Expected an integer for a bound in list slicing, got double. or List slicing operator requires at least one bound.

Ordering comparisons

Comparing two values that have no order between them with <, <=, > or >=, such as a number and a string, returns null instead of raising an error. In a WHERE clause, null counts as false, so the filter leaves those rows out. Here, the sensor that reports a string is left out instead of failing the query:

CREATE (:Sensor {name: 'boiler', reading: 72}), (:Sensor {name: 'pump', reading: 'offline'});
MATCH (s:Sensor) WHERE s.reading > 50 RETURN s.name;
+----------+
| s.name   |
+----------+
| "boiler" |
+----------+

To sort values of different types, use ORDER BY; see order results.

Before Memgraph 3.14, comparing two values that can’t be ordered, or two booleans, raised an error.

Parameters

When automating the queries for Memgraph, it comes in handy to change only some parts of the query. Usually, these parts are values that are used for filtering results or similar, while the rest of the query remains the same.

Parameters allow reusing the same query but with different parameter values. They are indicated using the $ symbol followed by the parameter name (e.g., $name, $limit).

Memgraph does not support the old Cypher syntax using curly braces (e.g., {param}).

The parameters described here are client-supplied — they are sent with each query via the Bolt protocol and exist only for the duration of that query. If you need named values that persist across sessions, see Server-side parameters.

Below are some examples of the usage of parameters in Memgraph.

Common examples

Filtering node properties

MATCH (node {property: $propertyValue}) RETURN node;

Updating node properties

MATCH (n) SET n.propertyValue = $propertyNewValue;

Using parameters in LIMIT clauses

Memgraph also supports parameters in LIMIT clauses. For example:

MATCH (n) 
RETURN n 
LIMIT $limit;

Using parameters with LOAD CSV

Additionally, Memgraph supports parameters for LOAD CSV queries. For instance:

LOAD CSV FROM $file AS row 
CREATE (:Node {property: row.property});

Label parameterization

Starting from version 3.1, Memgraph allows node labels to be created using expressions of type String or List[String].

Static label parameterization

You can use parameters instead of any literal in the query. For example, if you want to filter nodes based on a specific label, you can execute the following query:

MATCH (n:$label)
RETURN n;

Dynamic label parameterization

You can dynamically assign multiple labels to a node using parameters:

MATCH (n)
SET n:$labels;

Given the following parameter:

{
  "labels": ["Person", "Student"]
}

Using property maps

Memgraph supports property maps in some clauses. For example:

Supported (e.g., in CREATE)

CREATE (n $propertyMap) 
RETURN n;

Not supported (e.g., in MATCH or MERGE):

MATCH (n $propertyMap) 
RETURN n;

Usage with Python driver

To use parameters with a Python driver, use the following syntax:

session.run(
   'CREATE (alice:Person {name: $name, age: $ageValue})',
   name='Alice', ageValue=22
).consume()

To do the same with labels:

session.run(
   'CREATE (alice:$label {name: $name, age: $ageValue})',
   label='Person', name='Alice', ageValue=22
).consume()

To use a property map as a parameter, you can use the following syntax:

session.run(
   'CREATE (alice:Person $propertyMap)', 
   propertyMap={"name": "Alice"}
).consume()

To use parameters whose names are integers, you will need to wrap parameters in a dictionary and convert them to strings before running a query:

session.run(
   'CREATE (alice:Person {name: $0, age: $1})',
   {'0': "Alice", '1': 22}
).consume()

To use parameters with some other driver, please consult the appropriate documentation.

CASE

Conditional expressions can be expressed in the Cypher language with the CASE expression. A simple form is used to compare an expression against multiple predicates. CASE returns the expression after THEN for the first predicate that matches. If none matches, it returns the expression after ELSE, or null if there’s no ELSE:

MATCH (n)
RETURN CASE n.currency WHEN "DOLLAR" THEN "$" WHEN "EURO" THEN "€" ELSE "UNKNOWN" END;

In generic form, you don’t need to provide an expression whose value is compared to predicates, but you can list multiple predicates and the first one that evaluates to true is matched:

MATCH (n)
RETURN CASE WHEN n.height < 30 THEN "short" WHEN n.height > 300 THEN "tall" END;

A WHEN predicate that evaluates to null counts as false, so its branch isn’t taken. See comparisons with null for which comparisons evaluate to null.

The exists() function and the EXISTS { … }, COUNT { … } and COLLECT { … } subquery expressions can all be used inside CASE.

Comparisons with null

null stands for a value that isn’t known, so most expressions that take null as input return null. A comparison with null returns null too: null = null and 1 <> null are both null. In a WHERE clause or a CASE predicate, null counts as false, so the row is filtered out or the branch isn’t taken. To test for a missing value, use IS NULL or IS NOT NULL.

The same applies to lists and maps that hold null: [null] = [null] is null, so a filter that compares a property with such a value matches nothing. IN compares with = too, so WHERE NOT (n.code IN ['A', 'B']) keeps no row where n.code is null. Before Memgraph 3.14, [null] = [null] returned true.

Pattern existence (exists(pattern))

exists(pattern) is a short form for a simple pattern existence check. It is accepted in the same positions as EXISTS { … } — see where you can use a subquery expression. For a dataset-backed example, see Filter with EXISTS expressions.

Subquery expressions (EXISTS, COUNT, COLLECT)

EXISTS { … } tests whether a subquery body produces any rows, COUNT { … } returns how many it produces, and COLLECT { … } gathers its single return column into a list. All three run the body once per row of the enclosing query and may correlate with the enclosing query’s variables. See Subquery expressions for the positions they are accepted in and the rules their bodies follow.

For EXISTS used specifically as a filter, see Existential subqueries in WHERE.

Pattern comprehension

Pattern comprehension is a syntactic construct available in Cypher for creating a list based on matchings of a pattern. A pattern comprehension matches the specified pattern like a normal MATCH clause, with predicates like a normal WHERE clause, but yields a custom projection as specified.

For example, if you want to get person names along with the release years and titles of all the movies with Matrix in their title that they are related to the query would be:

MATCH (n:Person)
RETURN n.name,
    [(n)-->(b:Movie) WHERE b.title CONTAINS 'Matrix' | b.released] AS years,
    [(n)-->(c:Movie) WHERE c.title CONTAINS 'Matrix' | c.title] AS titles;

For example, the following query finds person names with more than 5 characters, treats them as actors, and extracts the titles and releases years of the movies they’re linked to (provided those movies were released after the year 2000), then returns all this information as lists, alongside the corresponding actor’s name.

MATCH (n:Person) WHERE size(n.name) > 5
WITH
    n AS actor,
    [(n)-->(m) WHERE m.released > 2000 | m.title] AS titles,
    [(n)-->(m) WHERE m.released > 2000 | m.released] AS years
RETURN actor.name, years, titles;

The whole predicate, including the WHERE keyword, is optional and may be omitted.

Pattern comprehensions can be nested, for example [(n)-->(m) | [(m)-->(x) | x.id]] returns a list of lists.

You can also bind the matched path to a variable using the syntax [path = (a)-[r]->(b) | length(path)].

Pattern comprehension in WHERE clause

Pattern comprehension can also be combined with comprehension constructs inside the WHERE clause.

MATCH (n:Person)
WHERE single(x in [(n)-->(m) WHERE m.released > 2000 | m.title] WHERE true)
RETURN n.name;

Storing lists as properties

It is possible to store homogeneous lists of simple values as properties. For example, the following query creates a list from the title properties of the Movie nodes connected to Keanu Reeves. It then sets that list as a resume property on Keanu Reeves.

MATCH (keanu:Person {name: 'Keanu Reeves'})
WITH keanu,[(keanu)-->(b:Movie) | b.title] AS movieTitles
SET keanu.resume = movieTitles
RETURN keanu.resume;

It is not, however, possible to store heterogeneous lists as properties. For example, the following query, which tries to set a list including both the title and the released properties as the resume property of Keanu Reeves will fail. This is because the title property values are stored as STRING values, while the released property values are stored as INTEGER values.

MATCH (keanu:Person {name: 'Keanu Reeves'})
WITH keanu,[(keanu)-->(b:Movie) | b.title]  + [(keanu)-->(b:Movie) | b.released] AS movieTitles
SET keanu.resume = movieTitles
RETURN keanu.resume;

List comprehension

List comprehension is a syntactic construct in Cypher that allows for the creation of a new list by evaluating an expression over each element of an existing list, optionally filtering elements based on a predicate. This feature is particularly useful for transforming and filtering data within queries.

The general syntax for list comprehension in Cypher is:

[variable IN list [WHERE predicate] | expression]
  • variable: Represents each element in the original list.
  • list: The original list to iterate over.
  • predicate (optional): A condition that filters elements; only elements satisfying this condition are processed.
  • expression: An expression applied to each filtered element; the results form the new list.

When the predicate is null for an element, that element is skipped and the other elements are still returned, the same as when the predicate is false. A list that contains null, or a property that an element does not have, does not turn the whole result into null:

RETURN [x IN [1, null, 3] WHERE x > 0 | x] AS positives;
+-----------+
| positives |
+-----------+
| [1, 3]    |
+-----------+

If the list itself is null, the result is null.

Examples:

  1. Transforming a list:

    To create a list of squares from a list of numbers:

    RETURN [x IN [1, 2, 3, 4] | x * x] AS squares;
    +---------------+
    | squares       |
    +---------------+
    | [1, 4, 9, 16] |
    +---------------+
  2. Filtering a list:

    To filter out even numbers from a list:

    RETURN [x IN [1, 2, 3, 4] WHERE x % 2 <> 0] AS oddNumbers;
    +------------+
    | oddNumbers |
    +------------+
    | [1, 3]     |
    +------------+
  3. Combining transformation and filtering:

    To create a list of squares of even numbers:

    RETURN [x IN [1, 2, 3, 4] WHERE x % 2 = 0 | x * x] AS evenSquares;
    +-------------+
    | evenSquares |
    +-------------+
    | [4, 16]     |
    +-------------+
  4. Extracting node properties:

    Assuming a graph where Person nodes are connected to Movie nodes with an ACTED_IN relationship, to retrieve the titles of movies released after the year 2000 that a person named ‘Alice’ acted in:

    MATCH (alice:Person {name: 'Alice'})-[:ACTED_IN]->(movie:Movie)
    RETURN [m IN collect(movie) WHERE m.released > 2000 | m.title] AS recentMovies;

    Result: A list of movie titles released after 2000 that ‘Alice’ acted in.