Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create unique constraint involving multiple properties in Neo4J

Tags:

neo4j

cypher

I know I can create a unique constraint on a single property with Cypher like CREATE CONSTRAINT ON (p:Person) ASSERT p.name IS UNIQUE. But I was wondering whether it is possible to create a unique constraint which involves multiple properties. If so, how?

like image 814
victorx Avatar asked Mar 19 '14 06:03

victorx


People also ask

Can relationships have properties in Neo4j?

The Neo4j Graph Data Science Library provides multiple operations to work with relationships and their properties stored in a projected graphs. Relationship properties are either added during the graph projection or when using the mutate mode of our graph algorithms.

How do you create a relationship between two nodes in Neo4j?

To create a relationship between two nodes, we first get the two nodes. Once the nodes are loaded, we simply create a relationship between them. The created relationship is returned by 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.


2 Answers

neo4j (2.0.1) does not currently support a uniqueness constraint that covers multiple properties simultaneously.

However, I can think of a workaround that might be acceptable, depending on your use cases. Let's say you want properties a, b, and c to be unique as a group. You can add an extra property, d, that concatenates the stringified values of a, b, and c, using appropriate delimiter(s) to separate the substrings (such that, for example, the a/b delimiter is a character that never appears in a or b). You can then create a uniqueness constraint on d.

[UPDATE]

Neo4j 3.3 added support for uniqueness constraints that cover multiple properties, via node key constraints. However, this feature is only available in the Enterprise Edition.

like image 194
cybersam Avatar answered Sep 23 '22 06:09

cybersam


As of neo4j version 3.3 there is a constraint called NODE KEY which can be used for uniqueness across multiple properties.

From the documentation:

To create a Node Key ensuring that all nodes with a particular label have a set of defined properties whose combined value is unique, and where all properties in the set are present

Example Query

CREATE CONSTRAINT ON (n:Person) ASSERT (n.firstname, n.surname) IS NODE KEY 
like image 26
pgericson Avatar answered Sep 22 '22 06:09

pgericson