Mike
Mike

Reputation: 643

In Neo4j, can I enforce a relationship+node value constraint?

this is from a Neo4j noob. The question is about identity rules, I suppose.

Imagine I have the following data structure:

ARTIST MADE many ALBUMs

I can enforce artist uniqueness in the following manner:

CREATE CONSTRAINT ON (artist:Artist) ASSERT artist.name IS UNIQUE

which means the name is the business identity of an artist.

But I also want to ensure that each album exists only once - an album identity, however, is (album name + artist name), since two different artists can have their own albums named the same. Is there an elegant way of achieving that with Neo4j?

So, for artist Metallica, I want to ensure that there is only one album called Death Magnetic, and that between the single Metallica node and the single Death Magnetic node only one relationship exists, while another artist called, say, Megadeth, can have their own album called Death Magnetic (different node).

This ensures only the uniqueness of the relationship, I still need to create the album node upfront:

MATCH (artist:Artist { name:'Metallica' }),(album:Album { name:'Death Magnetic' })
MERGE (artist)-[r:MADE]->(album)
RETURN r

Upvotes: 2

Views: 622

Answers (2)

Michael Hunger
Michael Hunger

Reputation: 41676

Currenty uniqueness constraints are the only ones.

You are asking for composite constraints and indexes those are on the roadmap, as workaround you can create a concatenated or array value and uniquely constrain that.

There are also other constraints on the roadmap like property, property-type, relationships and their cardinalities.

Upvotes: 2

FrobberOfBits
FrobberOfBits

Reputation: 18002

No, neo4j doesn't support this kind of schema constraint. You can assert uniqueness on the album title (which you wouldn't want to do, since more than one band can produce an album of the same title), or you can live without the constraint.

More broadly, it would be nice if neo4j's graph schema had relationship cardinality features, but they're not there yet, you'd have to ask the devs if/when they're going to be built in. But it might be tricky; for example, your cardinality constraint here refers to a foreign node's property (Album title). Enforcing this could get sticky; let's say you had a Metallica album named "Death Magnetic" linked to Metallica. You had another album "Ride the Lightning" linked to Metallica. Someone comes in and changes the album title of "Ride the Lightning" to "Death Magnetic". OK so now you have two nodes, both of which are already linked to Metallica, but the constraint is violated. What do you do? Do you refuse to permit the album title edit? Do you delete the "Ride the Lightning" album node? Or do you permit the edit, but sever the link to the "Metallica" node?

Due to questions like these, it's not always so obvious how this feature would work if it were there. Graph schemas can be quite tricky.

Upvotes: 4

Related Questions