简体   繁体   English

neo4j Cypher 以最佳方式迭代创建关系

[英]neo4j Cypher iteratively creating relationships in optimal way

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--ie to create an INVITED relationship between each user and an event node, what is the best approach?要编写一个 Cypher 查询来邀请列表中的每个用户参加一个事件——即在每个用户和一个事件节点之间创建一个INVITED关系,最好的方法是什么?

Should I iteratively create relationships with a single Cypher transaction?我应该迭代地创建与单个 Cypher 事务的关系吗? 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.或者,我可以遍历 Node.js 后端中的每个用户并编写一个事务,为列表中的每个用户创建一个INVITED关系。 My guess is that the latter approach is not optimal, as I would need to MATCH the same event for each transaction.我的猜测是后一种方法不是最佳的,因为我需要为每个事务MATCH相同的事件。

You can use lists in cypher and combined with UNWIND , you can achieve this with a single statement,您可以在UNWIND使用列表并与UNWIND结合使用,您可以使用单个语句来实现这一点,

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

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.我猜您在开始查询时已经访问了在 Node.js 后端识别用户的东西,例如id属性。 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.此查询将命中数据库一次以获取事件,并为用户 ID 的每个成员命中一次。

You can then pass the parameters user_ids and event_id when executing the query from Node.js.然后,您可以在从 Node.js 执行查询时传递参数user_idsevent_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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