0% found this document useful (0 votes)
8 views

neo4j-com-docs-cypher-cheat-sheet-5-all-...

This document serves as a comprehensive cheat sheet for Cypher queries, detailing the structure and syntax for read, write, and read-write operations in Neo4j. It includes examples of various query patterns, such as MATCH, OPTIONAL MATCH, CREATE, MERGE, and DELETE, along with explanations of clauses like WHERE, WITH, and RETURN. Additionally, it covers advanced topics like dynamic properties, variable-length patterns, and shortest path queries.

Uploaded by

anuragpanda222
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

neo4j-com-docs-cypher-cheat-sheet-5-all-...

This document serves as a comprehensive cheat sheet for Cypher queries, detailing the structure and syntax for read, write, and read-write operations in Neo4j. It includes examples of various query patterns, such as MATCH, OPTIONAL MATCH, CREATE, MERGE, and DELETE, along with explanations of clauses like WHERE, WITH, and RETURN. Additionally, it covers advanced topics like dynamic properties, variable-length patterns, and shortest path queries.

Uploaded by

anuragpanda222
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

Read Query

Cypher Cheat Sheet

Read Query Structure

Baseline for pattern search


[USE]
[MATCH [WHERE]]
operations.
[OPTIONAL MATCH [WHERE]]
USE clause.
[WITH [ORDER BY] [SKIP] [LIMIT]
MATCH clause.
[WHERE]]
OPTIONAL MATCH clause.
RETURN [ORDER BY] [SKIP] [LIMIT]
WITH clause.
RETURN clause.
Cypher keywords are not case-
sensitive.
Cypher is case-sensitive for
variables.

Match all nodes and return all


MATCH MATCH (n)
RETURN n
nodes.

Find all nodes with the Movie label.


MATCH (movie:Movie)
RETURN movie.title

Find the types of an aliased


MATCH (:Person {name: 'Oliver
Stone'})-[r]->()
relationship.
RETURN type(r) AS relType

Relationship pattern filtering on the


ACTED_IN relationship type. AI search
MATCH (:Movie {title: 'Wall
Street'})<-[:ACTED_IN]-
(actor:Person)
RETURN actor.name AS actor

Bind a path pattern to a path variable,


MATCH path = ()-[:ACTED_IN]->
(movie:Movie)
and return the path pattern.
RETURN path

Node labels and relationship types


MATCH (movie:$($label))
RETURN movie.title AS movieTitle
can be referenced dynamically in
expressions, parameters, and
variables when matching nodes and
relationships. The expression must
evaluate to a STRING NOT NULL |
LIST<STRING NOT NULL> NOT
NULL value.

Match nodes dynamically using a


CALL db.relationshipTypes()
YIELD relationshipType
variable.
MATCH ()-[r:$(relationshipType)]->
()
RETURN relationshipType, count(r)
AS relationshipCount

OPTIONAL MATCH

Use MATCH to find entities that must


MATCH (p:Person {name: 'Martin
Sheen'})
be present in the pattern. Use
OPTIONAL MATCH (p)-[r:DIRECTED]-> OPTIONAL MATCH to find entities
()
RETURN p.name, r that may not be present in the
pattern. OPTIONAL MATCH returns
null for empty rows.

WHERE can appear inside a


WITH 30 AS minAge
MATCH (a:Person WHERE a.name
node pattern in a MATCH
WHERE = 'Andy')-[:KNOWS]-> clause.
(b:Person WHERE b.age >
minAge)
RETURN b.name

WHERE can appear inside a pattern


MATCH (a:Person {name: 'Andy'})
RETURN [(a)-->(b WHERE b:Person) |
comprehension.
b.name] AS friends

To filter nodes by label, write a label


MATCH (n)
WHERE n:Swedish
predicate after the WHERE keyword
RETURN n.name, n.age using WHERE n:foo .

To filter on a node property, write


MATCH (n:Person)
WHERE n.age < 30
your clause after the WHERE
RETURN n.name, n.age keyword.

To filter on a relationship property,


MATCH (n:Person)-[k:KNOWS]->(f)
WHERE k.since < 2000
write your clause after the WHERE
RETURN f.name, f.age, f.email keyword.

You can use the boolean operators


MATCH (n:Person)
WHERE n.name = 'Peter' XOR (n.age
AND , OR , XOR , and NOT with the
< 30 AND n.name = 'Timothy') OR WHERE clause.
NOT (n.name = 'Timothy' OR n.name
= 'Peter')
RETURN
n.name AS name,
n.age AS age
ORDER BY name

Use the IS NOT NULL predicate to


MATCH (n:Person)
WHERE n.belt IS NOT NULL
only include nodes or relationships in
RETURN n.name, n.belt which a property exists.

As WHERE is not an independent


MATCH (n:Person)
WITH n.name as name
clause, its scope is not limited by a
WHERE n.age = 25 WITH clause directly before it.
RETURN name

Use WHERE to filter based on


MATCH
(timothy:Person {name:
patterns.
'Timothy'}),
(other:Person)
WHERE (other)-->(timothy)
RETURN other.name, other.age

To check if an element exists in a list,


MATCH (a:Person)
WHERE a.name IN ['Peter',
use the IN operator.
'Timothy']
RETURN a.name, a.age

Return a node.
MATCH (p:Person {name:
RETURN 'Keanu Reeves'})
RETURN p
Return relationship types.
MATCH (p:Person {name: 'Keanu
Reeves'})-[r:ACTED_IN]->(m)
RETURN type(r)

Return a specific property.


MATCH (p:Person {name: 'Keanu
Reeves'})
RETURN p.bornIn

To return all nodes, relationships and


MATCH p = (keanu:Person {name:
'Keanu Reeves'})-[r]->(m)
paths found in a query, use the *
RETURN * symbol.

Names of returned columns can be


MATCH (p:Person {name: 'Keanu
Reeves'})
aliased using the AS operator.
RETURN p.nationality AS
citizenship

DISTINCT retrieves unique rows for


MATCH (p:Person {name: 'Keanu
Reeves'})-->(m)
the returned columns.
RETURN DISTINCT m

The RETURN clause can use:


ORDER BY
SKIP
LIMIT
WHERE
You can create new variables to
MATCH (george {name:
'George'})<--(otherPerson)
store the results of evaluating
WITH otherPerson, expressions.
WITH toUpper(otherPerson.name) AS
upperCaseName
WHERE upperCaseName STARTS
WITH 'C'
RETURN otherPerson.name

You can use the wildcard * to carry


MATCH (person)-[r]->(otherPerson)
WITH *, type(r) AS connectionType
over all variables that are in scope, in
RETURN person.name, addition to introducing new variables.
otherPerson.name, connectionType

The WITH clause can use:


ORDER BY
SKIP
LIMIT
WHERE

Return the distinct union of all


MATCH (n:Actor)
RETURN n.name AS name
query results. Result column
UNION UNION types and names must match.
MATCH (n:Movie)
RETURN n.title AS name

Return the union of all query results,


MATCH (n:Actor)
RETURN n.name AS name
including duplicate rows.
UNION ALL
MATCH (n:Movie)
RETURN n.title AS name
Write query
Write-Only Query Structure

Baseline for write operations.


[USE]
[CREATE] CREATE clause.
[MERGE [ON CREATE ...] [ON MATCH MERGE clause.
...]] WITH clause.
[WITH [ORDER BY] [SKIP] [LIMIT] SET clause.
[WHERE]] DELETE clause.
[SET] REMOVE clause.
[DELETE] RETURN clause.
[REMOVE]
[RETURN [ORDER BY] [SKIP] [LIMIT]]

Read-Write Query Structure

Baseline for pattern search and write


[USE]
[MATCH [WHERE]]
operations.
[OPTIONAL MATCH [WHERE]] USE clause.
[WITH [ORDER BY] [SKIP] [LIMIT]
MATCH clause
[WHERE]]
OPTIONAL MATCH clause.
[CREATE]
CREATE clause
[MERGE [ON CREATE ...] [ON MATCH
...]]
MERGE clause.
[WITH [ORDER BY] [SKIP] [LIMIT] WITH clause.
[WHERE]] SET clause.
[SET] DELETE clause.
[DELETE] REMOVE clause.
[REMOVE] RETURN clause.
[RETURN [ORDER BY] [SKIP] [LIMIT]]
Create a node with the given
CREATE CREATE (n:Label {name:
$value})
label and properties.

Create a node with the given label


CREATE (n:Label $map)
and properties.

Create a relationship with the given


CREATE (n:Label)-[r:TYPE]->
(m:Label)
relationship type and direction; bind
a variable r to it.

Create a relationship with the given


CREATE (n:Label)-[:TYPE {name:
$value}]->(m:Label)
type, direction, and properties.

Node labels and relationship types


CREATE (greta:$($nodeLabels)
{name: 'Greta Gerwig'})
can be referenced dynamically in
WITH greta expressions, parameters, and
UNWIND $movies AS movieTitle
CREATE (greta)-[rel:$($relType)]-> variables when merging nodes and
(m:Movie {title: movieTitle}) relationships. The expression must
RETURN greta.name AS name,
labels(greta) AS labels, type(rel) evaluate to a STRING NOT NULL |
AS relType, collect(m.title) AS LIST<STRING NOT NULL> NOT
movies
NULL value.

Update or create a property.


SET SET e.property1 = $value1
Update or create several properties.
SET
e.property1 = $value1,
e.property2 = $value2

Dynamically set or update node


MATCH (n)
SET n[$key] = value
properties.

Dynamically set node labels.


MATCH (n)
SET n:$($label)

Set all properties. This will remove


SET e = $map
any existing properties.

Using the empty map ( {} ), removes


SET e = {}
any existing properties.

Add and update properties, while


SET e += $map
keeping existing ones.

Add a label to a node. This example


MATCH (n:Label)
WHERE n.id = 123
adds the label Person to a node.
SET n:Person

Match a pattern or create it if


MERGE (n:Label {name:
$value})
it does not exist. Use ON
ON CREATE SET n.created = CREATE and ON MATCH for
MERGE timestamp()
ON MATCH SET conditional updates.
n.counter =
coalesce(n.counter, 0) + 1,
n.accessTime = timestamp()

MERGE finds or creates a relationship


MATCH
(a:Person {name: $value1}),
between the nodes.
(b:Person {name: $value2})
MERGE (a)-[r:LOVES]->(b)

MERGE finds or creates paths


MATCH (a:Person {name: $value1})
attached to the node.

Node labels and relationship types


MERGE (greta:$($nodeLabels) {name:
'Greta Gerwig'})
can be referenced dynamically in
WITH greta expressions, parameters, and
UNWIND $movies AS movieTitle
MERGE (greta)-[rel:$($relType)]-> variables when merging nodes and
(m:Movie {title: movieTitle}) relationships. The expression must
RETURN greta.name AS name,
labels(greta) AS labels, type(rel) evaluate to a STRING NOT NULL |
AS relType, collect(m.title) AS
LIST<STRING NOT NULL> NOT
movies
NULL value.

Delete a relationship.
MATCH (n:Label)-[r]->

DELETE (m:Label)
WHERE r.id = 123
DELETE r

Delete all relationships.


MATCH ()-[r]->()
DELETE r

Delete a node and all relationships


MATCH (n:Label)
WHERE n.id = 123
connected to it.
DETACH DELETE n

Delete a node and a relationship. An


MATCH (n:Label)-[r]-()
WHERE r.id = 123 AND n.id = 'abc'
error will be thrown if the given node
DELETE n, r is attached to more than one
relationship.

Delete a relationship and return the


MATCH (n1:Label)-[r {id: 123}]->
(n2:Label)
number of relationships for each
CALL (n1) { node after the deletion. This example
MATCH (n1)-[r1]-()
RETURN count(r1) AS rels1 uses a variable scope clause
} (introduced in Neo4j 5.23) to import
CALL (n2) {
MATCH (n2)-[r2]-() variables into the CALL subquery. If
RETURN count(r2) AS rels2 you are using an older version of
}
DELETE r Neo4j, use an importing WITH
RETURN
clause instead.
n1.name AS node1, rels1 - 1 AS
relationships1,
n2.name AS node2, rels2 - 1 AS
relationships2

Delete all nodes and relationships


MATCH (n)
DETACH DELETE n
from the database.

Remove a label from a node.


MATCH (n:Label)
REMOVE WHERE n.id = 123
REMOVE n:Label

Dynamically remove node labels.


MATCH (n {name: 'Peter'})
REMOVE n:$($label)
RETURN n.name

Remove a property from a node.


MATCH (n:Label)
WHERE n.id = 123
REMOVE n.alias

Dynamically remove properties from


MATCH (n)
REMOVE n[$key]
nodes.

REMOVE cannot be used to remove


MATCH (n:Label)
WHERE n.id = 123
all existing properties from a node or
SET n = {} # REMOVE ALL properties relationship. All existing properties
can be removed from a node or
relationship by using the SET clause
with the property replacement
operator ( = ) and an empty map ( {} )
as the right operand.

Patterns
Fixed-length patterns

Match a node pattern including a


MATCH (n:Station WHERE n.name
STARTS WITH 'Preston')
WHERE clause predicate.
RETURN n

Match a fixed-length path pattern to


MATCH (s:Stop)-[:CALLS_AT]->
(:Station {name: 'Denmark Hill'})
paths in a graph.
RETURN s.departs AS departureTime

Variable-length patterns

Quantfied path pattern matching a


MATCH (:Station { name: 'Denmark
Hill' })<-[:CALLS_AT]-(d:Stop)
sequence of paths whose length is
((:Stop)-[:NEXT]->(:Stop)) constrained to a specific range (1 to 3
{1,3}
(a:Stop)-[:CALLS_AT]->
in this case) between two nodes.
(:Station { name: 'Clapham
Junction' })
RETURN d.departs AS departureTime,
a.arrives AS arrivalTime

Quantified relationship matching


MATCH (d:Station { name: 'Denmark
Hill' })<-[:CALLS_AT]-
paths where a specified relationship
(n:Stop)-[:NEXT]->{1,10} occurs between 1 and 10 times.
(m:Stop)-[:CALLS_AT]->
(a:Station { name:
'Clapham Junction' })
WHERE m.arrives < time('17:18')
RETURN n.departs AS departureTime

Quantified path pattern including a


MATCH (bfr:Station {name: "London
Blackfriars"}),
predicate.
(ndl:Station {name: "North
Dulwich"})
MATCH p = (bfr)
((a)-[:LINK]-(b:Station)
WHERE
point.distance(a.location,
ndl.location) >

point.distance(b.location,
ndl.location))+ (ndl)
RETURN reduce(acc = 0, r in
relationships(p) | round(acc +
r.distance, 2))
AS distance

Shortest paths

SHORTEST k finds the shortest


MATCH p = SHORTEST 1
(wos:Station)-[:LINK]-+
path(s) (by number of hops) between
(bmv:Station) nodes, where k is the number of
WHERE wos.name = "Worcester Shrub
Hill" AND bmv.name = "Bromsgrove" paths to match.
RETURN length(p) AS result

Find all shortest paths between two


MATCH p = ALL SHORTEST
(wos:Station)-[:LINK]-+
nodes.
(bmv:Station)
WHERE wos.name = "Worcester Shrub
Hill" AND bmv.name = "Bromsgrove"
RETURN [n in nodes(p) | n.name] AS
stops

SHORTEST k GROUPS returns all


MATCH p = SHORTEST 2 GROUPS
(wos:Station)-[:LINK]-+
paths that are tied for first, second,
(bmv:Station) and so on, up to the kth shortest
WHERE wos.name = "Worcester Shrub
Hill" AND bmv.name = "Bromsgrove" length. This example finds all paths
RETURN [n in nodes(p) | n.name] AS with the first and second shortest
stops, length(p) AS pathLength
lengths between two nodes.

The ANY keyword can be used to


MATCH path = ANY
(:Station {name: 'Pershore'})-
test the reachability of nodes from a
[l:LINK WHERE l.distance < 10]-+ given node(s). It returns the same as
(b:Station {name: 'Bromsgrove'})
RETURN [r IN relationships(path) | SHORTEST 1 , but by using the ANY
r.distance] AS distances keyword the intent of the query is
clearer.

Non-linear patterns

An equijoin is an operation on paths


MATCH (n:Station {name: 'London
Euston'})<-[:CALLS_AT]-(s1:Stop)
that requires more than one of the
-[:NEXT]->(s2:Stop)-[:CALLS_AT]- nodes or relationships of the paths to
>(:Station {name: 'Coventry'})
<-[:CALLS_AT]-(s3:Stop)-[:NEXT]- be the same. The equality between
>(s4:Stop)-[:CALLS_AT]->(n) the nodes or relationships is
RETURN s1.departs+'-'+s2.departs
AS outbound, specified by declaring a node
s3.departs+'-'+s4.departs AS variable or relationship variable more
`return`
than once. An equijoin on nodes
allows cycles to be specified in a
path pattern. Due to relationship
uniqueness, an equijoin on
relationships yields no solutions.

Multiple path patterns can be


MATCH (:Station {name:
'Starbeck'})<-[:CALLS_AT]-
combined in a comma-separated list
(a:Stop {departs: to form a graph pattern. In a graph
time('11:11')})-[:NEXT]->*(b)-
[:NEXT]->* pattern, each path pattern is matched
(c:Stop)-[:CALLS_AT]-> separately, and where node variables
(lds:Station {name: 'Leeds'}),
(b)-[:CALLS_AT]->(l:Station) are repeated in the separate path
<-[:CALLS_AT]-(m:Stop)-[:NEXT]->* patterns, the solutions are reduced
(n:Stop)-[:CALLS_AT]->
(lds), via equijoins.
(lds)<-[:CALLS_AT]-(x:Stop)-
View all (7 more lines)
[:NEXT]->*(y:Stop)-[:CALLS_AT]->
(:Station {name:

Clauses
CALL procedure

Standalone call to the procedure


CALL db.labels() YIELD label
db.labels to list all labels used in
the database. Note that required
procedure arguments are given
explicitly in brackets after the
procedure name.

Optionally CALL a procedure. Similar


MATCH (n)
OPTIONAL CALL
to OPTIONAL MATCH , any empty
apoc.neighbors.tohop(n, "KNOWS>", rows produced by the OPTIONAL
1)
YIELD node CALL will return null and not affect
RETURN n.name AS name, the remainder of the procedure
collect(node.name) AS connections
evaluation.

Standalone calls may use YIELD *


CALL db.labels() YIELD *
to return all columns.
Standalone calls may omit YIELD
CALL java.stored.procedureWithArgs
and also provide arguments implicitly
via statement parameters, e.g. a
standalone call requiring one
argument input may be run by
passing the parameter map {input:
'foo'} .

Calls the built-in procedure


CALL db.labels() YIELD label
RETURN count(label) AS db_labels
db.labels inside a larger query to
count all labels used in the database.
Calls inside a larger query always
requires passing arguments and
naming results explicitly with
YIELD .

A query ending in FINISH —


MATCH (p:Person)
instead of RETURN — has no
FINISH FINISH
result but executes all its side
effects.

FOREACH

FOREACH can be used to update


MATCH p=(start)-[*]->(finish)
WHERE start.name = 'A' AND
data, such as executing update
finish.name = 'D' commands on elements in a path, or
FOREACH (n IN nodes(p) | SET
n.marked = true) on a list created by aggregation. This
example sets the property marked
to true on all nodes along a path.

This example sets the property


MATCH p=(start)-[*]->(finish)
WHERE start.name = 'A' AND
marked to true on all relationships
finish.name = 'D' along a path.
FOREACH ( r IN relationships(p) |
SET r.marked = true )

This example creates a new node for


WITH ['E', 'F', 'G'] AS names
FOREACH ( value IN names | CREATE
each label in a list.
(:Person {name: value}) )

LIMIT constrains the number


MATCH (n)
ORDER BY n.name DESC
of returned rows. It can be
LIMIT SKIP 2 used in conjunction with ORDER
LIMIT 2
RETURN collect(n.name) AS BY and SKIP .
names

LIMIT can be used as a standalone


MATCH (n)
LIMIT 2
clause.
RETURN collect(n.name) AS names

LOAD CSV

LOAD CSV is used to import data


LOAD CSV FROM
'file:///artists.csv' AS row
from CSV files into a Neo4j database.
MERGE (a:Artist {name: row[1], This example imports the name and
year: toInteger(row[2])})
RETURN a.name, a.year year information of artists from a
local file.

LOAD CSV FROM 'https://data.neo4j.com/bands/artists.csv' AS row


MERGE (a:Artist {name: row[1], year: toInteger(row[2])})
RETURN a.name, a.year

Import artists name and year information from a remote file URL.

CSV columns can be referenced


LOAD CSV WITH HEADERS FROM
'file:///bands-with-headers.csv'
dynamically to map labels to nodes
AS line in the graph. This enables flexible
MERGE (n:$(line.Label) {name:
line.Name}) data handling, allowing labels to be
RETURN n AS bandNodes be populated from CSV column
values without manually specifying
each entry.

Load a CSV file in several


LOAD CSV WITH HEADERS FROM
'https://data.neo4j.com/importing-
transactions. This example uses a
cypher/persons.csv' AS row variable scope clause (introduced in
CALL (row) {
MERGE (p:Person {tmdbId: Neo4j 5.23) to import variables into
row.person_tmdbId}) the CALL subquery.
SET p.name = row.name, p.born =
row.born
} IN TRANSACTIONS OF 200 ROWS

Access line numbers in a CSV with


LOAD CSV FROM
'file:///artists.csv' AS row
the linenumber() function.
RETURN linenumber() AS number, row
Access the CSV file path with the
LOAD CSV FROM
'file:///artists.csv' AS row
file() function.
RETURN DISTINCT file() AS path

Load CSV data with headers.


LOAD CSV WITH HEADERS FROM
'file:///artists-with-headers.csv'
AS row
MERGE (a:Artist {name: row.Name,
year: toInteger(row.Year)})
RETURN
a.name AS name,
a.year AS year

Import a CSV using ; as field


LOAD CSV FROM 'file:///artists-
fieldterminator.csv' AS row
delimiter.
FIELDTERMINATOR ';'
MERGE (:Artist {name: row[1],
year: toInteger(row[2])})

ORDER BY

ORDER BY specifies how the output


MATCH (n)
RETURN n.name, n.age
of a clause should be sorted. It can
ORDER BY n.name be used as a sub-clause following
RETURN or WITH .

You can order by multiple properties


MATCH (n)
RETURN n.name, n.age
by stating each variable in the ORDER
ORDER BY n.age, n.name BY clause.
By adding DESC[ENDING] after the
MATCH (n)
ORDER BY n.name DESC
variable to sort on, the sort will be
SKIP 1 done in reverse order.
LIMIT 1
RETURN n.name AS name ORDER BY can be used in
conjunction with SKIP and LIMIT .

ORDER BY can be used as a


MATCH (n)
ORDER BY n.name
standalone clause.
RETURN collect(n.name) AS names

SHOW FUNCTIONS

List all available functions, returns


SHOW FUNCTIONS
only the default outputs ( name ,
category , and description ).

List built-in functions, can also be


SHOW BUILT IN FUNCTIONS YIELD *
filtered on ALL or USER-DEFINED .

Filter the available functions for the


SHOW FUNCTIONS EXECUTABLE BY
CURRENT USER YIELD *
current user.

Filter the available functions for the


SHOW FUNCTIONS EXECUTABLE BY
user_name
specified user.
SHOW PROCEDURES

List all available procedures, returns


SHOW PROCEDURES
only the default outputs ( name ,
description , mode , and
worksOnSystem ).

List all available procedures.


SHOW PROCEDURES YIELD *

List all procedures that can be


SHOW PROCEDURES EXECUTABLE YIELD
name
executed by the current user and
return only the name of the
procedures.

SHOW SETTINGS Neo4j Community Edition Neo4j Enterprise Edition

List configuration settings (within the


SHOW SETTINGS
instance), returns only the default
outputs ( name , value , isDynamic ,
defaultValue , and description ).

List configuration settings (within the


SHOW SETTINGS YIELD *
instance).

SHOW SETTINGS 'server.bolt.advertised_address',


'server.bolt.listen_address' YIELD *
List the configuration settings (within the instance) named
server.bolt.advertised_address and server.bolt.listen_address .
As long as the setting names evaluate to a string or a list of strings at runtime,
they can be any expression.

SHOW TRANSACTIONS

List running transactions (within the


SHOW TRANSACTIONS
instance), returns only the default
outputs ( database ,
transactionId , currentQueryId ,
connectionId , clientAddress ,
username , currentQuery ,
startTime , status , and
elapsedTime ).

List running transactions (within the


SHOW TRANSACTIONS YIELD *
instance).

List the running transaction (within


SHOW TRANSACTIONS 'transaction_id'
YIELD *
the instance), with a specific
transaction_id . As long as the
transaction IDs evaluate to a string or
a list of strings at runtime, they can
be any expression.

SKIP defines from which row


MATCH (n)
RETURN n.name
to start including the rows in
SKIP ORDER BY n.name the output. It can be used in
SKIP 1
LIMIT 2 conjunction with LIMIT and
ORDER BY .

SKIP can be used as a standalone


MATCH (n)
SKIP 2
clause.
RETURN collect(n.name) AS names

OFFSET can be used as a synonym


MATCH (n)
ORDER BY n.name
to SKIP .
OFFSET 2
LIMIT 2
RETURN collect(n.name) AS names

TERMINATE TRANSACTIONS

Terminate a specific transaction,


TERMINATE TRANSACTIONS
'transaction_id'
returns the outputs:
transactionId , username ,
message .

Terminal transactions allow for


TERMINATE TRANSACTIONS $value
YIELD transactionId, message
YIELD clauses. As long as the
RETURN transactionId, message transaction IDs evaluate to a string or
a list of strings at runtime, they can
be any expression.

List all transactions by the specified


SHOW TRANSACTIONS
YIELD transactionId AS txId,
user and terminate them. Return the
username transaction IDs of the transactions
WHERE username = 'user_name'
TERMINATE TRANSACTIONS txId that failed to terminate successfully.
YIELD message
WHERE NOT message = 'Transaction
terminated.'
RETURN txId

The UNWIND clause expands


UNWIND [1, 2, 3, null] AS x
UNWIND RETURN x, 'val' AS y
a list into a sequence of rows.
Four rows are returned.

Multiple UNWIND clauses can be


UNWIND $events AS event
MERGE (y:Year {year: event.year})
chained to unwind nested list
MERGE (y)<-[:IN]-(e:Event {id: elements.
event.id})
RETURN e.id AS x ORDER BY x Five rows are returned.

Create a number of nodes and


UNWIND [1, 2, 3, null] AS x
RETURN x, 'val' AS y
relationships from a parameter-list
without using FOREACH .

The USE clause determines


USE myDatabase
MATCH (n) RETURN n
which graph a query is
executed against. This example
USE assumes that the DBMS
contains a database named
myDatabase .
This example assumes that the
USE myComposite.myConstituent
MATCH (n) RETURN n
DBMS contains a composite
database named myComposite ,
which includes an alias named
myConstituent .

Subqueries
A CALL subquery is executed
UNWIND [0, 1, 2] AS x
CALL () {
once for each row. In this
CALL RETURN 'hello' AS example, the CALL subquery
innerReturn
} executes three times.
RETURN innerReturn

Variables are imported into a CALL


MATCH (t:Team)
CALL (t) {
subquery using a variable scope
MATCH (p:Player)-[:PLAYS_FOR]-> clause, CALL (<variable>) , or an
(t)
RETURN collect(p) as players importing WITH clause (deprecated).
} In this example, the subquery will
RETURN t AS team, players
process each Team at a time and
collect a list of all Player nodes.

Optionally CALL a subquery. Similar


MATCH (t:Team)
OPTIONAL CALL (t) {
to OPTIONAL MATCH, any empty
MATCH (p:Player)-[:PLAYS_FOR]-> rows produced by the OPTIONAL
(t)
RETURN collect(p) as players CALL will return null and not affect
} the remainder of the subquery
RETURN t AS team, players
evaluation.
CALL subqueries can be used to
CALL () {
MATCH (p:Player)
further process the results of a
RETURN p UNION query. This example finds the
ORDER BY p.age ASC
LIMIT 1 youngest and the oldest Player in
UNION the graph.
MATCH (p:Player)
RETURN p
ORDER BY p.age DESC
LIMIT 1
}
RETURN p.name AS name, p.age AS
age

CALL subqueries in transactions

CALL subqueries can execute in


LOAD CSV WITH HEADERS FROM
'https://data.neo4j.com/importing-
separate, inner transactions,
cypher/books.csv' AS row producing intermediate commits.
CALL (row) {
MERGE (b:Book {id: row.id,
title: row.title})
MERGE (a:Author {name:
row.author});
} IN TRANSACTIONS

LOAD CSV FROM 'https://data.neo4j.com/bands/artists.csv' AS line


CALL (line) {
MERGE (:Person {name: line[1], age: toInteger(line[2])})
} IN TRANSACTIONS OF 2 ROWS

Specify the number of rows processed in each transaction.

There are three different option flags


UNWIND [1, 0, 2, 4] AS i
CALL (i) {
to control the behavior in case of an
CREATE (n:Person {num: 100/i}) error occurring in any of the inner
RETURN n
} IN TRANSACTIONS OF 1 ROW ON transactions:
ERROR CONTINUE
ON ERROR CONTINUE - ignores a
RETURN n.num
recoverable error and continues
the execution of subsequent
inner transactions. The outer
transaction succeeds.
ON ERROR BREAK - ignores a
recoverable error and stops the
execution of subsequent inner
transactions. The outer
transaction succeeds.
ON ERROR FAIL - acknowledges
a recoverable error and stops
the execution of subsequent
inner transactions. The outer
transaction fails.

CALL subqueries can execute


LOAD CSV WITH HEADERS FROM
'https://data.neo4j.com/importing-
batches in parallel by appending IN
cypher/persons.csv' AS row [n] CONCURRENT TRANSACTIONS ,
CALL (row) {
MERGE (p:Person {tmdbId: where n is an optional concurrency
row.person_tmdbId}) value used to set the maximum
SET p.name = row.name, p.born =
row.born number of transactions that can be
} IN 3 CONCURRENT TRANSACTIONS OF
executed in parallel.
10 ROWS
RETURN count(*) AS personNodes

COUNT, COLLECT, and EXISTS

A COUNT subquery counts the


MATCH (person:Person)
WHERE COUNT { (person)-[:HAS_DOG]-
number of rows returned by the
>(:Dog) } > 1 subquery. Unlike CALL subqueries,
RETURN person.name AS name
variables introduced by the outer
scope can be used in EXISTS ,
COLLECT , and COUNT subqueries.

An EXISTS subquery determines if a


MATCH (person:Person)
WHERE EXISTS {
specified pattern exists at least once
MATCH (person)-[:HAS_DOG]-> in the graph. A WHERE clause can be
(dog:Dog)
WHERE person.name = dog.name used inside COLLECT , COUNT , and
} EXISTS patterns.
RETURN person.name AS name

A COLLECT subquery creates a list


MATCH (person:Person) WHERE
person.name = "Peter"
with the rows returned by the
SET person.dogNames = COLLECT { subquery. COLLECT , COUNT , and
MATCH (person)-[:HAS_DOG]->(d:Dog)
RETURN d.name } EXISTS subqueries can be used
RETURN person.dogNames as dogNames inside other clauses.

General
Operators

General
DISTINCT, ., []

Mathematical
+, -, *, /, %, ^
Comparison
=, <>, <, >, <=, >=, IS NULL, IS
NOT NULL

Boolean
AND, OR, XOR, NOT

String
+

List
+, IN, [x], [x .. y]

Regular expression
=~

String matching
STARTS WITH, ENDS WITH, CONTAINS

null is used to represent missing/undefined values.


null is not equal to null . Not knowing two values does not
imply that they are the same value. So the expression null =
null yields null and not true . To check if an expression is
null , use IS NULL .

null Arithmetic expressions, comparisons and function calls (except


coalesce ) will return null if any argument is null .

An attempt to access a missing element in a list or a property


that does not exist yields null .
In OPTIONAL MATCH clauses, nulls will be used for missing parts
of the pattern.

Create a node with label and


Labels CREATE (n:Person {name:
$value})
property.

Matches or creates unique node(s)


MERGE (n:Person {name: $value})
with the label and property.

Matches nodes labeled Person .


MATCH (n:Person)
RETURN n AS person

Checks the existence of the label


MATCH (n)
WHERE (n:Person)
Person on the node.

Matches nodes labeled Person with


MATCH (n:Person)
WHERE n.name = $value
the given property name .

Add label(s) to a node.


MATCH (n:Person {id: 123})
SET n:Spouse:Parent:Employee

The labels function returns the


MATCH (n {id: 123})
RETURN labels(n) AS labels
labels for the node.
Remove the label :Person from the
MATCH (n {id: 123})
REMOVE n:Person
node.

Properties

Neo4j only supports a subset of


MATCH (n {name: 'Alice'})
SET n += {
Cypher types for storage as
a: 1, singleton or array properties.
b: 'example',
c: true, Properties can be lists of numbers,
d: date('2022-05-04'), strings, booleans, temporal, or
e: point({x: 2, y: 3}),
f: [1, 2, 3], spatial.
g: ['abc', 'example'],
h: [true, false, false],
i: [date('2022-05-04'), date()],
j: [point({x: 2, y: 3}),
point({x: 5, y: 5})],
k: null
}

A map is not allowed as a property.


{a: 123, b: 'example'}

A list of maps are not allowed as a


[{a: 1, b: 2}, {c: 3, d: 4}]
property.

Collections containing collections


[[1,2,3], [4,5,6]]
cannot be stored in properties.

Collections containing null values


[1, 2, null]
cannot be stored in properties.

Literal lists are declared in


Lists RETURN ['a', 'b', 'c'] AS x
square brackets.

Literal lists are declared in square


WITH ['Alice', 'Neo', 'Cypher'] AS
names
brackets.
RETURN names

Lists can be passed in as parameters.


RETURN size($my_list) AS len

Lists can be passed in as parameters.


RETURN $my_list[0] AS value

range() creates a list of numbers


RETURN range($firstNum, $lastNum,
$step) AS list
(step is optional), other functions
returning lists are: labels() ,
nodes() , and relationships() .

The list of relationships comprising a


MATCH p = (a)-[:KNOWS*]->()
RETURN relationships(p) AS r
variable length path can be returned
using named paths and
relationships() .

List elements can be accessed with


RETURN list[$idx] AS value
idx subscripts in square brackets.
Invalid indexes return null .
Slices can be retrieved with intervals
RETURN list[$startIdx..$endIdx] AS
slice
from start_idx to end_idx , each
of which can be omitted or negative.
Out of range elements are ignored.

Pattern comprehensions may be


MATCH (a:Person)
RETURN [(a:Person)-->(b:Person)
used to do a custom projection from
WHERE b.name = 'Alice' | b.age] AS a match directly into a list.
list

Map projections may be easily


MATCH (n:Person)
RETURN n {.name, .age}
constructed from nodes,
relationships and other map values.

Literal maps are declared in


RETURN {name: 'Alice', age:
curly braces much like
Maps 20, address: {city:
'London', residential: property maps. Lists are
true}} AS alice
supported.

Map entries can be accessed by their


WITH {name: 'Alice', age: 20,
colors: ['blue', 'green']} AS map
keys. Invalid keys result in an error.
RETURN map.name, map.age,
map.colors[0]

Access the property of a nested map.


WITH {person: {name: 'Anne', age:
25}} AS p
RETURN p.person.name AS name
Maps can be passed in as
MERGE (p:Person {name: $map.name})
ON CREATE SET p = $map
parameters and used either as a map
or by accessing keys.

Nodes and relationships are returned


MATCH (matchedNode:Person)
RETURN matchedNode
as maps of their data.

Predicates

Use comparison operators.


n.property <> $value

Use functions.
toString(n.property) = $value

Use boolean operators to combine


n.number >= 1 AND n.number <= 10
predicates.

Check for node labels.


n:Person

Check if something is not null , e.g.


variable IS NOT NULL
that a property exists.

Either the property does not exist or


n.property IS NULL OR n.property =
$value
the predicate is true .
Non-existing property returns null ,
n.property = $value
which is not equal to anything.

Properties may also be accessed


n['property'] = $value
using a dynamically computed
property name.

String matching that starts with the


n.property STARTS WITH 'Neo'
specified string.

String matching that ends with the


n.property ENDS WITH '4j'
specified string.

String matching that contains the


n.property CONTAINS 'cypher'
specified string.

String matching that matches the


n.property =~ '(?i)neo.*'
specified regular expression. By
prepending a regular expression with
(?i) , the whole expression
becomes case-insensitive.

Ensure the pattern has at least one


(n:Person)-[:KNOWS]->(m:Person)
match.

Exclude matches to (n:Person)-


NOT (n:Person)-[:KNOWS]->
(m:Person)
[:KNOWS]→(m:Person) from the
result.

Check if an element exists in a list.


n.property IN [$value1, $value2]

List Expressions

A list of the value of the expression


[x IN list | x.prop]
for each element in the original list.

A filtered list of the elements where


[x IN list WHERE x.prop <> $value]
the predicate is true .

A list comprehension that filters a list


[x IN list WHERE x.prop <> $value
| x.prop]
and extracts the value of the
expression for each element in that
list.

Expressions
CASE expressions

The CASE expression can be used in


CASE n.eyes
WHEN 'blue' THEN 1
expression positions, for example as
WHEN 'brown' THEN 2 part of the WITH or RETURN clauses.
ELSE 3
END Return THEN value from the
matching WHEN value. The ELSE
value is optional, and substituted for
null if missing.

Return THEN value from the first


CASE
WHEN n.eyes = 'blue' THEN 1
WHEN predicate evaluating to true .
WHEN n.age < 40 THEN 2 Predicates are evaluated in order.
ELSE 3
END

A relationship type expression and a


MATCH (n)-[r]->(m)
RETURN
label expression can be used in a
CASE CASE expression.
WHEN n:A&B THEN 1
WHEN r:!R1&!R2 THEN 2
ELSE -1
END AS result

Label expressions

Node pattern using the OR ( | ) label


MATCH (n:Movie|Person)
RETURN n.name AS name, n.title AS
expression.
title

Node pattern using the negation ( ! )


MATCH (n:!Movie)
RETURN labels(n) AS label,
label expression.
count(n) AS labelCount

Relationship pattern using the OR


MATCH (:Movie {title: 'Wall
Street'})<-[:ACTED_IN|DIRECTED]-
( | ) label expression. As
(person:Person) relationships can only have exactly
RETURN person.name AS person
one type each, ()-[:A&B]→() will
never match a relationship.

Type predicate expressions

Verify that the property is of a


n.property IS :: INTEGER
certain type.

Verify that the property is of a


n.property IS :: INTEGER NOT NULL
certain type, and that it is not null .

Adding an exclamation mark after


n.property IS :: INTEGER!
the value type is a synonym to NOT
NULL . It can also be used to verify
that the property is of a certain
type and that it is not null .

Verify that the variable is not of a


variable IS NOT :: STRING
certain type.

Functions
Aggregating functions

The avg function returns the


MATCH (p:Person)
RETURN avg(p.age)
average of a set of INTEGER or
FLOAT values.

The avg duration function returns


UNWIND [duration('P2DT3H'),
duration('PT1H45S')] AS dur
the average of a set of DURATION
RETURN avg(dur) values.

The collect function returns a


MATCH (p:Person)
RETURN collect(p.age)
single aggregated list containing the
non- null values returned by an
expression.

The count function returns the


MATCH (p:Person {name: 'Keanu
Reeves'})-->(x)
number of values or rows. When
RETURN labels(p), p.age, count(*) count(*) is used, the function
returns the number of matching
rows.

The count function can also be


MATCH (p:Person)
RETURN count(p.age)
passed an expression. If so, it returns
the number of non- null values
returned by the given expression.

The max function returns the


MATCH (p:Person)
RETURN max(p.age)
maximum value in a set of values.

The min function returns the


MATCH (p:Person)
RETURN min(p.age)
minimum value in a set of values.

The percentileCont function


MATCH (p:Person)
RETURN percentileCont(p.age, 0.4)
returns the percentile of the given
value over a group, with a percentile
from 0.0 to 1.0 . It uses a linear
interpolation method, calculating a
weighted average between two
values if the desired percentile lies
between them.

The percentileDisc function


MATCH (p:Person)
RETURN percentileDisc(p.age, 0.5)
returns the percentile of the given
value over a group, with a percentile
from 0.0 to 1.0 . It uses a rounding
method and calculates the nearest
value to the percentile.

The stDev function returns the


MATCH (p:Person)
WHERE p.name IN ['Keanu Reeves',
standard deviation for the given
'Liam Neeson', 'Carrie Anne Moss'] value over a group. It uses a standard
RETURN stDev(p.age)
two-pass method, with N - 1 as the
denominator, and should be used
when taking a sample of the
population for an unbiased estimate.

The stDevP function returns the


MATCH (p:Person)
WHERE p.name IN ['Keanu Reeves',
standard deviation for the given
'Liam Neeson', 'Carrie Anne Moss'] value over a group. It uses a standard
RETURN stDevP(p.age)
two-pass method, with N as the
denominator, and should be used
when calculating the standard
deviation for an entire population.

The sum function returns the sum of


MATCH (p:Person)
RETURN sum(p.age)
a set of numeric values.

The sum duration function returns


UNWIND [duration('P2DT3H'),
duration('PT1H45S')] AS dur
the sum of a set of durations.
RETURN sum(dur)

Database functions

The db.nameFromElementId
WITH "2:efc7577d-022a-107c-a736-
dbcdfc189c03:0" AS eid
function returns the name of a
RETURN db.nameFromElementId(eid) database to which the element id
AS name
belongs. The name of the database
can only be returned if the provided
element id belongs to a standard
database in the DBMS.

Duration functions

The duration function can


UNWIND [
duration({days: 14, hours:16,
construct a DURATION from a MAP
minutes: 12}), of its components.
duration({months: 5, days: 1.5}),
duration({months: 0.75}),
duration({weeks: 2.5}),
duration({minutes: 1.5, seconds:
1, milliseconds: 123,
microseconds: 456, nanoseconds:
789}),
duration({minutes: 1.5, seconds:
1, nanoseconds: 123456789})
] AS aDuration
RETURN aDuration

The duration from a string


UNWIND [
duration("P14DT16H12M"),
function returns the DURATION value
duration("P5M1.5D"), obtained by parsing a STRING
duration("P0.75M"),
duration("PT0.75M"), representation of a temporal amount.
duration("P2012-02-
02T14:37:21.545")
] AS aDuration
RETURN aDuration

The duration.between function


UNWIND [
duration.between(date("1984-10-11"),
returns the DURATION value equal
date("1985-11-25")), to the difference between the two
duration.between(date("1985-11-25"),
date("1984-10-11")), given instants.
duration.between(date("1984-10-11"),
datetime("1984-10-
12T21:40:32.142+0100")),
duration.between(date("2015-06-24"),
localtime("14:30")),
duration.between(localtime("14:30"),
time("16:30+0100")),
View all (9 more lines)
duration.between(localdatetime("2015-
07-21T21:40:32.142"),

The duration.inDays function


UNWIND [
duration.inMonths(date("1984-10-11"),
returns the DURATION value
date("1985-11-25")), equal to the difference in whole
duration.inMonths(date("1985-11-25"),
date("1984-10-11")), days or weeks between the two
duration.inMonths(date("1984-10-11"), given instants.
datetime("1984-10-
12T21:40:32.142+0100")),
duration.inMonths(date("2015-06-24"),
localtime("14:30")),
duration.inMonths(localdatetime("2015-
07-21T21:40:32.142"),
View all (7 more lines)
localdatetime("2016-07-
21T21:45:22.142")),
The duration.inMonths function
UNWIND [
duration.inDays(date("1984-10-11"),
returns the DURATION value equal
date("1985-11-25")), to the difference in whole months
duration.inDays(date("1985-11-25"),
date("1984-10-11")), between the two given instants.
duration.inDays(date("1984-10-11"),
datetime("1984-10-
12T21:40:32.142+0100")),
duration.inDays(date("2015-06-24"),
localtime("14:30")),
duration.inDays(localdatetime("2015-
07-21T21:40:32.142"),
View all (7 more lines)
localdatetime("2016-07-
21T21:45:22.142")),

The duration.inSeconds function


UNWIND [
duration.inSeconds(date("1984-10-
returns the DURATION value equal to
11"), date("1984-10-12")), the difference in seconds and
duration.inSeconds(date("1984-10-
12"), date("1984-10-11")), nanoseconds between the two given
duration.inSeconds(date("1984-10- instants.
11"), datetime("1984-10-
12T01:00:32.142+0100")),
duration.inSeconds(date("2015-06-
24"), localtime("14:30")),
duration.inSeconds(datetime({year:
2017, month: 10, day: 29, hour: 0,
View all (3 more lines)
timezone: 'Europe/Stockholm'}),
datetime({year: 2017, month: 10,

Graph functions

The graph.names function returns a


RETURN graph.names() AS name
list containing the names of all
graphs on the current composite
database. It is only supported on
composite databases.

The graph.propertiesByName
UNWIND graph.names() AS name
RETURN name,
function returns a map containing
graph.propertiesByName(name) AS the properties associated with the
props
given graph. The properties are set
on the alias that adds the graph as a
constituent of a composite database.
It is only supported on composite
databases.

The graph.byName function


UNWIND graph.names() AS graphName
CALL () {
resolves a constituent graph by
USE graph.byName(graphName) name. It is only supported in the USE
MATCH (n)
RETURN n clause on composite databases.
}
RETURN n

The graph.byElementId function


USE graph.byElementId("4:c0a65d96-
4993-4b0c-b036-e7ebd9174905:0")
is used in the USE clause to resolve a
MATCH (n) RETURN n constituent graph to which a given
element id belongs. If the constituent
database is not a standard database
in the DBMS, an error will be thrown.

List functions

The keysfunction returns a


MATCH (a) WHERE a.name = 'Alice'
RETURN keys(a)
LIST<STRING> containing the
STRING representations for all the
property names of a NODE ,
RELATIONSHIP , or MAP .
The labels function returns a
MATCH (a) WHERE a.name = 'Alice'
RETURN labels(a)
LIST<STRING> containing the
STRING representations for all the
labels of a NODE .

The function returns a


nodes
MATCH p = (a)-->(b)-->(c)
WHERE a.name = 'Alice' AND c.name
LIST<NODE> containing all the
= 'Eskil' NODE values in a PATH .
RETURN nodes(p)

The range function returns a


RETURN range(0, 10), range(2, 18,
3), range(0, 5, -1)
LIST<INTEGER> comprising all
INTEGER values within a range
bounded by a start value and an end
value, where the difference step
between any two consecutive values
is constant; i.e. an arithmetic
progression.

The reduce function returns the


MATCH p = (a)-->(b)-->(c)
WHERE a.name = 'Alice' AND b.name
value resulting from the application
= 'Bob' AND c.name = 'Daniel' of an expression on each successive
RETURN reduce(totalAge = 0, n IN
nodes(p) | totalAge + n.age) AS element in a list in conjunction with
reduction the result of the computation thus
far.

The relationships function


MATCH p = (a)-->(b)-->(c)
WHERE a.name = 'Alice' AND c.name
returns a LIST<RELATIONSHIP>
= 'Eskil' containing all the RELATIONSHIP
RETURN relationships(p)
values in a PATH .

The reverse function returns a


WITH [4923,'abc',521, null, 487]
AS ids
LIST<ANY> in which the order of all
RETURN reverse(ids) elements in the given LIST<ANY>
have been reversed.

The tail function returns a


MATCH (a) WHERE a.name = 'Eskil'
RETURN a.likedColors,
LIST<ANY> containing all the
tail(a.likedColors) elements, excluding the first one,
from a given LIST<ANY> .

The toBooleanList converts a


RETURN toBooleanList(null) as
noList,
LIST<ANY> and returns a
toBooleanList([null, null]) as LIST<BOOLEAN> . If any values are
nullsInList,
toBooleanList(['a string', true, not convertible to BOOLEAN they will
'false', null, ['A','B']]) as be null in the LIST<BOOLEAN>
mixedList
returned.

The toFloatList converts a


RETURN toFloatList(null) as
noList,
LIST<ANY> of values and returns a
toFloatList([null, null]) as LIST<FLOAT> . If any values are not
nullsInList,
toFloatList(['a string', 2.5, convertible to FLOAT they will be
'3.14159', null, ['A','B']]) as null in the LIST<FLOAT> returned.
mixedList

The toIntegerList converts a


RETURN toIntegerList(null) as
noList,
LIST<ANY> of values and returns a
toIntegerList([null, null]) as LIST<INTEGER> . If any values are
nullsInList,
toIntegerList(['a string', 2, '5', not convertible to INTEGER they will
null, ['A','B']]) as mixedList be null in the LIST<INTEGER>
returned.

The toStringList converts a


RETURN toStringList(null) as
noList,
LIST<ANY> of values and returns a
toStringList([null, null]) as LIST<STRING> . If any values are not
nullsInList,
toStringList(['already a string', convertible to STRING they will be
2, date({year:1955, month:11, null in the LIST<STRING>
day:5}), null, ['A','B']]) as
mixedList returned.

Mathematical functions - numerical

The abs function returns the


MATCH (a), (e) WHERE a.name =
'Alice' AND e.name = 'Eskil'
absolute value of the given number.
RETURN a.age, e.age, abs(a.age -
e.age)

The ceil function returns the


RETURN ceil(0.1)
smallest FLOAT that is greater than
or equal to the given number and
equal to an INTEGER .

The floor function returns the


RETURN floor(0.9)
largest FLOAT that is less than or
equal to the given number and equal
to an INTEGER .

The isNan function returns true if


RETURN isNaN(0/0.0)
the given numeric value is NaN (Not
a Number).

The rand function returns a random


RETURN rand()
FLOAT in the range from 0 (inclusive)
to 1 (exclusive). The numbers
returned follow an approximate
uniform distribution.

The round function returns the


RETURN round(3.141592)
value of the given number rounded to
the nearest INTEGER , with ties
always rounded towards positive
infinity.

The round with precision function


RETURN round(3.141592, 3)
returns the value of the given
number rounded to the closest value
of given precision, with ties always
being rounded away from zero (using
rounding mode HALF_UP ). The
exception is for precision 0, where
ties are rounded towards positive
infinity to align with round()
without precision.

The round with precision and


RETURN round(1.249, 1, 'UP') AS
positive,
rounding mode function returns the
round(-1.251, 1, 'UP') AS value of the given number rounded
negative,
round(1.25, 1, 'UP') AS with the specified precision and the
positiveTie, specified rounding mode.
round(-1.35, 1, 'UP') AS
negativeTie

The sign function returns the


RETURN sign(-17), sign(0.1)
signum of the given number: 0 if the
number is 0, -1 for any negative
number, and 1 for any positive
number.

Mathematical functions - logarithmic

The e function returns the base of


RETURN e()
the natural logarithm, e.

The exp function returns en , where


RETURN exp(2)
e is the base of the natural
logarithm, and n is the value of the
argument expression.

The log function returns the natural


RETURN log(27)
logarithm of a number.

The log10 function returns the


RETURN log10(27)
common logarithm (base 10) of a
number.

The sqrt function returns the


RETURN sqrt(256)
square root of a number.

Mathematical Functions - trigonometric

The acos function returns the


RETURN acos(0.5)
arccosine of a FLOAT in radians.
The asin function returns the
RETURN asin(0.5)
arcsine of a FLOAT in radians.

The atan function returns the


RETURN atan(0.5)
arctangent of a FLOAT in radians.

The atan2 function returns the


RETURN atan2(0.5, 0.6)
arctangent2 of a set of coordinates in
radians.

The cos function returns the cosine


RETURN cos(0.5)
of a FLOAT .

The cot function returns the


RETURN cot(0.5)
cotangent of a FLOAT .

The degrees function converts


RETURN degrees(3.14159)
radians to degrees.

The haversin function converts


RETURN haversin(0.5)
half the versine of a number.

The pi function returns the


RETURN pi()
mathematical constant pi.

The radians function converts


RETURN radians(180)
degrees to radians.

The sin function returns the sine of


RETURN sin(0.5)
a number.

The tan function returns the


RETURN tan(0.5)
tangent of a number.

Predicate functions

The all function returns true if


MATCH p = (a)-[*]->(b)
WHERE
the predicate holds for all elements
a.name = 'Keanu Reeves' in the given LIST<ANY> .
AND b.name = 'Guy Pearce'
AND all(x IN nodes(p) WHERE
x.age < 60)
RETURN p

The any function returns true if


MATCH (p:Person)
WHERE any(nationality IN
the predicate holds for at least one
p.nationality WHERE nationality = element in the given LIST<ANY> .
'American')
RETURN p

The exists function returns true


MATCH (p:Person)
RETURN
if a match for the given pattern exists
p.name AS name, in the graph.
exists((p)-[:ACTED_IN]->()) AS
has_acted_in_rel

The isEmpty function returns true


MATCH (p:Person)
WHERE NOT isEmpty(p.nationality)
if the given LIST<ANY> or MAP
RETURN p.name, p.nationality contains no elements, or if the given
STRING contains no characters.

The none function returns true if


MATCH p = (n)-[*]->(b)
WHERE
the predicate does not hold for any
n.name = 'Keanu Reeves' element in the given LIST<ANY> .
AND none(x IN nodes(p) WHERE
x.age > 60)
RETURN p

The single function returns true


MATCH p = (n)-->(b)
WHERE
if the predicate holds for exactly one
n.name = 'Keanu Reeves' of the elements in the given
AND single(x IN nodes(p) WHERE
x.nationality = 'Northern Irish') LIST<ANY> .
RETURN p

Scalar functions

The char_length function returns


RETURN char_length('Alice')
the number of Unicode characters in
a STRING . This function is an alias of
the size function.

The character_length function


RETURN character_length('Alice')
returns the number of Unicode
characters in a STRING . This
function is an alias of the size
function.

The coalesce function returns the


MATCH (a)
WHERE a.name = 'Alice'
first given non-null argument.
RETURN coalesce(a.hairColor,
a.eyes)

The elementId function returns a


MATCH (n:Developer)
RETURN elementId(n)
STRING representation of a node or
relationship identifier, unique within a
specific transaction and DBMS.

The endNode function returns the


MATCH (x:Developer)-[r]-()
RETURN endNode(r)
the end NODE of a RELATIONSHIP .

The head function returns the first


MATCH (a)
WHERE a.name = 'Eskil'
element of the list. Returns null for
RETURN a.likedColors, an empty list. Equivalent to the list
head(a.likedColors)
indexing $list[0] .

The id function returns an


MATCH (a)
RETURN id(a)
INTEGER (the internal ID of a node or
relationship). Do not rely on the
internal ID for your business domain;
the internal ID can change between
transactions. The id function will be
removed in the next major release. It
is recommended to use elementId
instead.

The last function returns the last


MATCH (a)
WHERE a.name = 'Eskil'
element of the list. Returns null for
RETURN a.likedColors, an empty list. Equivalent to the list
last(a.likedColors)
indexing $list[-1] .
The length function returns the
MATCH p = (a)-->(b)-->(c)
WHERE a.name = 'Alice'
length of a PATH .
RETURN length(p)

The nullIf function returns null


RETURN nullIf("abc", "def")
if the two given parameters are
equivalent, otherwise it returns the
value of the first parameter.

The properties function returns a


CREATE (p:Person {name: 'Stefan',
city: 'Berlin'})
MAP containing all the properties of
RETURN properties(p) a node or relationship.

The randomUUID function returns a


RETURN randomUUID() AS uuid
STRING ; a randomly-generated
universally unique identifier (UUID).

The size function returns the


RETURN size(['Alice', 'Bob'])
number of elements in the list.

The function startNode function


MATCH (x:Developer)-[r]-()
RETURN startNode(r)
returns the start NODE of a
RELATIONSHIP .

The timestamp function returns the


RETURN timestamp()
time in milliseconds since
midnight, January 1, 1970
UTC. and the current time.

The toBoolean function converts a


RETURN toBoolean('true'),
toBoolean('not a boolean'),
STRING , INTEGER or BOOLEAN
toBoolean(0) value to a BOOLEAN value.

The toBooleanOrNull function


RETURN toBooleanOrNull('true'),
toBooleanOrNull('not a boolean'),
converts a STRING , INTEGER or
toBooleanOrNull(0), BOOLEAN value to a BOOLEAN value.
toBooleanOrNull(1.5)
For any other input value, null will
be returned.

The toFloat function converts an


RETURN toFloat('11.5'),
toFloat('not a number')
INTEGER , FLOAT or a STRING value
to a FLOAT .

The toFloatOrNull function


RETURN toFloatOrNull('11.5'),
toFloatOrNull('not a number'),
converts an INTEGER , FLOAT or a
toFloatOrNull(true) STRING value to a FLOAT . For any
other input value, null will be
returned.

The toIntegerfunction converts a


RETURN toInteger('42'),
toInteger('not a number'),
BOOLEAN , INTEGER , FLOAT or a
toInteger(true) STRING value to an INTEGER value.

The toIntegerOrNull function


RETURN toIntegerOrNull('42'),
toIntegerOrNull('not a number'),
converts a BOOLEAN , INTEGER ,
toIntegerOrNull(true), FLOAT or a STRING value to an
toIntegerOrNull(['A', 'B', 'C'])
INTEGER value. For any other input
value, null will be returned.

The type function returns the


MATCH (n)-[r]->()
WHERE n.name = 'Alice'
STRING representation of the
RETURN type(r) RELATIONSHIP type.

The valueType function returns a


UNWIND ["abc", 1, 2.0, true,
[date()]] AS value
STRING representation of the most
RETURN valueType(value) AS result precise value type that the given
expression evaluates to.

String functions

The btrim function returns the


RETURN btrim(' hello '),
btrim('xxyyhelloxyxy', 'xy')
original STRING with leading and
trailing trimCharacterString
characters removed. If
trimCharacterString is not
specified then all leading and trailing
whitespace will be removed.

The leftfunction returns a


RETURN left('hello', 3)
STRING containing the specified
number of leftmost characters of the
given STRING .

The lower function returns the


RETURN lower('HELLO')
given STRING in lowercase. This
function is an alias of the toLower
function.

The ltrim function returns the


RETURN ltrim(' hello'),
ltrim('xxyyhelloxyxy', 'xy')
original STRING with leading
trimCharacterString characters
removed. If trimCharacterString
is not specified then all leading
whitespace will be removed.

The normalize function returns a


RETURN normalize('\u212B') =
'\u00C5' AS result
given STRING normalized using the
NFC Unicode normalization form.

The replace function returns a


RETURN replace("hello", "l", "w")
STRING in which all occurrences of
a specified STRING in the given
STRING have been replaced by
another (specified) replacement
STRING .

The reverse function returns a


RETURN reverse('palindrome')
STRING in which the order of all
characters in the given STRING have
been reversed.

The right function returns a


RETURN right('hello', 3)
STRING containing the specified
number of rightmost characters in
the given STRING .

The rtrim function returns the


RETURN rtrim('hello '),
rtrim('xxyyhelloxyxy', 'xy')
given STRING with trailing
trimCharacterString characters
removed. If trimCharacterString
is not specified then all trailing
whitespace will be removed.

The split function returns a


RETURN split('one,two', ',')
LIST<STRING> resulting from the
splitting of the given STRING around
matches of the given delimiter.

The substring function returns a


RETURN substring('hello', 1, 3),
substring('hello', 2)
substring of the given STRING ,
beginning with a zero-based index
start and length.

The toLower function returns the


RETURN toLower('HELLO')
given STRING in lowercase.

The toString function converts an


RETURN
toString(11.5),
INTEGER , FLOAT , BOOLEAN ,
toString('already a string'), STRING , POINT , DURATION , DATE ,
toString(true),
toString(date({year: 1984, ZONED TIME , LOCAL TIME , LOCAL
month: 10, day: 11})) AS DATETIME or ZONED DATETIME
dateString,
toString(datetime({year: 1984, value to a STRING .
month: 10, day: 11, hour: 12,
minute: 31, second: 14,
millisecond: 341, timezone:
'Europe/Stockholm'})) AS
datetimeString,
toString(duration({minutes: 12,
seconds: -60})) AS durationString

The toStringOrNull function


RETURN toStringOrNull(11.5),
toStringOrNull('already a
converts an INTEGER , FLOAT ,
string'), BOOLEAN , STRING , POINT ,
toStringOrNull(true),
toStringOrNull(date({year: 1984, DURATION , DATE , ZONED TIME ,
month: 10, day: 11})) AS LOCAL TIME , LOCAL DATETIME or
dateString,
toStringOrNull(datetime({year: ZONED DATETIME value to a
1984, month: 10, day: 11, hour:
STRING . For any other input value,
12, minute: 31, second: 14,
millisecond: 341, timezone: null will be returned.
'Europe/Stockholm'})) AS
View all (3 more lines)
datetimeString,
toStringOrNull(duration({minutes:

The toUpper function returns the


RETURN toUpper('hello')
given STRING in uppercase.

The function returns the given


trim
RETURN trim(' hello '),
trim(BOTH 'x' FROM 'xxxhelloxxx')
STRING with leading and trailing
whitespace removed.

The upper function returns the


RETURN upper('hello')
given STRING in uppercase. This
function is an alias of the toUpper
function.

Spatial functions

The point Cartesian 2D function


WITH
point({longitude: 12.53,
returns a 2D POINT in the Cartesian
latitude: 55.66}) AS lowerLeft, CRS corresponding to the given
point({longitude: 12.614,
latitude: 55.70}) AS upperRight coordinate values.
MATCH (t:TrainStation)
WHERE
point.withinBBox(point({longitude:
t.longitude, latitude:
t.latitude}), lowerLeft,
upperRight)
RETURN count(t)
The point Cartesian 3D function
RETURN
point.withinBBox(
returns a 3D POINT in the Cartesian
null, CRS corresponding to the given
point({longitude: 56.7,
latitude: 12.78}), coordinate values.
point({longitude: 57.0,
latitude: 13.0})
) AS in

The point WGS 84 2D function


MATCH (t:TrainStation)-
[:TRAVEL_ROUTE]->(o:Office)
returns a 2D POINT in the WGS 84
WITH CRS corresponding to the given
point({longitude: t.longitude,
latitude: t.latitude}) AS coordinate values.
trainPoint,
point({longitude: o.longitude,
latitude: o.latitude}) AS
officePoint
RETURN
round(point.distance(trainPoint,
officePoint)) AS travelDistance

The point WGS 84 3D function


WITH
point({x: 0, y: 0, crs:
returns a 3D POINT in the WGS 84
'cartesian'}) AS lowerLeft, CRS corresponding to the given
point({x: 10, y: 10, crs:
'cartesian'}) AS upperRight coordinate values.
RETURN point.withinBBox(point({x:
5, y: 5, crs: 'cartesian'}),
lowerLeft, upperRight) AS result

The point.distance function


MATCH (p:Office)
RETURN point({longitude:
returns returns a FLOAT
p.longitude, latitude: representing the geodesic distance
p.latitude}) AS officePoint
between two points in the same
Coordinate Reference System (CRS).
The point.withinBBox function
RETURN point({x: 2.3, y: 4.5}) AS
point
takes the following arguments: the
POINT to check, the lower-left
(south-west) POINT of a bounding
box, and the upper-right (or north-
east) POINT of a bounding box. The
return value will be true if the
provided point is contained in the
bounding box (boundary included),
otherwise the return value will be
false.

Temporal functions

The date function returns the


RETURN date() AS currentDate
current DATE value. If no time zone
parameter is specified, the local time
zone will be used.

The date.transaction function


UNWIND [
date({year: 1984, week: 10,
returns the current DATE value using
dayOfWeek: 3}), the transaction clock. This value
date({year: 1984, week: 10}),
date({year: 1984}) will be the same for each invocation
] AS theDate within the same transaction.
RETURN theDate
However, a different value may be
produced for different transactions.

The date.statement function


UNWIND [
date({year: 1984, month: 11, day:
returns the current DATE value using
11}), the statement clock. This value will
localdatetime({year: 1984, month:
11, day: 11, hour: 12, minute: 31, be the same for each invocation
second: 14}), within the same statement. However,
datetime({year: 1984, month: 11,
day: 11, hour: 12, timezone: a different value may be produced
'+01:00'}) for different statements within the
] AS dd
RETURN date({date: dd}) AS same transaction.
dateOnly, date({date: dd, day:
28}) AS dateDay

The date.realtime function


RETURN date.realtime() AS
currentDate
returns returns the current DATE
value using the realtime clock.
This value will be the live clock of the
system.

The datetime function returns the


WITH
datetime({
current ZONED DATETIME value. If
year: 1984, month: 10, day: no time zone parameter is specified,
11,
hour: 12, the default time zone will be used.
timezone: 'Europe/Stockholm'
}) AS dd
RETURN
datetime({datetime: dd}) AS
dateTime,
datetime({datetime: dd,
timezone: '+05:00'}) AS
View all (5 more lines)
dateTimeTimezone,
datetime({datetime: dd, day: 28,

The datetime.transaction
RETURN datetime.transaction() AS
currentDateTime
function returns the current ZONED
DATETIME value using the
transaction clock. This value will
be the same for each invocation
within the same transaction.
However, a different value may be
produced for different transactions.

The datetime.statement function


RETURN datetime.statement() AS
currentDateTime
returns the current ZONED
DATETIME value using the
transaction clock. This value will
be the same for each invocation
within the same transaction.
However, a different value may be
produced for different transactions.

The datetime.realtime function


RETURN datetime.realtime() AS
currentDateTime
returns the current ZONED
DATETIME value using the
realtime clock. This value will be
the live clock of the system.

The localdatetime function returns the current LOCAL DATETIME value. If


no time zone parameter is specified, the local time zone will be used.

The localdatetime.transaction
RETURN localdatetime.transaction()
AS now
function returns the current LOCAL
DATETIME value using the
transaction clock. This value will
be the same for each invocation
within the same transaction.
However, a different value may be
produced for different transactions.

The localdatetime.statement
RETURN localdatetime.statement()
AS now
function returns the current LOCAL
DATETIME value using the
statement clock. This value will be
the same for each invocation within
the same statement. However, a
different value may be produced for
different statements within the same
transaction.

The localdatetime.realtime
RETURN localdatetime.realtime() AS
now
function returns the current LOCAL
DATETIME value using the
realtime clock. This value will be
the live clock of the system.

The localtime function returns the


RETURN localdatetime() AS now
current LOCAL TIME value. If no
time zone parameter is specified, the
local time zone will be used.

The localtime.transaction
RETURN
localdatetime({
function returns the current LOCAL
year: 1984, month: 10, day: TIME value using the transaction
11,
hour: 12, minute: 31, second: clock. This value will be the same for
14, millisecond: 123, microsecond: each invocation within the same
456, nanosecond: 789
}) AS theDate transaction. However, a different
value may be produced for different
transactions.

The localtime.statement
RETURN
localdatetime({
function returns the current LOCAL
year: 1984, quarter: 3, TIME value using the statement
dayOfQuarter: 45,
hour: 12, minute: 31, second: clock. This value will be the same for
14, nanosecond: 645876123 each invocation within the same
}) AS theDate
statement. However, a different value
may be produced for different
statements within the same
transaction.

The localtime.realtime function


WITH date({year: 1984, month: 10,
day: 11}) AS dd
returns the current LOCAL TIME
RETURN value using the realtime clock.
localdatetime({date: dd, hour:
10, minute: 10, second: 10}) AS This value will be the live clock of the
dateHHMMSS, system.
localdatetime({date: dd, day:
28, hour: 10, minute: 10, second:
10}) AS dateDDHHMMSS

The time function returns the


RETURN localtime({timezone:
'America/Los Angeles'}) AS nowInLA
current ZONED TIME value. If no
time zone parameter is specified, the
local time zone will be used.

The time.transaction function


WITH time({hour: 12, minute: 31,
second: 14, microsecond: 645876,
returns the current ZONED TIME
timezone: '+01:00'}) AS tt value using the transaction clock.
RETURN
localtime({time: tt}) AS This value will be the same for each
timeOnly, invocation within the same
localtime({time: tt, second:
42}) AS timeSS transaction. However, a different
value may be produced for different
transactions.

The time.statement function


RETURN localtime.statement() AS
now
returns the current ZONED TIME
value using the statement clock.
This value will be the same for each
invocation within the same
statement. However, a different value
may be produced for different
statements within the same
transaction.

The time.realtime function


WITH time({hour: 12, minute: 31,
second: 14, nanosecond: 645876123,
returns the current ZONED TIME
timezone: '-01:00'}) AS t value using the realtime clock.
RETURN
localtime.truncate('day', t) AS This value will be the live clock of the
truncDay, system.
localtime.truncate('hour', t) AS
truncHour,
localtime.truncate('minute', t,
{millisecond: 2}) AS truncMinute,
localtime.truncate('second', t)
AS truncSecond,
View all (3 more lines)

localtime.truncate('millisecond',

Vector functions

The
MATCH (n:Label)
WITH n,
vector.similarity.euclidean
vector.similarity.euclidean($query, function returns a FLOAT
n.vector) AS score
RETURN n, score representing the similarity between
the argument vectors based on their
Euclidean distance.

The vector.similarity.cosine
MATCH (n:Label)
WITH n,
function returns a FLOAT
vector.similarity.cosine($query, representing the similarity between
n.vector) AS score
RETURN n, score the argument vectors based on their
cosine.
Schema
Search-performance indexes
Cypher includes four search-performance indexes: range (default), text, point,
and token lookup.

CREATE INDEX index_name


FOR (p:Person) ON (p.name)

Create a range index with the name index_name on nodes with label
Person and property name .

It is possible to omit the index_name , if not specified the index name will be
decided by the DBMS. Best practice is to always specify a sensible name
when creating an index.
The create syntax is CREATE
[RANGE|TEXT|POINT|LOOKUP|FULLTEXT|VECTOR] INDEX …​. Defaults to
range if not explicitly stated.

Create a range index on relationships


CREATE RANGE INDEX index_name
FOR ()-[k:KNOWS]-() ON (k.since)
with type KNOWS and property
since with the name index_name .

Create a composite range index with


CREATE INDEX $nameParam
FOR (p:Person) ON (p.name, p.age)
the name given by the parameter
nameParam on nodes with label
Person and the properties name
and age , throws an error if the index
already exist.
Create a composite range index with
CREATE INDEX index_name IF NOT
EXISTS
the name index_name on nodes
FOR (p:Person) ON (p.name, p.age) with label Person and the
properties name and age if it does
not already exist, does nothing if it
did exist.

Create a text index on nodes with


CREATE TEXT INDEX index_name
FOR (p:Person) ON (p.name)
label Person and property name .
Text indexes only solve predicates
involving STRING property values.

Create a text index on relationships


CREATE TEXT INDEX index_name
FOR ()-[r:KNOWS]-() ON (r.city)
with type KNOWS and property
city . Text indexes only solve
predicates involving STRING
property values.

Create a point index on nodes with


CREATE POINT INDEX index_name
FOR (p:Person) ON (p.location)
label Person and property
OPTIONS { location with the name
indexConfig: {
`spatial.cartesian.min`: index_name and the given
[-100.0, -100.0], spatial.cartesian settings. The
`spatial.cartesian.max`:
[100.0, 100.0] other index settings will have their
}
default values. Point indexes only
}
solve predicates involving POINT
property values.

Create a point index with the name


CREATE POINT INDEX $nameParam
FOR ()-[h:STREET]-() ON
given by the parameter nameParam
(h.intersection) on relationships with the type
STREET and property
intersection . Point indexes only
solve predicates involving POINT
property values.

Create a token lookup index on


CREATE LOOKUP INDEX index_name
FOR (n) ON EACH labels(n)
nodes with any label.

Create a token lookup index on


CREATE LOOKUP INDEX index_name
FOR ()-[r]-() ON EACH type(r)
relationships with any relationship
type.

List all indexes, returns only the


SHOW INDEXES
default outputs ( id , name , state ,
populationPercent , type ,
entityType , labelsOrTypes ,
properties , indexProvider ,
owningConstraint , lastRead ,
and readCount ).

List all indexes and return all


SHOW INDEXES YIELD *
columns.

List all indexes and return only


SHOW INDEX YIELD name, type,
entityType, labelsOrTypes,
specific columns.
properties

List all indexes and return only


SHOW INDEXES
YIELD name, type, options,
specific columns using the RETURN
createStatement clause. Note that YIELD is
RETURN name, type,
options.indexConfig AS config, mandatory if RETURN is used.
createStatement

List range indexes, can also be


SHOW RANGE INDEXES
filtered on ALL , FULLTEXT ,
LOOKUP , POINT , TEXT , and
VECTOR .

Drop the index named index_name ,


DROP INDEX index_name
throws an error if the index does not
exist.

Drop the index named index_name


DROP INDEX index_name IF EXISTS
if it exists, does nothing if it does not
exist.

Drop an index using a parameter.


DROP INDEX $nameParam

Index usage can be enforced when


MATCH (n:Person)
USING INDEX n:Person(name)
Cypher uses a suboptimal index, or
WHERE n.name = $value when more than one index should be
used.

Full-text indexes

Create a fulltext index on nodes with


CREATE FULLTEXT INDEX
node_fulltext_index
the name index_name and analyzer
FOR (n:Friend) ON EACH [n.name] swedish . The other index settings
OPTIONS {
indexConfig: { will have their default values.
`fulltext.analyzer`: 'swedish'
}
}

Create a fulltext index on


CREATE FULLTEXT INDEX
relationship_fulltext_index
relationships with the name
FOR ()-[r:KNOWS]-() ON EACH index_name and analyzer
[r.info, r.note]
OPTIONS { english . The other index settings
indexConfig: { will have their default values.
`fulltext.analyzer`: 'english'
}
}

CALL db.index.fulltext.queryNodes("node_fulltext_index", "Alice") YIELD


node, score

Query a full-text index on nodes.

CALL db.index.fulltext.queryRelationships("relationship_fulltext_index",
"Alice") YIELD relationship, score

Query a full-text index on relationships.

List all full-text indexes.


SHOW FULLTEXT INDEXES

Drop a full-text index.


DROP INDEX node_fulltext_index
Vector indexes

Create a vector index on nodes with


CREATE VECTOR INDEX `abstract-
embeddings`
label Abstract , property
FOR (a:Abstract) ON (a.embedding) embedding , and a vector dimension
OPTIONS {
indexConfig: { of 1536 using the cosine similarity
`vector.dimensions`: 1536, function and the name abstract-
`vector.similarity_function`:
'cosine' embeddings . Note that the OPTIONS
}
map is mandatory since a vector
}
index cannot be created without
setting the vector dimensions and
similarity function.

Create a vector index on


CREATE VECTOR INDEX `review-
embeddings`
relationships with relationship type
FOR ()-[r:REVIEWED]-() ON REVIEWED , property embedding ,
(r.embedding)
OPTIONS { and a vector dimension of 256 using
indexConfig: { the cosine similarity function and
`vector.dimensions`: 256,
`vector.similarity_function`: the name review-embeddings .
'cosine'
Note that the OPTIONS map is
}
} mandatory since a vector index
cannot be created without setting
the vector dimensions and similarity
function.

Query the node vector index


CALL
db.index.vector.queryNodes('abstract-
abstract-embeddings for a
embeddings', 10, abstract.embedding) neighborhood of 10 similar
abstracts.
CALL db.index.vector.queryRelationships('review-embeddings', 10, $query)

Query the relationship vector index review-embeddings for a neighborhood


of 10 similar reviews to the vector given by the query parameter.

MATCH (n:Node {id: $id})


CALL db.create.setNodeVectorProperty(n, 'propertyKey', $vector)

Set the vector properties of a node using


db.create.setNodeVectorProperty .

MATCH ()-[r:Relationship {id: $id}]->()


CALL db.create.setRelationshipVectorProperty(r, 'propertyKey', $vector)

Set the vector properties of a relationship using


db.create.setRelationshipVectorProperty .

List all vector indexes.


SHOW VECTOR INDEXES

Drop a vector index.


DROP INDEX `abstract-embeddings`

Constraints
List all constraints, returns only the
SHOW ALL CONSTRAINTS
default outputs ( id , name , type ,
entityType , labelsOrTypes ,
properties , ownedIndex , and
propertyType ). Can also be filtered
on NODE UNIQUENESS ,
RELATIONSHIP UNIQUENESS ,
UNIQUENESS , NODE EXISTENCE ,
RELATIONSHIP EXISTENCE ,
EXISTENCE , NODE PROPERTY TYPE ,
RELATIONSHIP PROPERTY TYPE ,
PROPERTY TYPE , NODE KEY ,
RELATIONSHIP KEY , and KEY . For
more information, see Constraints →
Syntax → SHOW CONSTRAINTS.

List all constraints. For more


SHOW CONSTRAINTS YIELD *
information, see Constraints →
Create, show, and drop constraints →
SHOW CONSTRAINTS.

Drop the constraint with the name


DROP CONSTRAINT constraint_name
constraint_name , throws an error
if the constraint does not exist.

Drop the constraint with the name


DROP CONSTRAINT $nameParam IF
EXISTS
given by the parameter nameParam
if it exists, does nothing if it does not
exist.

Create a node property uniqueness


CREATE CONSTRAINT constraint_name
IF NOT EXISTS
constraint on the label Person and
FOR (p:Person) property name . Using the keyword
REQUIRE p.name IS UNIQUE
IF NOT EXISTS makes the
command idempotent, and no error
will be thrown if an attempt is made
to create the same constraint twice.
If any other node with that label is
updated or created with a name that
already exists, the write operation
will fail.
Best practice is to always specify a
sensible name when creating a
constraint.

Create a node property uniqueness


CREATE CONSTRAINT constraint_name
FOR (p:Person)
constraint on the label Person and
REQUIRE (p.name, p.age) IS UNIQUE properties name and age . An error
will be thrown if an attempt is made
to create the same constraint twice.
If any node with that label is updated
or created with a name and age
combination that already exists, the
write operation will fail.

Create a relationship property


CREATE CONSTRAINT constraint_name
FOR ()-[r:LIKED]-()
uniqueness constraint on the
REQUIRE r.when IS UNIQUE relationship type LIKED and
property when . If any other
relationship with that relationship
type is updated or created with a
when property value that already
exists, the write operation will fail.
Best practice is to always specify a
sensible name when creating a
constraint.

Not available on Neo4j Community Edition

Create a node property existence


CREATE CONSTRAINT $nameParam
FOR (p:Person)
constraint with the name given by
REQUIRE p.name IS NOT NULL the parameter nameParam on the
label Person and property name . If
a node with that label is created
without a name property, or if the
name property on the existing node
with the label Person is removed,
the write operation will fail.

Not available on Neo4j Community Edition

Create a relationship property


CREATE CONSTRAINT constraint_name
FOR ()-[r:LIKED]-()
existence constraint on the type
REQUIRE r.when IS NOT NULL LIKED and property when . If a
relationship with that type is created
without a when property, or if the
property when is removed from an
existing relationship with the type
LIKED , the write operation will fail.

Not available on Neo4j Community Edition

Create a node property type


CREATE CONSTRAINT constraint_name
FOR (p:Person)
constraint on the label Person and
REQUIRE p.name IS :: STRING property name , restricting the
property to STRING . If a node with
that label is created with a name
property of a different Cypher type,
the write operation will fail.

Not available on Neo4j Community Edition

Create a relationship property type


CREATE CONSTRAINT constraint_name
FOR ()-[r:LIKED]-()
constraint on the type LIKED and
REQUIRE r.when IS :: DATE property when , restricting the
property to DATE . If a relationship
with that type is created with a when
property of a different Cypher type,
the write operation will fail.

Not available on Neo4j Community Edition

Create a node key constraint on the


CREATE CONSTRAINT constraint_name
FOR (p:Person)
label Person and properties name
REQUIRE (p.name, p.surname) IS and surname with the name
NODE KEY
constraint_name . If a node with
that label is created without both the
name and surname properties, or if
the combination of the two is not
unique, or if the name and/or
surname properties on an existing
node with the label Person is
modified to violate these constraints,
the write operation will fail.

Not available on Neo4j Community Edition

Create a relationship key constraint


CREATE CONSTRAINT constraint_name
FOR ()-[r:KNOWS]-()
with the name constraint_name on
REQUIRE (r.since, r.isFriend) IS the relationship type KNOWS and
RELATIONSHIP KEY
properties since and isFriend . If
a relationship with that relationship
type is created without both the
since and isFriend properties, or
if the combination of the two is not
unique, the write operation will fail.
The write operation will also fail if
the since and/or isFriend
properties on an existing relationship
with the relationship type KNOWS is
modified to violate these constraints.

Performance
Performance
Use parameters instead of literals when possible. This allows Neo4j DBMS
to cache your queries instead of having to parse and build new execution
plans.
Always set an upper limit for your variable length patterns. It is possible to
have a query go wild and touch all nodes in a graph by mistake.
Return only the data you need. Avoid returning whole nodes and
relationships; instead, pick the data you need and return only that.
Use PROFILE / EXPLAIN to analyze the performance of your queries. See
Query Tuning for more information on these and other topics, such as
planner hints.
Database Management
DATABASE Management

The naming rules for a database:


dba
`db1` The character length of a
`database-name` database name must be at least
`database-name-123` 3 characters; and not more than
`database.name` 63 characters.
`database.name.123` The first character of a database
name must be an ASCII
alphabetic character.
Subsequent characters must be
ASCII alphabetic or numeric
characters, dots or dashes;
[a..z][0..9].- .
Database names are case-
insensitive and normalized to
lowercase.
Database names that begin with
an underscore ( _ ) or with the
prefix system are reserved for
internal use.

Database names may include dots


( . ) without being quoted with
backticks, although this behavior is
deprecated as it may introduce
ambiguity when addressing
composite databases. Naming a
database foo.bar.baz is valid, but
deprecated. `foo.bar.baz` is
valid.

List all databases in Neo4j DBMS


SHOW DATABASES
and information about them, returns
only the default outputs ( name ,
type , aliases , access ,
address , role , writer ,
requestedStatus ,
currentStatus , statusMessage ,
default , home , and
constituents ).

List all databases in Neo4j DBMS


SHOW DATABASES YIELD *
and information about them.

List information about databases,


SHOW DATABASES
YIELD name, currentStatus
filtered by name and
WHERE name CONTAINS 'my' currentStatus and further refined
AND currentStatus = 'online'
by conditions on these.

List information about the database


SHOW DATABASE `database-name`
YIELD *
database-name .

List information about the default


SHOW DEFAULT DATABASE
database, for the Neo4j DBMS.

List information about the current


SHOW HOME DATABASE
users home database.

Neo4j Enterprise Edition

Delete the database database-


DROP DATABASE `database-name` IF
EXISTS
name , if it exists. This command can
delete both standard and composite
databases.

Neo4j Enterprise Edition

Delete the database named


DROP COMPOSITE DATABASE
`composite-database-name`
composite-database-name . In
case the given database name does
not exist or is not composite, and
error will be thrown.

Neo4j Enterprise Edition

Drop the database database-name


DROP DATABASE `database-name`
CASCADE ALIASES
and any database aliases referencing
the database. This command can
drop both standard and composite
databases. For standard databases,
the database aliases that will be
dropped are any local database
aliases targeting the database. For
composite databases, the database
aliases that will be dropped are any
constituent database aliases
belonging to the composite
database.

Neo4j Enterprise Edition

Create a standard database named


CREATE DATABASE `database-name` IF
NOT EXISTS
database-name if it does not
already exist.
Neo4j Enterprise Edition

Create a standard database named


CREATE OR REPLACE DATABASE
`database-name`
database-name . If a database with
that name exists, then the existing
database is deleted and a new one
created.

Neo4j Enterprise Edition

Create a standard database named


CREATE DATABASE `topology-example`
IF NOT EXISTS
topology-example in a cluster
TOPOLOGY 1 PRIMARY 0 SECONDARIES environment, to use 1 primary server
and 0 secondary servers.

Neo4j Enterprise Edition

Create a composite database named


CREATE COMPOSITE DATABASE
`composite-database-name`
composite-database-name .

Neo4j Enterprise Edition

Stop a database named database-


STOP DATABASE `database-name`
name .

Neo4j Enterprise Edition

Start a database named database-


START DATABASE `database-name`
name .

Neo4j Enterprise Edition


Modify a standard database named
ALTER DATABASE `database-name` IF
EXISTS
database-name to accept only read
SET ACCESS READ ONLY queries.

Neo4j Enterprise Edition

Modify a standard database named


ALTER DATABASE `database-name` IF
EXISTS
database-name to accept write and
SET ACCESS READ WRITE read queries.

Neo4j Enterprise Edition

Modify a standard database named


ALTER DATABASE `topology-example`
SET TOPOLOGY 1 PRIMARY 0
topology-example in a cluster
SECONDARIES environment to use 1 primary server
and 0 secondary servers.

Neo4j Enterprise Edition

Modify a standard database named


ALTER DATABASE `topology-example`
SET TOPOLOGY 1 PRIMARY
topology-example in a cluster
SET ACCESS READ ONLY environment to use 1 primary servers
and 0 secondary servers, and to only
accept read queries.

ALIAS Management

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

List all database aliases in Neo4j


SHOW ALIASES FOR DATABASE
DBMS and information about them,
returns only the default outputs
( name , composite , database ,
location , url , and user ).

List the database alias named


SHOW ALIASES `database-alias` FOR
DATABASE
database-alias and the
information about it. Returns only the
default outputs ( name , composite ,
database , location , url , and
user ).

List all database aliases in Neo4j


SHOW ALIASES FOR DATABASE YIELD *
DBMS and information about them.

Create a local alias named


CREATE ALIAS `database-alias` IF
NOT EXISTS
database-alias for the database
FOR DATABASE `database-name` named database-name .

Create or replace a local alias named


CREATE OR REPLACE ALIAS `database-
alias`
database-alias for the database
FOR DATABASE `database-name` named database-name .

Database aliases can be given


CREATE ALIAS `database-alias`
FOR DATABASE `database-name`
properties.
PROPERTIES { property = $value }

Create a remote alias named


CREATE ALIAS `database-alias`
FOR DATABASE `database-name`
database-alias for the database
AT $url named database-name .
USER user_name
PASSWORD $password

Create a remote alias named alias-


CREATE ALIAS `composite-database-
name`.`alias-in-composite-name`
in-composite-name as a
FOR DATABASE `database-name` constituent alias in the composite
AT $url
USER user_name database named composite-
PASSWORD $password database-name for the database
with name database-name .

Alter the alias named database-


ALTER ALIAS `database-alias` IF
EXISTS
alias to target the database named
SET DATABASE TARGET `database- database-name .
name`

Alter the remote alias named


ALTER ALIAS `remote-database-
alias` IF EXISTS
remote-database-alias , set the
SET DATABASE username ( user_name ) and the
USER user_name
PASSWORD $password password.

Update the properties for the


ALTER ALIAS `database-alias`
SET DATABASE PROPERTIES { key:
database alias named database-
value } alias .

Delete the alias named database-


DROP ALIAS `database-alias` IF
EXISTS FOR DATABASE
alias .
SERVER Management

AuraDB Business Critical AuraDB Virtual Dedicated Cloud

Display all servers running in the


SHOW SERVERS
cluster, including servers that have
yet to be enabled as well as dropped
servers. Default outputs are: name ,
address , state , health , and
hosting .

Neo4j Enterprise Edition

Make the server with the ID


ENABLE SERVER 'serverId'
serverId an active member of the
cluster.

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Change the name of a server.


RENAME SERVER 'oldName' TO
'newName'

Neo4j Enterprise Edition

Only allow the specified server to


ALTER SERVER 'name' SET OPTIONS
{modeConstraint: 'PRIMARY'}
host databases in primary mode.

Neo4j Enterprise Edition

Re-balance databases among the


REALLOCATE DATABASES
servers in the cluster.
Neo4j Enterprise Edition

Remove all databases from the


DEALLOCATE DATABASES FROM SERVER
'name'
specified server, adding them to
other servers as needed. The
specified server is not allowed to
host any new databases.

Neo4j Enterprise Edition

Remove the specified server from


DROP SERVER 'name'
the cluster.

Access Control
USER Management

List all users in Neo4j DBMS, returns


SHOW USERS
only the default outputs ( user ,
roles , passwordChangeRequired ,
suspended , and home ).

List the currently logged-in user,


SHOW CURRENT USER
returns only the default outputs
( user , roles ,
passwordChangeRequired ,
suspended , and home ).
Not available on Neo4j Community Edition

List users that are suspended.


SHOW USERS
WHERE suspended = true

List users that must change their


SHOW USERS
WHERE passwordChangeRequired
password at the next login.

List users with their auth providers.


SHOW USERS WITH AUTH
Will return one row per user per auth
provider.

List users who have the oidc1 auth


SHOW USERS WITH AUTH WHERE
provider = 'oidc1'
provider.

Delete the specified user.


DROP USER user_name

Create a new user and set the


CREATE USER user_name
SET PASSWORD $password
password. This password must be
changed on the first login.

Create a new user and set the


CREATE USER user_name
SET AUTH 'native' {
password using the auth provider
SET PASSWORD $password syntax. This password must be
SET PASSWORD CHANGE REQUIRED
} changed on the first login.

Rename the specified user.


RENAME USER user_name TO
other_user_name

Change the password of the logged-


ALTER CURRENT USER
SET PASSWORD FROM $oldPassword TO
in user. The user will not be required
$newPassword to change this password on the next
login.

Set a new password (a String) for a


ALTER USER user_name
SET PASSWORD $password
user. This user will not be required to
CHANGE NOT REQUIRED change this password on the next
login.

If the specified user exists, force this


ALTER USER user_name IF EXISTS
SET PASSWORD CHANGE REQUIRED
user to change the password on the
next login.

Neo4j Enterprise Edition

Add another way for the user to


ALTER USER user_name
SET AUTH 'externalProviderName' {
authenticate and authorize using the
SET ID external provider
'userIdForExternalProvider'
} externalProviderName . This
provider needs to be defined in the
configurations settings.

Not available on Neo4j Community Edition

Change the status to SUSPENDED ,


ALTER USER user_name
SET STATUS SUSPENDED
for the specified user.

Not available on Neo4j Community Edition


Change the status to ACTIVE , for
ALTER USER user_name
SET STATUS ACTIVE
the specified user.

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Set the home database for the


ALTER USER user_name
SET HOME DATABASE `database-name`
specified user. The home database
can either be a database or an alias.

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Unset the home database for the


ALTER USER user_name
REMOVE HOME DATABASE
specified user and fallback to the
default database.

ROLE Management

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

List all roles in the system, returns


SHOW ROLES
the output role .

List roles that contains a given string.


SHOW ROLES
WHERE role CONTAINS $subString

List all roles that are assigned to at


SHOW POPULATED ROLES
least one user in the system.
List all roles that are assigned to at
SHOW POPULATED ROLES WITH USERS
least one user in the system, and the
users assigned to those roles. The
returned outputs are role and
member .

List all roles that are assigned to a


SHOW POPULATED ROLES WITH USERS
YIELD member, role
$user .
WHERE member = $user
RETURN role

Delete a role.
DROP ROLE role_name

Create a role, unless it already exists.


CREATE ROLE role_name IF NOT
EXISTS

Create a role, as a copy of the


CREATE ROLE role_name AS COPY OF
other_role_name
existing other_role_name .

Rename a role.
RENAME ROLE role_name TO
other_role_name

Assign roles to a user.


GRANT ROLE role_name1, role_name2
TO user_name

Remove the specified role from a


REVOKE ROLE role_name FROM
user_name
user.

SHOW Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

List all privileges in the system, and


SHOW PRIVILEGES
the roles that they are assigned to.
Outputs returned are: access ,
action , resource , graph ,
segment , role , and immutable .

List all privileges in the system as


SHOW PRIVILEGES AS COMMANDS
Cypher commands, for example
GRANT ACCESS ON DATABASE * TO
`admin` . Returns only the default
output ( command ).

List all privileges of the currently


SHOW USER PRIVILEGES
logged-in user, and the roles that
they are assigned to. Outputs
returned are: access , action ,
resource , graph , segment ,
role , immutable , and user .

List all privileges of the currently


SHOW USER PRIVILEGES AS COMMANDS
logged-in user, and the roles that
they are assigned to as Cypher
commands, for example GRANT
ACCESS ON DATABASE * TO $role .
Returns only the default output
( command ).

List all privileges assigned to each of


SHOW USER user_name PRIVILEGES
the specified users (multiple users
can be specified separated by
commas n1, n2, n3 ), and the roles
that they are assigned to. Outputs
returned are: access , action ,
resource , graph , segment ,
role , immutable , and user .

List all privileges assigned to each of


SHOW USER user_name PRIVILEGES AS
COMMANDS YIELD *
the specified users (multiple users
can be specified separated by
commas n1, n2, n3 ), as generic
Cypher commands, for example
GRANT ACCESS ON DATABASE * TO
$role . Outputs returned are:
command and immutable .

List all privileges assigned to each of


SHOW ROLE role_name PRIVILEGES
the specified roles (multiple roles
can be specified separated by
commas r1, r2, r3 ). Outputs
returned are: access , action ,
resource , graph , segment ,
role , and immutable .

List all privileges assigned to each of


SHOW ROLE role_name PRIVILEGES AS
COMMANDS
the specified roles (multiple roles
can be specified separated by
commas r1, r2, r3 ) as Cypher
commands, for example GRANT
ACCESS ON DATABASE * TO
`admin` . Returns only the default
output ( command ).

SHOW SUPPORTED Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

List all privileges that are possible to


SHOW SUPPORTED PRIVILEGES
grant or deny on a server. Outputs
returned are: action , qualifier ,
target , scope , and description .

IMMUTABLE Privileges Neo4j Enterprise Edition

Grant immutable TRAVERSE


GRANT IMMUTABLE TRAVERSE
ON GRAPH * TO role_name
privilege on all graphs to the
specified role.

Deny immutable START privilege to


DENY IMMUTABLE START
ON DATABASE * TO role_name
start all databases to the specified
role.

Revoke immutable CREATE ROLE


REVOKE IMMUTABLE CREATE ROLE
ON DBMS FROM role_name
privilege from the specified role.
When immutable is specified in
conjunction with a REVOKE
command, it will act as a filter and
only remove the matching immutable
privileges.

Load Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant LOAD privilege on ALL DATA


GRANT LOAD
ON ALL DATA
to allow loading all data to the
TO role_name specified role.

Deny privilege on CIDR range


LOAD
DENY LOAD
ON CIDR "127.0.0.1/32"
127.0.0.1/32 to disallow loading
TO role_name data from sources in that range to
the specified role.

ON GRAPH
ON GRAPH Read Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant TRAVERSE privilege on all


GRANT TRAVERSE
ON GRAPH * NODE * TO role_name
graphs and all nodes to the specified
role.
GRANT – gives privileges to roles.
DENY – denies privileges to roles.

To remove a granted or denied


REVOKE GRANT TRAVERSE
ON GRAPH * NODE * FROM role_name
privilege, prepend the privilege query
with REVOKE and replace the TO
with FROM .

Grant TRAVERSE privilege on all


GRANT TRAVERSE
ON GRAPH * RELATIONSHIP * TO
graphs and all relationships to the
role_name specified role.

Deny READ privilege on a specified


DENY READ {prop}
ON GRAPH `database-name`
property, on all relationships with a
RELATIONSHIP rel_type TO role_name specified type in a specified graph,
to the specified role.

Revoke READ privilege on a


REVOKE READ {prop}
ON GRAPH `database-name` FROM
specified property in a specified
role_name graph from the specified role.

Grant MATCH privilege on all nodes


GRANT MATCH {*}
ON HOME GRAPH ELEMENTS
and relationships with the specified
label_or_type TO role_name label/type, on the home graph, to the
specified role. This is semantically
the same as having both TRAVERSE
privilege and READ {*} privilege.

Grant READ privilege on all graphs


GRANT READ {*}
ON GRAPH *
and all nodes with a secret
FOR (n) WHERE n.secret = false property set to false to the
TO role_name
specified role.

Deny TRAVERSE privilege on all


DENY TRAVERSE
ON GRAPH *
graphs and all nodes with the
FOR (n:label) WHERE n.secret <> specified label and with a secret
false
TO role_name property not set to false to the
specified role.

Revoke MATCH privilege on all


REVOKE MATCH {*}
ON GRAPH *
graphs and all nodes with either
FOR (n:foo_label|bar_label) WHERE foo_label or bar_label and with
n.secret IS NULL
FROM role_name a secret property that is null
from the specified role.

ON GRAPH Write Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant ALL GRAPH PRIVILEGES


GRANT ALL GRAPH PRIVILEGES
ON GRAPH `database-name` TO
privilege on a specified graph to the
role_name specified role.

Short form for grant ALL GRAPH


GRANT ALL ON GRAPH `database-name`
TO role_name
PRIVILEGES privilege.

GRANT – gives privileges to roles.


DENY – denies privileges to roles.

To remove a granted or denied


privilege, prepend the privilege query
with REVOKE and replace the TO
with FROM ; ( REVOKE GRANT ALL ON
GRAPH `database-name FROM
role_name`).

Deny CREATE privilege on all nodes


DENY CREATE
ON GRAPH * NODES node_label TO
with a specified label in all graphs to
role_name the specified role.

Revoke DELETE privilege on all


REVOKE DELETE
ON GRAPH `database-name` TO
nodes and relationships in a
role_name specified graph from the specified
role.

Grant SET LABEL privilege for the


GRANT SET LABEL node_label
ON GRAPH * TO role_name
specified label on all graphs to the
specified role.

Deny REMOVE LABEL privilege for all


DENY REMOVE LABEL *
ON GRAPH `database-name` TO
labels on a specified graph to the
role_name specified role.

Grant SET PROPERTY privilege on a


GRANT SET PROPERTY {prop_name}
ON GRAPH `database-name`
specified property, on all
RELATIONSHIPS rel_type TO relationships with a specified type in
role_name
a specified graph, to the specified
role.

Grant MERGE privilege on all


GRANT MERGE {*}
ON GRAPH * NODES node_label TO
properties, on all nodes with a
role_name specified label in all graphs, to the
specified role.

Revoke WRITE privilege on all


REVOKE WRITE
ON GRAPH * FROM role_name
graphs from the specified role.

ON DATABASE
ON DATABASE Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant ALL DATABASE PRIVILEGES


GRANT ALL DATABASE PRIVILEGES
ON DATABASE * TO role_name
privilege for all databases to the
specified role.
Allows access ( GRANT ACCESS ).
Index management ( GRANT
INDEX MANAGEMENT ).
Constraint management ( GRANT
CONSTRAINT MANAGEMENT ).
Name management ( GRANT
NAME MANAGEMENT ).

Note that the privileges for starting


and stopping all databases, and
transaction management, are not
included.
Short form for grant ALL DATABASE
GRANT ALL ON DATABASE * TO
role_name
PRIVILEGES privilege.

GRANT – gives privileges to roles.


DENY – denies privileges to roles.

To remove a granted or denied


privilege, prepend the privilege query
with REVOKE and replace the TO
with FROM ; ( REVOKE GRANT ALL ON
DATABASE * FROM role_name ).

Revoke ACCESS privilege to access


REVOKE ACCESS
ON HOME DATABASE FROM role_name
and run queries against the home
database from the specified role.

Grant START privilege to start all


GRANT START
ON DATABASE * TO role_name
databases to the specified role.

Deny STOP privilege to stop the


DENY STOP
ON HOME DATABASE TO role_name
home database to the specified role.

ON DATABASE - INDEX MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant INDEX MANAGEMENT privilege


GRANT INDEX MANAGEMENT
ON DATABASE * TO role_name
to create, drop, and list indexes for
all database to the specified role.
Allow creating an index - ( GRANT
CREATE INDEX ).
Allow removing an index - ( GRANT
DROP INDEX ).
Allow listing an index - ( GRANT
SHOW INDEX ).

Grant CREATE INDEX privilege to


GRANT CREATE INDEX
ON DATABASE `database-name` TO
create indexes on a specified
role_name database to the specified role.

Grant DROP INDEX privilege to drop


GRANT DROP INDEX
ON DATABASE `database-name` TO
indexes on a specified database to
role_name the specified role.

Grant SHOW INDEX privilege to list


GRANT SHOW INDEX
ON DATABASE * TO role_name
indexes on all databases to the
specified role.

ON DATABASE - CONSTRAINT MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant CONSTRAINT MANAGEMENT


GRANT CONSTRAINT MANAGEMENT
ON DATABASE * TO role_name
privilege to create, drop, and list
constraints for all database to the
specified role.
Allow creating a constraint -
( GRANT CREATE CONSTRAINT ).
Allow removing a constraint -
( GRANT DROP CONSTRAINT ).
Allow listing a constraint -
( GRANT SHOW CONSTRAINT ).

Grant CREATE CONSTRAINT


GRANT CREATE CONSTRAINT
ON DATABASE * TO role_name
privilege to create constraints on all
databases to the specified role.

Grant DROP CONSTRAINT privilege


GRANT DROP CONSTRAINT
ON DATABASE * TO role_name
to create constraints on all databases
to the specified role.

Grant SHOW CONSTRAINT privilege


GRANT SHOW CONSTRAINT
ON DATABASE `database-name` TO
to list constraints on a specified
role_name database to the specified role.

ON DATABASE - NAME MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant NAME MANAGEMENT privilege


GRANT NAME MANAGEMENT
ON DATABASE * TO role_name
to create new labels, new
relationship types, and new property
names for all databases to the
specified role.
Allow creating a new label -
( GRANT CREATE NEW LABEL ).
Allow creating a new
relationship type - ( GRANT
CREATE NEW TYPE ).
Allow creating a new property
name - ( GRANT CREATE NEW
NAME ).
Grant CREATE NEW LABEL privilege
GRANT CREATE NEW LABEL
ON DATABASE * TO role_name
to create new labels on all databases
to the specified role.

Deny CREATE NEW TYPE privilege to


DENY CREATE NEW TYPE
ON DATABASE * TO role_name
create new relationship types on all
databases to the specified role.

Grant CREATE NEW NAME privilege


GRANT CREATE NEW NAME
ON DATABASE * TO role_name
to create new property names on all
databases to the specified role.

ON DATABASE - TRANSACTION MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant TRANSACTION MANAGEMENT


GRANT TRANSACTION MANAGEMENT (*)
ON DATABASE * TO role_name
privilege to show and terminate
transactions on all users, for all
databases, to the specified role.
Allow listing transactions -
( GRANT SHOW TRANSACTION ).
Allow terminate transactions -
( GRANT TERMINATE
TRANSACTION ).

Grant SHOW TRANSACTION privilege


GRANT SHOW TRANSACTION (*)
ON DATABASE * TO role_name
to list transactions on all users on all
databases to the specified role.
Grant SHOW TRANSACTION privilege
GRANT SHOW TRANSACTION
(user_name1, user_name2)
to list transactions by the specified
ON HOME DATABASE TO role_name1, users on home database to the
role_name2
specified roles.

Grant TERMINATE TRANSACTION


GRANT TERMINATE TRANSACTION (*)
ON DATABASE * TO role_name
privilege to terminate transactions on
all users on all databases to the
specified role.

ON DBMS
ON DBMS Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant ALL DBMS PRIVILEGES


GRANT ALL DBMS PRIVILEGES
ON DBMS TO role_name
privilege to perform management for
roles, users, databases, aliases, and
privileges to the specified role. Also
privileges to execute procedures and
user defined functions are granted.
Allow controlling roles - ( GRANT
ROLE MANAGEMENT ).
Allow controlling users - ( GRANT
USER MANAGEMENT ).
Allow controlling databases -
( GRANT DATABASE
MANAGEMENT ).
Allow controlling aliases - ( GRANT
ALIAS MANAGEMENT ).
Allow controlling privileges -
( GRANT PRIVILEGE
MANAGEMENT ).
Allow user impersonation -
( GRANT IMPERSONATE (*) ).
Allow to execute all procedures
with elevated privileges.
Allow to execute all user defined
functions with elevated
privileges.

Short form for grant ALL DBMS


GRANT ALL
ON DBMS TO role_name
PRIVILEGES privilege.

GRANT – gives privileges to roles.


DENY – denies privileges to roles.

To remove a granted or denied


privilege, prepend the privilege query
with REVOKE and replace the TO
with FROM ; ( REVOKE GRANT ALL ON
DBMS FROM role_name ).

Deny IMPERSONATE privilege to


DENY IMPERSONATE (user_name1,
user_name2)
impersonate the specified users
ON DBMS TO role_name ( user_name1 and user_name2 ) to
the specified role.

Revoke IMPERSONATE privilege to


REVOKE IMPERSONATE (*)
ON DBMS TO role_name
impersonate all users from the
specified role.

Enables the specified role to execute


GRANT EXECUTE PROCEDURE *
ON DBMS TO role_name
all procedures.
Enables the specified role to use
GRANT EXECUTE BOOSTED PROCEDURE *
ON DBMS TO role_name
elevated privileges when executing
all procedures.

Enables the specified role to execute


GRANT EXECUTE ADMIN PROCEDURES
ON DBMS TO role_name
procedures annotated with @Admin .
The procedures are executed with
elevated privileges.

Enables the specified role to execute


GRANT EXECUTE FUNCTIONS *
ON DBMS TO role_name
all user defined functions.

Enables the specified role to use


GRANT EXECUTE BOOSTED FUNCTIONS *
ON DBMS TO role_name
elevated privileges when executing
all user defined functions.

Enables the specified role to view all


GRANT SHOW SETTINGS *
ON DBMS TO role_name
configuration settings.

ON DBMS - ROLE MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant ROLE MANAGEMENT privilege


GRANT ROLE MANAGEMENT
ON DBMS TO role_name
to manage roles to the specified role.
Allow creating roles - ( GRANT
CREATE ROLE ).
Allow renaming roles - ( GRANT
RENAME ROLE ).
Allow deleting roles - ( GRANT
DROP ROLE ).
Allow assigning ( GRANT ) roles to
a user - ( GRANT ASSIGN ROLE ).
Allow removing ( REVOKE ) roles
from a user - ( GRANT REMOVE
ROLE ).
Allow listing roles - ( GRANT SHOW
ROLE ).

Grant CREATE ROLE privilege to


GRANT CREATE ROLE
ON DBMS TO role_name
create roles to the specified role.

Grant RENAME ROLE privilege to


GRANT RENAME ROLE
ON DBMS TO role_name
rename roles to the specified role.

Deny DROP ROLE privilege to delete


DENY DROP ROLE
ON DBMS TO role_name
roles to the specified role.

Grant ASSIGN ROLE privilege to


GRANT ASSIGN ROLE
ON DBMS TO role_name
assign roles to users to the specified
role.

Deny REMOVE ROLE privilege to


DENY REMOVE ROLE
ON DBMS TO role_name
remove roles from users to the
specified role.

Grant SHOW ROLE privilege to list


GRANT SHOW ROLE
ON DBMS TO role_name
roles to the specified role.
ON DBMS - USER MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant USER MANAGEMENT privilege


GRANT USER MANAGEMENT
ON DBMS TO role_name
to manage users to the specified
role.
Allow creating users - ( GRANT
CREATE USER ).
Allow renaming users - ( GRANT
RENAME USER ).
Allow modifying a user - ( GRANT
ALTER USER ).
Allow deleting users - ( GRANT
DROP USER ).
Allow listing users - ( GRANT
SHOW USER ).

Deny CREATE USER privilege to


DENY CREATE USER
ON DBMS TO role_name
create users to the specified role.

Grant RENAME USER privilege to


GRANT RENAME USER
ON DBMS TO role_name
rename users to the specified role.

Grant ALTER USER privilege to alter


GRANT ALTER USER
ON DBMS TO my_role
users to the specified role.
Allow changing a user’s
password - ( GRANT SET
PASSWORD ).
Allow adding or removing a
user’s auth providers - ( GRANT
SET AUTH ).
Allow changing a user’s home
database - ( GRANT SET USER
HOME DATABASE ).
Allow changing a user’s status -
( GRANT USER STATUS ).

Deny SET PASSWORD privilege to


DENY SET PASSWORD
ON DBMS TO role_name
alter a user password to the
specified role.

Grant SET AUTH privilege to


GRANT SET AUTH
ON DBMS TO role_name
add/remove auth providers to the
specified role.

Grant SET USER HOME DATABASE


GRANT SET USER HOME DATABASE
ON DBMS TO role_name
privilege to alter the home database
of users to the specified role.

Grant SET USER STATUS privilege


GRANT SET USER STATUS
ON DBMS TO role_name
to alter user account status to the
specified role.

Grant DROP USER privilege to delete


GRANT DROP USER
ON DBMS TO role_name
users to the specified role.

Deny SHOW USER privilege to list


DENY SHOW USER
ON DBMS TO role_name
users to the specified role.
ON DBMS - DATABASE MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant DATABASE MANAGEMENT


GRANT DATABASE MANAGEMENT
ON DBMS TO role_name
privilege to manage databases to the
specified role.
Allow creating standard
databases - ( GRANT CREATE
DATABASE ).
Allow deleting standard
databases - ( GRANT DROP
DATABASE ).
Allow modifying standard
databases - ( GRANT ALTER
DATABASE ).
Allow managing composite
databases - ( GRANT COMPOSITE
DATABASE MANAGEMENT ).

Grant CREATE DATABASE privilege


GRANT CREATE DATABASE
ON DBMS TO role_name
to create standard databases to the
specified role.

Grant DROP DATABASE privilege to


GRANT DROP DATABASE
ON DBMS TO role_name
delete standard databases to the
specified role.

Grant ALTER DATABASE privilege to


GRANT ALTER DATABASE
ON DBMS TO role_name
alter standard databases the
specified role.
Allow modifying access mode
for standard databases - ( GRANT
SET DATABASE ACCESS ).
Allow modifying topology
settings for standard databases.
Grant SET DATABASE ACCESS
GRANT SET DATABASE ACCESS
ON DBMS TO role_name
privilege to set database access
mode for standard databases to the
specified role.

Grant all privileges to manage


GRANT COMPOSITE DATABASE
MANAGEMENT
composite databases to the specified
ON DBMS TO role_name role.
Allow creating composite
databases - ( CREATE COMPOSITE
DATABASE ).
Allow deleting composite
databases - ( DROP COMPOSITE
DATABASE ).

Denies the specified role the


DENY CREATE COMPOSITE DATABASE
ON DBMS TO role_name
privilege to create composite
databases.

Revokes the granted and denied


REVOKE DROP COMPOSITE DATABASE
ON DBMS FROM role_name
privileges to delete composite
databases from the specified role.

Enables the specified role to show,


GRANT SERVER MANAGEMENT
ON DBMS TO role_name
enable, rename, alter, reallocate,
deallocate, and drop servers.

Denies the specified role the


DENY SHOW SERVERS
ON DBMS TO role_name
privilege to show information about
the serves.
ON DBMS - ALIAS MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant ALIAS MANAGEMENT privilege


GRANT ALIAS MANAGEMENT
ON DBMS TO role_name
to manage aliases to the specified
role.
Allow creating aliases - ( GRANT
CREATE ALIAS ).
Allow deleting aliases - ( GRANT
DROP ALIAS ).
Allow modifying aliases - ( GRANT
ALTER ALIAS ).
Allow listing aliases - ( GRANT
SHOW ALIAS ).

Grant CREATE ALIAS privilege to


GRANT CREATE ALIAS
ON DBMS TO role_name
create aliases to the specified role.

Grant DROP ALIAS privilege to


GRANT DROP ALIAS
ON DBMS TO role_name
delete aliases to the specified role.

Grant ALTER ALIAS privilege to


GRANT ALTER ALIAS
ON DBMS TO role_name
alter aliases to the specified role.

Grant SHOW ALIAS privilege to list


GRANT SHOW ALIAS
ON DBMS TO role_name
aliases to the specified role.
ON DBMS - ROLE MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant ROLE MANAGEMENT privilege


GRANT ROLE MANAGEMENT
ON DBMS TO role_name
to manage roles to the specified role.
Allow creating roles - ( GRANT
CREATE ROLE ).
Allow renaming roles - ( GRANT
RENAME ROLE ).
Allow deleting roles - ( GRANT
DROP ROLE ).
Allow assigning ( GRANT ) roles to
a user - ( GRANT ASSIGN ROLE ).
Allow removing ( REVOKE ) roles
from a user - ( GRANT REMOVE
ROLE ).
Allow listing roles - ( GRANT SHOW
ROLE ).

Grant CREATE ROLE privilege to


GRANT CREATE ROLE
ON DBMS TO role_name
create roles to the specified role.

Grant RENAME ROLE privilege to


GRANT RENAME ROLE
ON DBMS TO role_name
rename roles to the specified role.

Deny DROP ROLE privilege to delete


DENY DROP ROLE
ON DBMS TO role_name
roles to the specified role.

Grant ASSIGN ROLE privilege to


GRANT ASSIGN ROLE
ON DBMS TO role_name
assign roles to users to the specified
role.

Deny REMOVE ROLE privilege to


DENY REMOVE ROLE
ON DBMS TO role_name
remove roles from users to the
specified role.

Grant SHOW ROLE privilege to list


GRANT SHOW ROLE
ON DBMS TO role_name
roles to the specified role.

ON DBMS - PRIVILEGE MANAGEMENT Privileges

AuraDB Business Critical AuraDB Virtual Dedicated Cloud Neo4j Enterprise Edition

Grant PRIVILEGE MANAGEMENT


GRANT PRIVILEGE MANAGEMENT
ON DBMS TO role_name
privilege to manage privileges for the
Neo4j DBMS to the specified role.
Allow assigning ( GRANT|DENY )
privileges for a role - ( GRANT
ASSIGN PRIVILEGE ).
Allow removing ( REVOKE )
privileges for a role - ( GRANT
REMOVE PRIVILEGE ).
Allow listing privileges - ( GRANT
SHOW PRIVILEGE ).

Grant ASSIGN PRIVILEGE privilege,


GRANT ASSIGN PRIVILEGE
ON DBMS TO role_name
allows the specified role to assign
privileges for roles.

Grant REMOVE PRIVILEGE privilege,


GRANT REMOVE PRIVILEGE
ON DBMS TO role_name
allows the specified role to remove
privileges for roles.

Grant SHOW PRIVILEGE privilege to


GRANT SHOW PRIVILEGE
ON DBMS TO role_name
list privileges to the specified role.

LEARN SOCIAL CONTACT US →

 Sandbox  Twitter US: 1-855-636-4532


 Neo4j Community  Meetups Sweden +46 171 480 113
Site  Github UK: +44 20 3868 3223
 Neo4j Developer Blog  Stack Overflow France: +33 (0) 1 88 46 13
 Neo4j Videos 20
 GraphAcademy Want to Speak?
 Neo4j Labs

© 2025 Neo4j, Inc.


Terms | Privacy | Sitemap

Neo4j®, Neo Technology®, Cypher®, Neo4j® Bloom™ and Neo4j® Aura™ are registered
trademarks of Neo4j, Inc. All other marks are owned by their respective companies.

You might also like