Though you can't do this as a constraint just yet you can use the following work-around to get similar behavior at the query level (instead of the constraint level) by using MERGE
in your queries. You used to be able to use CREATE UNIQUE
to do this, but that has since been deprecated, but the CREATE UNIQUE
docs here have a good introduction section that covers the details pretty well and shows you how to do alternatively in the non-deprecated MERGE
way.
So, you can use these docs to see how you can create unique nodes and relationships through queries using MERGE
. Also, since this uniqueness is decided at the query level instead of the constraint level you should be very cautious of accidentally creating duplicate data where it should be unique.
(I'll put the current relevant doc sections provided above for CREATE UNIQUE
with the MERGE
alternatives here in case they disappear.)
CREATE UNIQUE
is in the middle of MATCH
and CREATE
— it will match what it can, and create what is missing.
We show in the following example how to express using MERGE
the same level of uniqueness guaranteed by CREATE UNIQUE
for nodes and relationships.
Assume the original set of queries is given by:
MERGE (p:Person {name: 'Joe'})
RETURN p
MATCH (a:Person {name: 'Joe'})
CREATE UNIQUE (a)-[r:LIKES]->(b:Person {name: 'Jill'})-[r1:EATS]->(f:Food {name: 'Margarita Pizza'})
RETURN a
MATCH (a:Person {name: 'Joe'})
CREATE UNIQUE (a)-[r:LIKES]->(b:Person {name: 'Jill'})-[r1:EATS]->(f:Food {name: 'Banana'})
RETURN a
This will create two :Person
nodes, a :LIKES
relationship between them, and two :EATS
relationships from one of the :Person
nodes to two :Food
nodes. No node or relationship is duplicated.
The following set of queries — using MERGE
— will achieve the same result:
MERGE (p:Person {name: 'Joe'})
RETURN p
MATCH (a:Person {name: 'Joe'})
MERGE (b:Person {name: 'Jill'})
MERGE (a)-[r:LIKES]->(b)
MERGE (b)-[r1:EATS]->(f:Food {name: 'Margarita Pizza'})
RETURN a
MATCH (a:Person {name: 'Joe'})
MERGE (b:Person {name: 'Jill'})
MERGE (a)-[r:LIKES]->(b)
MERGE (b)-[r1:EATS]->(f:Food {name: 'Banana'})
RETURN a
We note that all these queries can also be combined into a single, larger query.
The CREATE UNIQUE
examples below use the following graph:
--- source: Cypher Manual v3.5: Section 3.18, Introduction