简体   繁体   中英

In Neo4J create relationship between two nodes, but if one of nodes don't exists create it in the same call

I have two nodes in my Neo4J graph db, node User and node Video, and I want to create relationship between them.

Node User exists for sure, but node Video might not. If that's the case it should be created with given id, and after creation of node relationship between them is created also.

I know I can first check if Video node exists and if it don't exists I can create it first. But could creation of Video node (if it don't already exists) and relationship between User and Video node be done in single call?

Also, I must prevent that some concurrent request create the same Video node before first request finished job.

So please give me ideas how to achieve this request. I'm very new with graph database concept and with Neo4J.

当您使用Cypher并且您已经在neo4j 2.0.0-M05上时,您可以使用MERGE命令。

According to Stefan Ambruster hint I researched MERGE statement in Cypher and create single statement call with which I achieved my goal to create video node if not exists and after that create relationship between my user node and video node.

Cypher:

MERGE (user:User {uuid : {user_uuid}})
ON CREATE user
SET user.uuid = {user_uuid}

MERGE (video:Video {id : {video_id}})
ON CREATE video
SET video.id = {video_id}

CREATE UNIQUE user-[:SHARED {ts : timestamp()}]->video

This seams good for my need. I also preserve that my User node is created if it don't exists, not just Video node.

Is there any possible improvements or pitfalls of this aproach/statement?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM