我需要播种Neo4j数据库。假设添加了Person
个节点后,我需要它们来编写Book
个。这是我到目前为止的内容:
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..." })
我当时想用???
中的一个随机人来填写p
,该人在第一行中是MATCH
。我该怎么办?
答案 0 :(得分:1)
使用APOC程序,您可以使用功能从列表中选择随机项目。这是用法示例:
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..." })
答案 1 :(得分:1)
如果您只想说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..."})
请注意,如果要重新运行此查询,我将使用MERGE
而不是CREATE
,以避免产生重复的关系和节点。