How can I limit to only one relationship between two nodes in Neo4j?

♀尐吖头ヾ 提交于 2020-05-24 00:35:46

问题


I have the following graph:

Currently I am using this QUERY to add a relationship between two nodes:

MATCH (a:Service),(b:Service)
WHERE a.service_id = 'cs2322' and b.service_id = 'ab3232'
CREATE (a)-[r:DEPENDENT_ON]->(b)
RETURN type(r)

However I dont want to have more than one relationship between any two nodes, because I want to visualise my services and the dependency between them, so I cannot have a service being two times dependent on the other.

Is there any way I can limit this to force neo4j server to throw an error if I try to create a relationship between two nodes which already have a relationship per direction with one-another?


回答1:


There is no built-in way to throw an error if you create a duplicate relationship. But that would also be a pretty expensive way to enforce such a policy.

Instead, you can use MERGE instead of CREATE to avoid creating duplicate relationships.

For example, this query will only create the DEPENDENT_ON relationship if it does not already exist; otherwise, it will just bind the existing relationship to r:

    MATCH (a:Service), (b:Service)
    WHERE a.service_id = 'cs2322' AND b.service_id = 'ab3232'
    MERGE (a)-[r:DEPENDENT_ON]->(b)
    RETURN TYPE(r)


来源:https://stackoverflow.com/questions/61625904/how-can-i-limit-to-only-one-relationship-between-two-nodes-in-neo4j

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