cancel
Showing results for 
Search instead for 
Did you mean: 

Protip: Dynamic Node Labels in Cypher using APOC

abk
Neo4j
Neo4j

Cypher treats node labels as symbols. They are not data. They're closer to property names, almost like a valueless property.

Symbols must be static terms in a Cypher statement. There are no operations you can perform to create or modify label terms.

To create labels from strings or string expressions, use APOC's apoc.create.addLabels()

Examples

1. Create label from a list of strings

Create a plain node, then set the labels using a list of strings:

CREATE (n) WITH n
CALL apoc.create.addLabels(n, ["Aye", "Bee", "Sea"]) YIELD node
RETURN node

This is exactly equivalent to the following Cypher:

CREATE (n:Aye:Bee:Sea) RETURN n

But using a list of strings means we can do clever things...

2. Create label from string expression

Create a node, get the current date, then set a label on that node based on the date.

CREATE (n) WITH n, date().ordinalDay as dayOfYear
CALL apoc.create.addLabels(n, ["DAY_" + toString(dayOfYear)]) YIELD node
RETURN node

3. Create label from query parameter

Pass in a string value as a query paramter, then use it to set a label.

In Browser, you can set a query parameter like this: :param parameterizedLabel => "DynaLabel"

Then use it like this:

CREATE (n) WITH n
CALL apoc.create.addLabels(n, [$parameterizedLabel]) YIELD node
RETURN node

4. Derive labels from node data

Match persons, then label them using their first name.

MATCH (n:Person) WITH n, split(n.name, " ")[0] as firstName
CALL apoc.create.addLabels(n, [firstName]) YIELD node
RETURN node
0 REPLIES 0