0
votes

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.

2

2 Answers

1
votes

When you're using Cypher and you're already on neo4j 2.0.0-M05 you can use the MERGE command.

1
votes

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?