In Cypher, how can I create a relationship if it doesn't exist; update property if it does

旧巷老猫 提交于 2019-12-03 08:39:49

问题


In Cypher in Neo4J, given two nodes, if there's no relationship between them, I'd like to create a relationship (of type Foo) with a weight property of one. If this relationship already exists, I'd like to increment its weight property.

Is there a good way to do this in a single Cypher query? Thanks!

Edit: Some additional details: The nodes are already created, unique, and in an index.


回答1:


This is exactly why we added CREATE UNIQUE in 1.8.

START a=node(...), b=node(...)
CREATE UNIQUE a-[r:CONNECTED_TO]-b
SET r.weight = coalesce(r.weight?, 0) + 1

Read more about CREATE UNIQUE here, the question mark here, and coalesce here.




回答2:


To complete Andres answer, question mark at the end of a property is now an error with Neo4j 2. So request will be :

MATCH a, b
WHERE a(...) AND b(...)
CREATE UNIQUE a-[r:CONNECTED_TO]->b
SET r.weight = coalesce(r.weight, 0) + 1



回答3:


For future reference, CREATE UNIQUE has since been deprecated (see here). It looks like you can do something similar with MATCH and MERGE:

                MATCH (a:Person {name: 'Wonder Woman'})
                MERGE (b:Person {name: 'Aries'})
                MERGE (a)-[r:FOUGHT]->(b)
                ON CREATE SET r.weight = 1
                ON MATCH SET r.weight = r.weight + 1

So here, Wonder Woman fought Aries at least once, else it will increment the weight.



来源:https://stackoverflow.com/questions/11354401/in-cypher-how-can-i-create-a-relationship-if-it-doesnt-exist-update-property

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