简体   繁体   中英

Neo4j/Cypher - Get random node from matched result

I need to seed a Neo4j database. Let's say after adding Person nodes, I need them to write Book s. 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. How can I do this?

Using APOC Procedures you can use a function to choose a random item from a list. 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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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