[英]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.