Neo4j: Reserved keywords Cheat Sheet

Clauses

  • CALL
  • CREATE
  • DELETE
  • DETACH
  • EXISTS
  • FOREACH
  • LOAD
  • MATCH
  • MERGE
  • OPTIONAL
  • REMOVE
  • RETURN
  • SET
  • START
  • UNION
  • UNWIND
  • WITH

Subclauses

  • LIMIT
  • ORDER
  • SKIP
  • WHERE
  • YIELD

Modifiers

  • ASC
  • ASCENDING
  • ASSERT
  • BY
  • CSV
  • DESC
  • DESCENDING
  • ON

Expressions

  • ALL
  • CASE
  • ELSE
  • END
  • THEN
  • WHEN

Operators

  • AND
  • AS
  • CONTAINS
  • DISTINCT
  • ENDS
  • IN
  • IS
  • NOT
  • OR
  • STARTS
  • XOR

Schema

  • CONSTRAINT
  • CREATE
  • DROP
  • EXISTS
  • INDEX
  • NODE
  • KEY
  • UNIQUE

Hints

  • INDEX
  • JOIN
  • PERIODIC
  • COMMIT
  • SCAN
  • USING

Literals

  • false
  • null
  • true

Reserved for future use

  • ADD
  • DO
  • FOR
  • MANDATORY
  • OF
  • REQUIRE
  • SCALAR

Neo4j: Operators Cheat Sheet

Operators at a glance:

Aggregation operatorsDISTINCT
Property operators. for static property access, [] for dynamic property access, = for replacing all properties, += for mutating specific properties
Mathematical operators+-*/%^
Comparison operators=<><><=>=IS NULLIS NOT NULL
String-specific comparison operatorsSTARTS WITHENDS WITHCONTAINS
Boolean operatorsANDORXORNOT
String operators+ for concatenation, =~ for regex matching
Temporal operators+ and - for operations between durations and temporal instants/durations, * and / for operations between durations and numbers
Map operators. for static value access by key, [] for dynamic value access by key
List operators+ for concatenation, IN to check existence of an element in a list, [] for accessing element(s) dynamically

Neo4j: Clauses Cheat Sheet

Reading clauses

ClauseQueryDescription
MATCHMATCH (n) RETURN nSpecify the patterns to search for in the database.
OPTIONAL MATCHMATCH (node:label {properties. . . . . . . . . . . . . .}) OPTIONAL MATCH (node)-->(x) RETURN xSpecify the patterns to search for in the database while using nulls for missing parts of the pattern.

Projecting clauses

ClauseQueryDescription
RETURN …​ [AS]MATCH (n { name: 'A' })
RETURN n
Defines what to include in the query result set.
WITH …​ [AS]MATCH (n) WITH n ORDER BY n.property RETURN collect(n.property)Allows query parts to be chained together, piping the results from one to be used as starting points or criteria in the next.
UNWIND …​ [AS]UNWIND [a, b, c, d] AS x RETURN xExpands a list into a sequence of rows.

Reading sub-clauses

Sub-clauseQueryDescription
WHEREMATCH (label) WHERE label.country = "property" RETURN labelAdds constraints to the patterns in a MATCH or OPTIONAL MATCH clause or filters the results of a WITH clause.
ORDER BY [ASC[ENDING] | DESC[ENDING]]MATCH (n) RETURN n.property1, n.property2 . . . . . . . .
ORDER BY n.property
A sub-clause following RETURN or WITH, specifying that the output should be sorted in either ascending (the default) or descending order.
SKIPMATCH (n) RETURN n.name, n.runs
ORDER BY n.runs DESC
SKIP numberofrows
Defines from which row to start including the rows in the output.
LIMITMATCH (n) RETURN n ORDER BY n.name
LIMIT numberofrows
Constrains the number of rows in the output.

Reading hints

HintDescription
USING INDEXIndex hints are used to specify which index, if any, the planner should use as a starting point.
USING INDEX SEEKIndex seek hint instructs the planner to use an index seek for this clause.
USING SCANScan hints are used to force the planner to do a label scan (followed by a filtering operation) instead of using an index.
USING JOINJoin hints are used to enforce a join operation at specified points.

Writing clauses

ClauseQueryDescription
CREATECREATE (node_name);
or
CREATE (node1),(node2)
Create nodes and relationships.
DELETEMATCH (n) DELETE n
Delete nodes, relationships or paths. Any node to be deleted must also have all associated relationships explicitly deleted.
DETACH DELETEMATCH (n) DETACH DELETE nDelete a node or set of nodes. All associated relationships will automatically be deleted.
SETMATCH (node:label{properties . . . . . . . . . . . . . . })
SET node.property = value
RETURN node
Update labels on nodes and properties on nodes and relationships.
REMOVEMATCH (node:label{properties . . . . . . . })
REMOVE node.property RETURN node
Remove properties and labels from nodes and relationships.
FOREACHMATCH p = (start node)-[*]->(end node)
WHERE start.node = "node_name" AND end.node = "node_name"
FOREACH (n IN nodes(p)| SET n.marked = TRUE)
Update data within a list, whether components of a path, or the result of aggregation.

Reading/Writing clauses

ClauseQueryDescription
MERGEMERGE (node: label {properties . . . . . . . })Ensures that a pattern exists in the graph. Either the pattern already exists, or it needs to be created.
— ON CREATEMERGE (node:label {properties . . . . . . . . . . .})
ON CREATE SET property.isCreated ="true"
Used in conjunction with MERGE, this write sub-clause specifies the actions to take if the pattern needs to be created.
— ON MATCHMERGE (node:label {properties . . . . . . . . . . .})
ON MATCH SET property.isFound ="true"
Used in conjunction with MERGE, this write sub-clause specifies the actions to take if the pattern already exists.
CALL […​YIELD]CALL dbms.procedures() YIELD name, signature, description as text
WHERE name STARTS WITH 'db.'
RETURN * ORDER BY name ASC
Invokes a procedure deployed in the database and return any results.

Set operations

ClauseQueryDescription
UNION<MATCH Command1>
UNION

<MATCH Command2>
Combines the result of multiple queries into a single result set. Duplicates are removed.
UNION ALL<MATCH Command1> UNION ALL
<MATCH Command2>
Combines the result of multiple queries into a single result set. Duplicates are retained.

Subquery clauses

ClauseDescription
CALL { …​ }Evaluates a subquery, typically used for post-union processing or aggregations.

Multiple graphs

ClauseQueryDescription
USEUSE <graph> <other clauses>Determines which graph a query, or query part, is executed against.

Neo4j: Predicate Functions Cheat Sheet

all()

returns true if the predicate holds for all elements in the given list. null is returned if the list is null or all of its elements are null

all(variable IN list WHERE predicate)

any()

returns true if the predicate holds for at least one element in the given list. null is returned if the list is null or all of its elements are null

any(variable IN list WHERE predicate)

exists()

returns true if a match for the given pattern exists in the graph, or if the specified property exists in the node, relationship or map. null is returned if the input argument is null

exists(pattern-or-property)

none()

returns true if the predicate holds for no element in the given list. null is returned if the list is null or all of its elements are null

none(variable IN list WHERE predicate)

single()

returns true if the predicate holds for exactly one of the elements in the given list. null is returned if the list is null or all of its elements are null

single(variable IN list WHERE predicate)

Neo4j: Scalar functions Cheat Sheet

coalesce()

returns the first non-null value in the given list of expressions.

coalesce(expression [, expression]*)

expression: An expression which may return null.

endNode()

returns the end node of a relationship.

endNode(relationship)

head()

returns the first element in a list.

head(list)

id()

returns the id of a relationship or node.

id(expression)

last()

returns the last element in a list.

last(expression)

length()

returns the length of a path.

length(path)

properties() 

returns a map containing all the properties of a node or relationship. If the argument is already a map, it is returned unchanged.

properties(expression)

randomUUID()

returns a randomly-generated Universally Unique Identifier (UUID), also known as a Globally Unique Identifier (GUID). This is a 128-bit value with strong guarantees of uniqueness.

randomUUID()

size()

returns the number of elements in a list.

size(list)

size() applied to pattern expression

This is the same size() method as described above, but instead of passing in a list directly, a pattern expression can be provided that can be used in a match query to provide a new set of results. These results are a list of paths. The size of the result is calculated, not the length of the expression itself.

size(pattern expression)

size() applied to string

returns the number of Unicode characters in a string.

size(string)

startNode()

returns the start node of a relationship.

startNode(relationship)

timestamp()

returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. It is the equivalent of datetime().epochMillis

timestamp()

toBoolean()

converts a string value to a boolean value.

toBoolean(expression)

toFloat()

converts an integer or string value to a floating point number.

toFloat(expression)

toInteger()

converts a floating point or string value to an integer value.

toInteger(expression)

type()

returns the string representation of the relationship type.

type(relationship)

Neo4j: Mathematical functions Cheat Sheet

Numeric

abs()

abs(expression)

ceil()

ceil(expression)

floor()

floor(expression)

rand()

rand()

sign()

sign(expression)

Logarithmic

e()

e()

exp()

e(expression)

log()

log(expression)

log10()

log10(expression)

sqrt()

sqrt(expression)

Trigonometric

acos()

acos(expression)

asin()

asin(expression)

atan()

atan(expression)

atan2()

atan2(expression1, expression2)

cos()

cos(expression)

cot()

cot(expression)

degrees()

degrees(expression)

haversin()

haversin(expression)

pi()

pi()

radians()

radians(expression)

sin()

sin(expression)

tan()

tan(expression)

Neo4j: String functions Cheat Sheet

left()

left(original, length)

original: An expression that returns a string.

n: An expression that returns a positive integer.

ltrim()

lTrim(original)

An expression that returns a string.

replace()

replace(original, search, replace)

original: An expression that returns a string.

search: An expression that specifies the string to be replaced in original.

replace: An expression that specifies the replacement string.

reverse()

reverse(original)

right()

right(original, length)

rtrim()

rTrim(original)

split()

split(original, splitDelimiter)

splitDelimiter: The string with which to split original.

substring()

substring(original, start [, length])

toLower()

toLower(original)

toString()

toString(expression)

toUpper()

toUpper(original)

trim()

trim(original)

Neo4j: Temporal unctions – Duration cheat sheet

Syntax:

duration([ {years, quarters, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds} ])

Creating a Duration from a string:

duration(temporalAmount)

duration.between()

duration.between(instant1, instant2)

Returns the Duration value equal to the difference between the two given instants.

duration.inMonths()

duration.inMonths(instant1, instant2)

Returns the Duration value equal to the difference in whole months, quarters or years between the two given instants.

duration.inDays()

duration.inDays(instant1, instant2)

Returns the Duration value equal to the difference in whole days or weeks between the two given instants.

duration.inSeconds()

duration.inSeconds(instant1, instant2)

Returns the Duration value equal to the difference in seconds and fractions of seconds, or minutes or hours, between the two given instants.

Neo4j: Temporal functions – Instant Types cheat sheet

date() function

Getting the current Date

date([ {timezone} ])

Creating a calendar (Year-Month-Day) Date

date({year [, month, day]})

Creating a week (Year-Week-Day) Date

date({year [, week, dayOfWeek]})

Creating a quarter (Year-Quarter-Day) Date

date({year [, quarter, dayOfQuarter]})

Creating an ordinal (Year-Day) Date

date({year [, ordinalDay]})

Creating a Date from a string

date(temporalValue)

Creating a Date using other temporal values as components

date({date [, year, month, day, week, dayOfWeek, quarter, dayOfQuarter, ordinalDay]})

datetime() function

Getting the current DateTime

datetime([ {timezone} ])

Creating a calendar (Year-Month-Day) DateTime

datetime({year [, month, day, hour, minute, second, millisecond, microsecond, nanosecond, timezone]})

Creating a week (Year-Week-Day) DateTime

datetime({year [, week, dayOfWeek, hour, minute, second, millisecond, microsecond, nanosecond, timezone]})

Creating an ordinal (Year-Day) DateTime

datetime({year [, ordinalDay, hour, minute, second, millisecond, microsecond, nanosecond, timezone]})

localdatetime() function

Getting the current LocalDateTime

localdatetime([ {timezone} ])

time() function

Getting the current Time

time([ {timezone} ])

Creating a Time

time({hour [, minute, second, millisecond, microsecond, nanosecond, timezone]})

Creating a Time from a string

time(temporalValue)

Creating a Time using other temporal values as components

time({time [, hour, …​, timezone]})

Truncating a Time

time.truncate(unit [, temporalInstantValue [, mapOfComponents ] ])

Neo4j: Spatial functions cheat sheet

distance()

distance(point1, point2)

point1 returning a point in either a geographic or cartesian coordinate system.

point2 returning a point in the same CRS as ‘point1’.

point() – WGS 84 2D

point({longitude | x, latitude | y [, crs][, srid]})

Returns a 2D point in the WGS 84 CRS corresponding to the given coordinate values.

point() – WGS 84 3D

point({longitude | x, latitude | y, height | z, [, crs][, srid]}) 

Returns a 3D point in the WGS 84 CRS corresponding to the given coordinate values.

point() – Cartesian 2D

point({x, y [, crs][, srid]}) 

Returns a 2D point in the Cartesian CRS corresponding to the given coordinate values.

point() – Cartesian 3D

point({x, y, z, [, crs][, srid]}) 

Returns a 3D point in the Cartesian CRS corresponding to the given coordinate values.

Neo4j: LOAD CSV functions cheat sheet

linenumber()

linenumber()

returns the line number that LOAD CSV is currently using (An Integer)

file()

file()

returns the absolute path of the file that LOAD CSV is using (A String)

Neo4j: Aggregation Function Cheat Sheet

Count()

COUNT(expression) 

Max()

MAX(expression) 

An expression returning a set containing any combination of property types and lists thereof.

Min()

MIN(expression) 

An expression returning a set containing any combination of property types and lists thereof.

Sum()

SUM(expression)

An expression returning a set of numeric values or Durations

Avg()

AVG(expression)

An expression returning a set of numeric values or Durations

Collect()

COLLECT(expression)

An expression returning a set of values.

percentileCont()

percentileCont(expression, percentile)

An expression returning a numeric expression.

A percentile returning a numeric value between 0.0 and 1.0

percentileDisc()

percentileDisc(expression, percentile)

An expression returning a numeric expression.

A percentile returning a numeric value between 0.0 and 1.0

stDev()

stDev(expression)

An expression returning a numeric expression.

stDevP()

stDevP(expression)

An expression returning a numeric expression.

Neo4j: Databases Cheat Sheet

Listing databases

SHOW { DATABASE db | DATABASES | DEFAULT DATABASE }
    [YIELD field1[, field2] [ORDER BY field1 [, field2]] [SKIP n] [LIMIT n]]
    [WHERE expression]

A particular database can be seen using the command SHOW DATABASE name.

The default database can be seen using the command SHOW DEFAULT DATABASE.

Creating databases

CREATE DATABASE customers

Appending IF NOT EXISTS to the command will ensure that no exception is thrown and nothing happens should the database already exist.

CREATE DATABASE customers IF NOT EXISTS

Adding OR REPLACE to the command will result in any existing database being deleted and a new one created.

CREATE OR REPLACE DATABASE customers

Stopping databases 

STOP DATABASE customers

Starting databases 

START DATABASE customers

Deleting databases 

DROP DATABASE customers

Neo4j: Indexes Cheat Sheet

Indexes for search performance

CommandDescription
CREATE INDEX [index_name] FOR (n:LabelName) ON (n.propertyName)Create a single-property index.
CREATE INDEX [index_name] FOR (n:LabelName) ON (n.propertyName_1, n.propertyName_2, … n.propertyName_n)Create a composite index.
DROP INDEX index_nameDrop an index
CALL db.indexesList all indexes in the database.
DROP INDEX ON :LabelName(propertyName)Drop a single-property index without specifying a name.
DROP INDEX ON :LabelName (n.propertyName_1, n.propertyName_2, … n.propertyName_n)Drop a composite index without specifying a name.

Indexes for full-text search

UsageProcedure
Create full-text node indexdb.index.fulltext.createNodeIndex
Create full-text relationship indexdb.index.fulltext.createRelationshipIndex
List available analyzersdb.index.fulltext.listAvailableAnalyzers
Use full-text node indexdb.index.fulltext.queryNodes
Use full-text relationship indexdb.index.fulltext.queryRelationships
Drop full-text indexdb.index.fulltext.drop
Eventually consistent indexesdb.index.fulltext.awaitEventuallyConsistentIndexRefresh

Neo4j: Constraints Cheat Sheet

Creating an Index

CREATE INDEX ON:label (node)  

Deleting an Index

DROP INDEX ON:label(node) 

Create a unique node property constraint

CREATE CONSTRAINT [constraint_name]
ON (n:LabelName)
ASSERT n.propertyName IS UNIQUE

Create a node property existence constraint

CREATE CONSTRAINT [constraint_name]
ON (n:LabelName)
ASSERT EXISTS (n.propertyName)

Create a relationship property existence constraint

CREATE CONSTRAINT [constraint_name]
ON ()-[R:RELATIONSHIP_TYPE]-()
ASSERT EXISTS (R.propertyName)

Create a node key constraint

CREATE CONSTRAINT [constraint_name]
ON (n:LabelName)
ASSERT (n.propertyName_1,
n.propertyName_2,
…
n.propertyName_n)
IS NODE KEY

Drop a constraint

DROP CONSTRAINT constraint_name

List all constraints in the database

CALL db.constraints

Drop a unique constraint without specifying a name

DROP CONSTRAINT
ON (n:LabelName)
ASSERT n.propertyName IS UNIQUE

Drop an exists constraint without specifying a name

DROP CONSTRAINT
ON (n:LabelName)
ASSERT EXISTS (n.propertyName)

Drop a relationship property existence constraint without specifying a name

DROP CONSTRAINT
ON ()-[R:RELATIONSHIP_TYPE]-()
ASSERT EXISTS (R.propertyName)

Drop a node key constraint without specifying a name

DROP CONSTRAINT
ON (n:LabelName)
ASSERT (n.propertyName_1,
n.propertyName_2,
…
n.propertyName_n)
IS NODE KEY