简体   繁体   中英

Write a Cypher query to CREATE links between random nodes

To seed a database, I would like to create a small set of Person nodes...

WITH ["Amy","Bob","Cal","Dan","Eve"]
AS names
FOREACH (r IN range(0, size(names)-1) |
  CREATE (:Person {name: names[r]})
)

... and I would like to create a random connection for each Person. Is it possible to do this in a single query?

I imagine that I would need to add each new Person to a collection, and work with a variable created from FLOOR(RAND() * size(names)), but the official documentation does not give many clues as to how to do this.

Good question!

A couple of things, first I often prefer UNWIND over FOREACH , particularly in a case like this:

WITH ["Amy","Bob","Cal","Dan","Eve"] AS names
UNWIND names AS name
CREATE (:Person {name: name})

As far as creating random relationships, Michael Hunger has a good blog post covering it:

http://jexp.de/blog/2014/03/quickly-create-a-100k-neo4j-graph-data-model-with-cypher-only/

In your case it would be something like:

MATCH (p1:Person), (p2:Person)
WITH p1, p2
WHERE rand() < 0.1
MERGE p1-[:LIKES]->p2

Just be careful with that as the first MATCH specifies a full cartesian product of all people with all other people which can grow quickly as your Person nodes grow. Michael puts a LIMIT on his WITH in the post

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