SeanKilleen
SeanKilleen

Reputation: 8977

Can I create a neo4j constraint for uniqueness within a certain originating relationship?

I intend to have multiple organizations existing within my database.

Within a given organization, I'd like to enforce a uniqueness constraint on a node.

For example:

I'm aware that I can add a uniqueness constraint on the name property of the thing label, but it seems that this would be a global constraint across all labels. Which would be fine if my tenant strategy was multi-database, but as of now it is not.

I'm looking to do something like the following (which isn't currently possible):

CREATE CONSTRAINT thing_name_unique_to_org FOR (o:Organization)-[r]->(t:Thing) REQUIRE t.name IS UNIQUE

Is there a way to create this constraint at the Neo4j level, or should I plan to enforce this in code?

Upvotes: 1

Views: 226

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

You can't do it like this:

CREATE CONSTRAINT thing_name_unique_to_org FOR (o:Organization)-[r]->(t:Thing) REQUIRE t.name IS UNIQUE

But you can try a workaround like this, using Node Key Constraints, provided you are using Neo4j Enterprise Edition.

You can store the Organization unique identifier, in the Thing node, let's say orgId. Then you can create a constraint like this:

CREATE CONSTRAINT unique_org_thing_name ON (n:Thing) ASSERT (n.orgId, n.name) IS NODE KEY

This will ensure that orgId and name combination is unique.

Upvotes: 3

Related Questions