Built-in Functions

Cypher functions work in expressions such as RETURN, WITH, and WHERE. See Aggregating Data for functions that summarize multiple rows.

Use qualified names for built-ins that declare a namespace, such as duration.inDays() and point.distance(). Call length() and other unqualified functions without a prefix.

String Functions

Function Result
toUpper(text), toLower(text) Convert the case of a string. upper and lower are aliases.
trim(text), ltrim(text), rtrim(text) Remove whitespace from both ends, the start, or the end, respectively.
left(text, length), right(text, length) Take up to length characters from the start or end. The length must be a positive integer.
substring(text, start[, length]) Take a substring from a zero-based offset. Omit length to read through the end. The start and length must be non-negative integers. The result is clipped to the available characters.
replace(text, search, replacement) Replace every occurrence of a literal substring.
split(text, separator) Split on a literal separator and keep empty fields. An empty separator splits into individual Unicode code points.
reverse(value) Reverse a string or the elements of a list.
toString(value) Convert a number, boolean, or temporal value to text. A string is returned as supplied.

String positions and lengths count Unicode code points. A substring that starts beyond the end is empty. A null input string yields null. A non-null string requires valid integer bounds in left(), right(), and substring().

Strings compare and sort by Unicode code point. In string literals, use \u followed by four hexadecimal digits for a UTF-16 code unit or \U followed by eight hexadecimal digits for a Unicode scalar value. For example, '\U0001F600' represents '😀'. Unknown escapes and malformed Unicode escapes are invalid.

RETURN toUpper('hello') AS upperCase,
       substring('Hello, world!', 0, 5) AS prefix,
       split('a,,b,', ',') AS fields,
       reverse([1, 2, 3]) AS reversed

The values are 'HELLO', 'Hello', ['a', '', 'b', ''], and [3, 2, 1].

Numeric Functions

Function Result
abs(x) Absolute value, with an integer, floating-point, or decimal result according to the input type.
ceil(x), floor(x) Round up or down to a whole number, returned as a floating-point value.
round(x) Round to the nearest whole number as a floating-point value. Halfway values round toward positive infinity.
sign(x) Return the integer -1, 0, or 1 for a negative, zero, or positive input.
rand() Random floating-point value greater than or equal to zero and less than one.
e(), exp(x) Euler’s number and the exponential function with that base.
log(x), log10(x) Natural and base-10 logarithm.
sqrt(x) Square root as a floating-point value. A negative input yields null.
pi() The constant π.
sin(x), cos(x), tan(x), cot(x) Trigonometric functions with the angle in radians.
asin(x), acos(x), atan(x), atan2(y, x) Inverse trigonometric functions that return radians.
degrees(x), radians(x) Convert radians to degrees or degrees to radians.
toInteger(value) Convert a number or numeric string to a signed 64-bit integer, discarding any fractional part toward zero. Unparseable text and values whose truncated result falls outside the integer range yield null.
toFloat(value) Convert a number or numeric string to a floating-point value. Unparseable text yields null.

Numeric functions with arguments return null when an argument is null.

Integer literals and integer arithmetic use signed 64-bit values.

RETURN round(3.14) AS rounded, floor(3.14) AS down,
       ceil(3.14) AS up, sqrt(9) AS root,
       toInteger('-2.9') AS integerValue, toFloat('0.5') AS floatingValue

The values are 3.0, 3.0, 4.0, 3.0, -2, and 0.5.

Boolean Conversion and Null Handling

  • toBoolean(value) accepts a Boolean or text. It recognizes 'true' and 'false' without regard to case. Other strings and null values yield null. A value of any other type raises an error.
  • coalesce(value[, other, …]) evaluates arguments in order and returns the first non-null value. If every argument is null, it returns null.
RETURN toBoolean('TrUe') AS enabled, coalesce(null, 'untitled') AS title

The values are true and 'untitled'.

Temporal Functions

Dates and times

Function Value Example
date(value) Calendar date date('2023-05-18')
localtime(value) Time of day localtime('12:34:56.123456789')
time(value) Time of day with a UTC offset time('12:34:56+02:00')
localdatetime(value) Date and local time localdatetime('2023-05-18T12:34:56')
datetime(value) Date and time with a UTC offset or a named time zone datetime('2024-03-31T00:00:00.123456789[Europe/Stockholm]')

Constructors accept text or a map of components, for example date({year: 2024, month: 2, day: 29}). You can also convert a compatible temporal value, for example date(datetime('2023-05-18T12:34:56Z')). When text omits the zone or offset, time() and datetime() use the server’s default time zone.

Read components with dot notation. Available fields depend on the value’s type. Date fields include year, month, day, and dayOfWeek. Time fields include hour, minute, second, and nanosecond. Use .offset for the UTC offset of a time or datetime value, or .timezone for the stored time zone of a datetime value.

Clocks, truncation, and Unix time

The five date and time constructors use the statement clock when called with no arguments. Each also supports these explicit clocks, with an optional time zone argument such as 'UTC' or 'Europe/Stockholm'.

Variant Clock
.statement() Start time of the current statement.
.transaction() Start time of the current transaction.
.realtime() Current time when the function is evaluated.

Each constructor also has a .truncate(unit, value[, components]) variant. The unit is a string such as 'month', 'day', or 'minute'. Choose a unit supported by the result type. The optional map can override components below the truncation boundary.

datetime.fromEpoch(seconds, nanoseconds) and datetime.fromEpochMillis(milliseconds) construct a date-time in UTC. The map forms datetime({epochSeconds: seconds, nanosecond: nanoseconds}) and datetime({epochMillis: milliseconds}) accept epoch components as well. Read back .epochSeconds or .epochMillis from the result. timestamp() returns the statement start time as an integer in Unix epoch milliseconds.

RETURN date.truncate('month', date('2024-02-29')) AS monthStart,
       datetime.fromEpoch(0, 1).nanosecond AS nanos,
       datetime.fromEpochMillis(1).epochMillis AS millis,
       timestamp() = datetime.statement().epochMillis AS sameClock

The values are 2024-02-01, 1, 1, and true.

Durations

duration(value) constructs a duration from an ISO 8601 string such as 'P1DT24H' or a component map such as {days: 1, hours: 24}. Months, calendar days, and elapsed time are stored separately. Use component access such as .months, .days, or .seconds to read these values. Calendar and elapsed units are useful when adding a duration to a temporal value across time zone changes.

Function Result
duration.between(start, end) Difference in calendar months, calendar days, and elapsed time.
duration.inMonths(start, end) Difference in whole calendar months.
duration.inDays(start, end) Difference in whole calendar days.
duration.inSeconds(start, end) Elapsed time in seconds, including any fractional second.

The difference functions return durations. For example, one calendar month and 31 calendar days are distinct duration values.

WITH date('2023-05-18') AS fromDate, date('2023-06-18') AS toDate
RETURN duration.between(fromDate, toDate) AS calendarDuration,
       duration.inDays(fromDate, toDate) AS dayDuration

The values are P1M and P31D. Polypheny sends dates, times, and durations created by Cypher temporal functions as ISO text over Prism.

List Functions

  • head(list) returns the first element, or null for an empty or null list.
  • tail(list) returns the list after removing its first element. An empty list yields an empty list and a null list yields null.
  • last(list) returns the final element, or null for an empty or null list.
  • size(value) returns the number of elements in a list or Unicode code points in a string. A null input yields null.
  • collect(value) aggregates non-null values into a list.
  • range(start, end[, step]) generates integers from start up to and including end if the step lands on it. The default step is 1. A negative step generates descending values. If the step points away from the end, the result is empty. A zero step is invalid.
RETURN size([1, 2, 3]) AS listSize, size('A😀') AS textSize,
       range(1, 5) AS increasingValues, range(5, 1, -2) AS decreasingValues

The values are 3, 2, [1, 2, 3, 4, 5], and [5, 3, 1].

List indices start at zero. A negative index counts back from the end. An index outside the list returns null. A slice includes the lower bound and excludes the upper bound. Omitting a bound selects from the beginning or to the end. Negative slice bounds count back from the end. The evaluated bounds are clamped between zero and the list length. An end at or before the start yields an empty list.

WITH [1, 2, 3] AS xs
RETURN xs[-1] AS tail, xs[..1] AS prefix, xs[1..] AS suffix

The result is 3, [1], and [2, 3]. Indices and slice bounds use integers. A null index or an explicit null slice bound returns null. These operations also work on the relationship list from a variable-length pattern.

List Comprehensions

Use [x IN list WHERE predicate | expression] to build a list in input order. The optional WHERE keeps items for which the predicate is true. The optional projection after | transforms each remaining item. With no projection, the comprehension returns the items themselves.

RETURN [n IN [1, 2, 3, 4] WHERE n % 2 = 0 | n * n] AS squares

The result is [4, 16]. A null input list yields null. An empty list or a filter with no matches yields []. The item binding is local to the comprehension and is visible inside existential subqueries in the filter or projection.

List Predicates

Use a Boolean expression after WHERE to test each list item. The item variable is local to the predicate.

Predicate Returns true when Empty list
all(x IN list WHERE predicate) Every item satisfies the predicate. true
any(x IN list WHERE predicate) At least one item satisfies the predicate. false
none(x IN list WHERE predicate) No item satisfies the predicate. true
single(x IN list WHERE predicate) Exactly one item satisfies the predicate. false

A null list produces null. If any predicate results are null, the result is null when the known results leave the outcome undecided. For example, one true result makes any() true, and two true results make single() false, even if another result is null.

RETURN all(x IN [] WHERE x > 0) AS allEmpty,
       any(x IN [null, 2] WHERE x > 0) AS anyMatch,
       none(x IN [0, null] WHERE x > 0) AS noneUnknown,
       single(x IN [0, 2, 0] WHERE x > 0) AS singleMatch,
       single(x IN [2, null, 3] WHERE x > 0) AS singleMultiple

The values are true, true, null, true, and false.

Path Functions

Function Result
nodes(p) The path’s nodes in traversal order, including both endpoints.
relationships(p) The path’s relationships in traversal order.
rels(p) An alias for relationships(p).
length(p) The number of relationships in the path.
MATCH p = (:Person {name: 'Alice'})-[:KNOWS*]->(:Person)
RETURN nodes(p)[-1].name AS destination, relationships(p) AS links, length(p) AS hops

For a zero-hop path, the lists contain one node and zero relationships. Each function returns null when the path binding is null.

Shortest Paths

shortestPath() and allShortestPaths() measure path length by the number of relationships. Write one relationship pattern between the endpoints. Direction, relationship types, hop bounds, and property filters constrain the search. In a matching clause, shortestPath() chooses one minimum-length path for each endpoint pair. Use allShortestPaths() to get a row for every path tied for the minimum length.

To try the examples, create this graph in an empty graph namespace.

CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}),
       (c:Person {name: 'Carol'}),
       (a)-[:KNOWS {active: false}]->(b),
       (a)-[:KNOWS {active: true}]->(c),
       (c)-[:KNOWS {active: true}]->(b)

Attach WHERE to the MATCH or OPTIONAL MATCH that contains shortestPath() to filter candidates before path selection.

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
MATCH p = shortestPath((a)-[:KNOWS*]->(b))
WHERE all(r IN relationships(p) WHERE r.active)
RETURN length(p) AS hops

This query returns 2 with either MATCH or OPTIONAL MATCH on the second line. Moving the filter to a later WITH p WHERE … would first select the direct one-hop path and then discard it.

When no path qualifies, MATCH drops the row and OPTIONAL MATCH keeps it with a null path. Here Bob has no outgoing path to Alice, so the query returns one row with hops set to null.

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
OPTIONAL MATCH p = shortestPath((b)-[:KNOWS*]->(a))
RETURN length(p) AS hops

Multiple Patterns in One Clause

With one shortestPath() pattern in a matching clause, Polypheny selects one path for each input row, endpoint pair, and match of the other patterns in the clause. The patterns share the relationship uniqueness rule.

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
MATCH p = shortestPath((a)-[:KNOWS*]->(b)), (a)-[r:KNOWS]->()
RETURN length(p) AS hops, r.active AS otherActive
ORDER BY hops

This returns (1, true) and (2, false) for the same endpoint pair. When r is Alice’s relationship to Carol, p can use the direct relationship to Bob. When r is the direct relationship to Bob, p has to go through Carol.

With several shortestPath() patterns, Polypheny considers the endpoint pairs together and selects one combination of paths for each match of the other patterns. Among combinations that satisfy the whole clause, it minimizes the hop count of the first shortest-path pattern, then the next in the order written. If all hop counts tie, it returns one eligible combination.

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
MATCH p = shortestPath((a)-[:KNOWS*]->(b)),
      q = shortestPath((a)-[:KNOWS*]->(b))
RETURN length(p) AS pHops, length(q) AS qHops

The query returns (1, 2). Writing q first in the second MATCH gives it the direct route and changes the result to (2, 1).

Shortest Path as a Value

In a value expression, shortestPath() searches between two endpoint nodes already bound in the current row. The expression yields null if either endpoint is null or no path qualifies. This query returns the two-hop path through Carol by requiring active: true on every relationship.

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
RETURN shortestPath((a)-[:KNOWS* {active: true}]->(b)) AS path

With bound endpoints, allShortestPaths() returns a list as a value expression. It returns an empty list for disconnected endpoints and null when either endpoint is null.

Tied Shortest Paths

After running the examples above, add a second active route between Alice and Bob.

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
CREATE (a)-[:KNOWS {active: true}]->(:Person {name: 'Dana'})-[:KNOWS {active: true}]->(b)

Select paths that use active relationships on every hop.

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
MATCH p = allShortestPaths((a)-[:KNOWS* {active: true}]->(b))
RETURN nodes(p)[1].name AS via, length(p) AS hops
ORDER BY via

This returns Carol and Dana, each with a hop count of 2.

Vector Functions

There is one function to rank vector properties. The function expects exactly three arguments as shown below. The function’s result is an ordinary scalar, so it works in RETURN, WHERE and ORDER BY like any other value.

Syntax: vector_distance(vector1, vector2, vectorDistanceMetric)

Description: Returns a DOUBLE representing the distance between the two vector values based on the selected vectorDistanceMetric algorithm.

Arguments:

Name Type
vector1 list of numbers or booleans
vector2 list of numbers or booleans
vectorDistanceMetric [L1, L2, COSINE, INNER_PRODUCT, HAMMING, JACCARD, CHISQUARED, L2SQUARED]
  • Note that the HAMMING and JACCARD metrics require boolean lists and the others lists of numbers.
  • vectorDistanceMetric must be a string literal.

When using vector_distance, the distance calculations are never pushed down but are always computed inside Polypheny, even if the store supports it natively. This means that querying data stored on a PostgreSQL store with the pgvector extension will not result in a pushdown to this store, even when an SQL query of the same data would.

Example

MATCH (n:Order)
RETURN n.id, vector_distance(n.embedding, [1.0, 2.0, 3.0], 'L2') AS score
ORDER BY score ASC
LIMIT 10

This returns the IDs and L2 distances of up to ten Order nodes whose embedding values are closest to the query vector.

Other Functions

There are many other functions available in Cypher, for handling different types of data and operations. A few examples include:

  • TYPE: Return the type of a relationship.
    MATCH (a)-[r]->(b)
    RETURN TYPE(r)
    
  • id(value) returns the internal identifier of a node or relationship as a string.
  • labels(node) returns the node’s labels as a list of strings.
MATCH (p:Person { name: 'John Doe' })
RETURN id(p) AS personId, labels(p) AS personLabels

Graph Properties and Endpoints

Function Result
keys(value) The property or entry names of a node, relationship, or map.
properties(value) A map of the node or relationship properties, or the entries of a map.
startNode(r) The source node of the stored relationship r.
endNode(r) The target node of the stored relationship r.

Each function returns null for a null input. Map entries with null values remain in the result of properties(map) and their names appear in keys(map). Relationship endpoints follow the stored direction, even when a pattern traverses the relationship in reverse.

MATCH (b:Person)<-[r:KNOWS]-(a:Person)
RETURN keys(r) AS propertyNames, properties(r) AS relationshipProperties,
       startNode(r).name AS startName, endNode(r).name AS endName

Existence Predicates

exists(value.key) tests for a non-null property on a node, relationship, or map. A missing or null property, or a null owner, produces false. Values such as 0, false, and the empty string count as present.

exists(pattern) tests whether a relationship pattern matches for the current row. Any named variables in the pattern must already be in scope and have the expected type. Use anonymous nodes and relationships for additional positions. A pattern with no match, including one that requires a null binding, yields false.

MATCH (p:Person)
RETURN p.name AS person, exists(p.age) AS hasAge,
       exists((p)-[:KNOWS]->()) AS knowsSomeone

You can use a bare relationship pattern in WHERE or another Boolean context such as CASE WHEN. Use exists(pattern) to return the Boolean value directly. Use an EXISTS { … } subquery to check for rows from a query with its own clauses and variables.

© Polypheny GmbH. All Rights Reserved.