Home > front end >  neo4j Cypher iteratively creating relationships in optimal way
neo4j Cypher iteratively creating relationships in optimal way

Time:10-25

I am making a social media app where users can invite lists of other users to "events." To write a Cypher query to invite each user on a list to an event--i.e. to create an INVITED relationship between each user and an event node, what is the best approach?

Should I iteratively create relationships with a single Cypher transaction? I'm not sure what that would look like. Alternatively, I could loop through each user in my Node.js backend and write a transaction creating a single INVITED relationship for each user on the list. My guess is that the latter approach is not optimal, as I would need to MATCH the same event for each transaction.

CodePudding user response:

You can use lists in cypher and combined with UNWIND, you can achieve this with a single statement,

WITH ["user1","user2", "user3"] as users 
UNWIND users as user
MATCH (u:User {id: user})
MATCH (e:Event {id: 'event1'}) 
CREATE (u)-[:INVITED]->(e) 

CodePudding user response:

I am guessing that you have access the something that identifies the users on your Node.js backend already when starting the query, such as as an id property. If so then the query becomes

MATCH (user:User) WHERE user.id IN $user_ids
MATCH (event:Event) WHERE event.id = $event_id
CREATE (user)-[:INVITED_TO]->(event)

This query will hit the db once for fetching the event and once for each member of the user ID's.

You can then pass the parameters user_ids and event_id when executing the query from Node.js.

  • Related