简体   繁体   English

Neo4j / Cypher-从匹配结果中获取随机节点

[英]Neo4j/Cypher - Get random node from matched result

I need to seed a Neo4j database. 我需要播种Neo4j数据库。 Let's say after adding Person nodes, I need them to write Book s. 假设添加了Person节点后,我需要它们编写Book Here's what I have so far: 这是我到目前为止的内容:

MATCH (p:Person)
WITH ["Book 1", "Book 2", "Book 3", "Book 4", "Book 5"] AS titles
UNWIND titles AS title
CREATE (???)-[:CREATED]->(:Content { title: title, content: "Words..." })

I was thinking I could fill in the ??? 我以为我可以填写??? with a random person from p , which was MATCH ed on the first line. 与来自p的随机人MATCH ,这是第一行的MATCH How can I do this? 我怎样才能做到这一点?

Using APOC Procedures you can use a function to choose a random item from a list. 使用APOC程序,您可以使用函数从列表中选择随机项。 Here's an example of usage: 这是用法示例:

MATCH (p:Person)
WITH collect(p) as people
UNWIND ["Book 1", "Book 2", "Book 3", "Book 4", "Book 5"] AS title
WITH apoc.coll.randomItem(people) as person, title
CREATE (person)-[:CREATED]->(:Content { title: title, content: "Words..." })

If you just want, say, 5 different Person nodes and you don't care if they are randomly distributed or that repeated runs may very well get the same nodes, you can use this efficient query (since it does not require getting all Person nodes): 如果您只想说5个不同的Person节点,而不必关心它们是否是随机分布的,或者重复运行很可能获得相同的节点,则可以使用此高效查询(因为它不需要获取所有Person节点):

MATCH (p:Person)
WITH p LIMIT 5
WITH COLLECT(p) AS ps, ["Book 1", "Book 2", "Book 3", "Book 4", "Book 5"] AS titles
UNWIND [i IN RANGE(0, SIZE(ps)-1) | {p: ps[i], title: titles[i]}] AS data
WITH data.p AS p, data.title AS title
MERGE (p)-[:CREATED]->(:Content {title: title, content: "Words..."})

Note that I used MERGE instead of CREATE , to avoid producing duplicate relationships and nodes should you want to re-run this query. 请注意,如果要重新运行此查询,我将使用MERGE而不是CREATE来避免产生重复的关系和节点。

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

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