Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

tree - Neo4j Create node if no relationship exists

From the MERGE documentation

MATCH (person:Person)
MERGE (city:City { name: person.bornIn })
MERGE (person)-[r:BORN_IN]->(city)
RETURN person.name, person.bornIn, city

The problem is, I want to create a Relationship and a Node, if the RELATIONSHIP does not exist, but in my graph all the nodes are identical so the second step would not create a new Node.

Since my graph is a tree I know that if the relationship i'm looking for does not exist, the node also does not exist.

Giving the nodes unique identifiers is not helpful as it would just be the path from the root node to the one i want to create. If I replace MERGE with CREATE it will create redundant nodes that are not connected to the tree. Since you cant use MERGE with WHERE, is there a way to do the equivalent of:

MERGE (nextpos:Position) WHERE NOT (nextpos)--()

Which would create a node if there are no nodes without connections, allowing me in the next step to create the needed relationship. Or should I just remove all the redundant nodes afterwards? That would seem very hacky and I am hoping for an elegant solution.

question from:https://stackoverflow.com/questions/65906624/neo4j-create-node-if-no-relationship-exists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I strongly recommend changing your DB schema. If all the nodes are having identical properties, I don't know how are you planning to perform MATCH later on. All nodes might be identical to user but neo4j has a <id> field, which is unique to each entity (node and relationship).

Anyways coming to the problem, As far as I understand you need to check if a particular node is already connected to another particular node. Since you didn't give the entities properties I assume some properties here.

DB elements

(:Position {position: prev_move})-[:Move {move: next_move}]->(:Position {position: next_move})

Cypher Query

MATCH (n: Position {position: prev_move})
OPTIONAL MATCH (n)-[rel:Move {move: next_move}]->(:Position {position: next_move))
CALL apoc.do.when(rel is NULL, 
  "CREATE (next: Position {position : next_move}) CREATE (n)-[:Move {move: next_move}]->(next) RETURN next", 
  "", {n:n})
YEILD value
RETURN n

EDIT

You might need a different MATCHing condition to get the exact node you are looking for. MATCH (n: Position {position: prev_move}) will yield in multiple nodes. Please fell free to update the matching condition, rest remains same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...