问题
I am adding constraints to a neo4j database using Cypher constraints and want to create a constraint which only applies to a subset of a node type.
I can create a constraint that a foo
field must exist on Entity
with
CREATE CONSTRAINT ON (e:Entity) ASSERT EXISTS (e.foo)
but instead, I want to constrain only nodes with a given field. e.g
CREATE CONSTRAINT ON (e:Entity {constrain_flag:true) ASSERT EXISTS (e.foo)
For example, I may have two nodes like
(e:Entity { foo: 'bar' , constrain_flag: true })
and
(e:Entity { constrain_flag: false })
I only want the constraint that e.foo
must exist to apply to the Entity
where constrain_flag = true
, so both of these should be allowed. However,
(e:Entity { constrain_flag: false })
should throw an exception.
Is there a way to do this currently with cypher and neo4j?
Thanks in advance!
回答1:
Instead of adding a flag property, you can just add an additional label (say, ConstrainedEntity
) to Entity
nodes that should be constrained. Queries can continue to use just the Entity
label.
For example:
CREATE CONSTRAINT ON (ce:ConstrainedEntity) ASSERT EXISTS (ce.foo)
To create a "flagged" Entity
:
CREATE (e:Entity:ConstrainedEntity {id: 111, foo: 'bar'})
To "flag" an existing Entity
:
MATCH (e:Entity)
WHERE e.id = 123
SET e:ConstrainedEntity
来源:https://stackoverflow.com/questions/62088558/add-constraints-to-neo4j-node-based-on-node-property-value