Neo4j Writing Data

Spatial functions

point({x: $x, y: $y})

Returns a point in a 2D cartesian coordinate system.

point({latitude: $y, longitude: $x})

Returns a point in a 2D geographic coordinate system, with coordinates specified in decimal degrees.

point({x: $x, y: $y, z: $z})

Returns a point in a 3D cartesian coordinate system.

point({latitude: $y, longitude: $x, height: $z})

Returns a point in a 3D geographic coordinate system, with latitude and longitude in decimal degrees, and height in meters.

distance(point({x: $x1, y: $y1}), point({x: $x2, y: $y2}))

Returns a floating point number representing the linear distance between two points. The returned units will be the same as those of the point coordinates, and it will work for both 2D and 3D cartesian points.

distance(point({latitude: $y1, longitude: $x1}), point({latitude: $y2, longitude: $x2}))

Returns the geodesic distance between two points in meters. It can be used for 3D geographic points as well.

Path functions

length(path)

The number of relationships in the path.

nodes(path)

The nodes in the path as a list.

relationships(path)

The relationships in the path as a list.

[x IN nodes(path) | x.prop]

Extract properties from the nodes in a path.

Functions

coalesce(n.property, $defaultValue)

The first non-null expression.

timestamp()

Milliseconds since midnight, January 1, 1970 UTC.

id(nodeOrRelationship)

The internal id of the relationship or node.

toInteger($expr)

Converts the given input into an integer if possible; otherwise it returns null.

toFloat($expr)

Converts the given input into a floating point number if possible; otherwise it returns null.

toBoolean($expr)

Converts the given input into a boolean if possible; otherwise it returns null.

keys($expr)

Returns a list of string representations for the property names of a node, relationship, or map.

properties($expr)

Returns a map containing all the properties of a node or relationship.

List expressions

size($list)

Number of elements in the list.

reverse($list)

Reverse the order of the elements in the list.

head($list), last($list), tail($list)

head() returns the first, last() the last element of the list. tail() returns all but the first element. All return null for an empty list.

[x IN list | x.prop]

A list of the value of the expression for each element in the original list.

[x IN list WHERE x.prop <> $value]

A filtered list of the elements where the predicate is true.

[x IN list WHERE x.prop <> $value | x.prop]

A list comprehension that filters a list and extracts the value of the expression for each element in that list.

reduce(s = "", x IN list | s + x.prop)

Evaluate expression for each element in the list, accumulate the results.

CASE

CASE n.eyes
 WHEN 'blue' THEN 1
 WHEN 'brown' THEN 2
 ELSE 3
END

Return THEN value from the matching WHEN value. The ELSE value is optional, and substituted for null if missing.

CASE
 WHEN n.eyes = 'blue' THEN 1
 WHEN n.age < 40 THEN 2
 ELSE 3
END

Return THEN value from the first WHEN predicate evaluating to true. Predicates are evaluated in order.

List predicates

all(x IN coll WHERE x.property IS NOT NULL)

Returns true if the predicate is true for all elements in the list.

any(x IN coll WHERE x.property IS NOT NULL)

Returns true if the predicate is true for at least one element in the list.

none(x IN coll WHERE x.property IS NOT NULL)

Returns true if the predicate is false for all elements in the list.

single(x IN coll WHERE x.property IS NOT NULL)

Returns true if the predicate is true for exactly one element in the list.

Predicates

n.property <> $value

Use comparison operators.

toString(n.property) = $value

Use functions.

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

Use boolean operators to combine predicates.

1 <= n.number <= 10

Use chained operators to combine predicates.

n:Person

Check for node labels.

variable IS NOT NULL

Check if something is not null, e.g. that a property exists.

n.property IS NULL OR n.property = $value

Either the property does not exist or the predicate is true.

n.property = $value

Non-existing property returns null, which is not equal to anything.

n["property"] = $value

Properties may also be accessed using a dynamically computed property name.

n.property STARTS WITH 'Tim' OR
n.property ENDS WITH 'n' OR
n.property CONTAINS 'goodie'

String matching.

n.property =~ 'Tim.\*'

String regular expression matching.

(n)-[:KNOWS]->(m)

Ensure the pattern has at least one match.

NOT (n)-[:KNOWS]->(m)

Exclude matches to (n)-[:KNOWS]->(m) from the result.

n.property IN [$value1, $value2]

Check if an element exists in a list.

Maps

{name: 'Alice', age: 38,
 address: {city: 'London', residential: true}}

Literal maps are declared in curly braces much like property maps. Lists are supported.

WITH {person: {name: 'Anne', age: 25}} AS p
RETURN p.person.name

Access the property of a nested map.

MERGE (p:Person {name: $map.name})
  ON CREATE SET p = $map

Maps can be passed in as parameters and used either as a map or by accessing keys.

MATCH (matchedNode:Person)
RETURN matchedNode

Nodes and relationships are returned as maps of their data.

map.name, map.age, map.children[0]

Map entries can be accessed by their keys. Invalid keys result in an error.

Lists

['a', 'b', 'c'] AS list

Literal lists are declared in square brackets.

size($list) AS len, $list[0] AS value

Lists can be passed in as parameters.

range($firstNum, $lastNum, $step) AS list

range() creates a list of numbers (step is optional), other functions returning lists are: labels(), nodes(), relationships().

MATCH p = (a)-[:KNOWS\*]->()
RETURN relationships(p) AS r

The list of relationships comprising a variable length path can be returned using named paths and relationships().

RETURN matchedNode.list[0] AS value,
       size(matchedNode.list) AS len

Properties can be lists of strings, numbers or booleans.

list[$idx] AS value,
list[$startIdx..$endIdx] AS slice

List elements can be accessed with idx subscripts in square brackets. Invalid indexes return null. Slices can be retrieved with intervals from start_idx to end_idx, each of which can be omitted or negative. Out of range elements are ignored.

UNWIND $names AS name
MATCH (n {name: name})
RETURN avg(n.age)

With UNWIND, any list can be transformed back into individual rows. The example matches all names from a list of names.

MATCH (a)
RETURN [(a)-->(b) WHERE b.name = 'Bob' | b.age]

Pattern comprehensions may be used to do a custom projection from a match directly into a list.

MATCH (person)
RETURN person { .name, .age}

Map projections may be easily constructed from nodes, relationships and other map values.

Labels

CREATE (n:Person {name: $value})

Create a node with label and property.

MERGE (n:Person {name: $value})

Matches or creates unique node(s) with the label and property.

SET n:Spouse:Parent:Employee

Add label(s) to a node.

MATCH (n:Person)

Matches nodes labeled Person.

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

Matches nodes labeled Person with the given name.

WHERE (n:Person)

Checks the existence of the label on the node.

labels(n)

Labels of the node.

REMOVE n:Person

Remove the label from the node.

SHOW FUNCTIONS and PROCEDURES

SHOW FUNCTIONS

Listing all available functions.

SHOW PROCEDURES EXECUTABLE YIELD name

List all procedures that can be executed by the current user and return only the name of the procedures.

USE

USE myDatabase

Select myDatabase to execute query, or query part, against.

USE neo4j
MATCH (n:Person)-[:KNOWS]->(m:Person)
WHERE n.name = 'Alice'

MATCH query executed against neo4j database.

Patterns

(n:Person)

Node with Person label.

(n:Person:Swedish)

Node with both Person and Swedish labels.

(n:Person {name: $value})

Node with the declared properties.

()-[r {name: $value}]-()

Matches relationships with the declared properties.

(n)-->(m)

Relationship from n to m.

(n)--(m)

Relationship in any direction between n and m.

(n:Person)-->(m)

Node n labeled Person with relationship to m.

(m)<-[:KNOWS]-(n)

Relationship of type KNOWS from n to m.

(n)-[:KNOWS|:LOVES]->(m)

Relationship of type KNOWS or of type LOVES from n to m.

(n)-[r]->(m)

Bind the relationship to variable r.

(n)-[\*1..5]->(m)

Variable length path of between 1 and 5 relationships from n to m.

(n)-[\*]->(m)

Variable length path of any number of relationships from n to m. (See Performance section.)

(n)-[:KNOWS]->(m {property: $value})

A relationship of type KNOWS from a node n to a node m with the declared property.

shortestPath((n1:Person)-[\*..6]-(n2:Person))

Find a single shortest path.

allShortestPaths((n1:Person)-[\*..6]->(n2:Person))

Find all shortest paths.

size((n)-->()-->())

Count the paths matching the pattern.

null

  • 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.
  • 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 doesn’t exist yields null.
  • In OPTIONAL MATCH clauses, nulls will be used for missing parts of the pattern.

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

Import

LOAD CSV FROM
'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists.csv' AS line
CREATE (:Artist {name: line[1], year: toInteger(line[2])})

Load data from a CSV file and create nodes.

LOAD CSV WITH HEADERS FROM
'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists-with-headers.csv' AS line
CREATE (:Artist {name: line.Name, year: toInteger(line.Year)})

Load CSV data which has headers.

USING PERIODIC COMMIT 500
LOAD CSV WITH HEADERS FROM
'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists-with-headers.csv' AS line
CREATE (:Artist {name: line.Name, year: toInteger(line.Year)})

Commit the current transaction after every 500 rows when importing large amounts of data.

LOAD CSV FROM
'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists-fieldterminator.csv'
AS line FIELDTERMINATOR ';'
CREATE (:Artist {name: line[1], year: toInteger(line[2])})

Use a different field terminator, not the default which is a comma (with no whitespace around it).

LOAD CSV FROM
'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists.csv' AS line
RETURN DISTINCT file()

Returns the absolute path of the file that LOAD CSV is processing, returns null if called outside of LOAD CSV context.

LOAD CSV FROM
'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists.csv' AS line
RETURN linenumber()

Returns the line number that LOAD CSV is currently processing, returns null if called outside of LOAD CSV context.

CALL procedure

CALL db.labels() YIELD label

This shows a standalone call to the built-in procedure db.labels to list all labels used in the database. Note that required procedure arguments are given explicitly in brackets after the procedure name.

CALL db.labels() YIELD *

Standalone calls may use YIELD * to return all columns.

CALL java.stored.procedureWithArgs

Standalone calls may omit YIELD 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'}.

CALL db.labels() YIELD label
RETURN count(label) AS count

Calls the built-in procedure 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.

CALL subquery

CALL {
  MATCH (p:Person)-[:FRIEND\_OF]->(other:Person) RETURN p, other
  UNION
  MATCH (p:Child)-[:CHILD\_OF]->(other:Parent) RETURN p, other
}

This calls a subquery with two union parts. The result of the subquery can afterwards be post-processed.

FOREACH

FOREACH (r IN relationships(path) |
  SET r.marked = true)

Execute a mutating operation for each relationship in a path.

FOREACH (value IN coll |
 CREATE (:Person {name: value}))

Execute a mutating operation for each element in a list.

REMOVE

REMOVE n:Person

Remove a label from n.

REMOVE n.property

Remove a property.

DELETE

DELETE n, r

Delete a node and a relationship.

DETACH DELETE n

Delete a node and all relationships connected to it.

MATCH (n)
DETACH DELETE n

Delete all nodes and relationships from the database.

MERGE

MERGE (n:Person {name: $value})
  ON CREATE SET n.created = timestamp()
  ON MATCH SET
    n.counter = coalesce(n.counter, 0) + 1,
    n.accessTime = timestamp()

Match a pattern or create it if it does not exist. Use ON CREATE and ON MATCH for conditional updates.

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

MERGE finds or creates a relationship between the nodes.

MATCH (a:Person {name: $value1})
MERGE
  (a)-[r:KNOWS]->(b:Person {name: $value3})

MERGE finds or creates paths attached to the node.

SET

SET n.property1 = $value1,
    n.property2 = $value2

Update or create a property.

SET n = $map

Set all properties. This will remove any existing properties.

SET n += $map

Add and update properties, while keeping existing ones.

SET n:Person

Adds a label Person to a node.

CREATE

CREATE (n {name: $value})

Create a node with the given properties.

CREATE (n $map)

Create a node with the given properties.

UNWIND $listOfMaps AS properties
CREATE (n) SET n = properties

Create nodes with the given properties.

CREATE (n)-[r:KNOWS]->(m)

Create a relationship with the given type and direction; bind a variable to it.

CREATE (n)-[:LOVES {since: $value}]->(m)

Create a relationship with the given type, direction, and properties.

Comments