Constraining a relationship type or node labels?

I have attempted to search for whether the following is supported in any version of Neo4j:

  1. Constraining the type of b in (a)-[b]-(c), i.e. creating a new relationship with a disallowed type would fail the transaction. This basically would enable modeling according to a "schema".

  2. Alternatively performing the same by constraining the labels of nodes a and c for a specific relationship type

I have imagined something like this:

CREATE CONSTRAINT foobar ON (:FOO)-[b]->(:BAR) ASSERT TYPE(b) = "FOOBAR";

CREATE CONSTRAINT foobar ON (:FOO)-[b]->(:BAR) ASSERT TYPE(b) IN ["FOOBAR","BARFOO"];

From the official documentation i have only found asserts for existence and uniqueness.

That is correct. You can assert that a property must exist if you create a relationship, but not that the relationship must exist if you create (:FOO) and (:BAR) .
Think of Neo4j as schema optional and set yourself free!

You can add schema-based constraints expressed using the SHACL language(1) with the neosemantics plugin from Neo4j labs. (Validating Neo4j graphs against SHACL - Neosemantics)

It's WIP but even in its current form will let you do most of what you describe in your example.

I show it in action in this live session .

Check it out and let us know what you think.

(1) Shapes Constraint Language (SHACL)

1 Like

Hi @jesus_barrasa - I knew I could add constraints expressed in SHACL based on types (e.g. int or string), but I learned something new today!
Thank you!

@david_rosenblum This is unfortunately not an answer - there are many examples of situations where creating content adhering to a schema is beneficial with graphs - building ontologies for example. I would absolutely prefer a model where Neo is by default schema-free but it does allow constraining in a multitude of ways when it is beneficial for the users' use case (and there are plenty of very diverse use cases for graphs).

What @jesus_barrasa described is fascinating (I wasn't aware of this kind of support) and it is definitely something I will immediately go and test out! Thank you for the hint.