Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4J unique constraint for multiple labels

Tags:

neo4j

cypher

I have a set of nodes with multiple Labels (A, B, C). All nodes have a common property, which is unique across all labels. However, when creating unique constraint it is limited to one label, isn't it?

Documentation says something like:

CREATE CONSTRAINT ON (n:A) ASSERT n.uid IS UNIQUE

But I'd like to do something like

CREATE CONSTRAINT ON (n:A AND n:B AND n:C) ASSERT n.uid IS UNIQUE

or

CREATE CONSTRAINT ON (n) ASSERT n.uid IS UNIQUE

If that is not possible, would it be best, to create a label D, and add it to all nodes with label A, B, and C and then create the constraint for label D?

like image 297
naraesk Avatar asked Aug 25 '16 21:08

naraesk


People also ask

Can a node have multiple labels Neo4j?

If you look closely, the labels column is in the form of an array, which means that a single node can have multiple labels. Also, with cypher projection, we can provide a virtual label, as shown in the query.

When using Neo4j why would you use constraints?

The constraint ensures that your database will never contain more than one node with a specific label and one property value.

What are constraints in Neo4j?

Unique property constraints ensure that property values are unique for all nodes with a specific label. For unique property constraints on multiple properties, the combination of the property values is unique.


1 Answers

Your suggestion is exactly what I used in a similar case. I created a label meant to encompass two other labels, and added the constraint on the new one (in addition to the others).

The only trick is remembering to apply that label in addition to any new nodes you create with the sublabels.

It wouldn't be a bad idea to make a neo4j feature request for constraints that apply across multiple labels, that would be rather useful.

like image 145
InverseFalcon Avatar answered Oct 21 '22 15:10

InverseFalcon