Add constraints to neo4j node based on node property value

五迷三道 提交于 2020-06-23 16:31:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!