Write a Cypher query to CREATE links between random nodes

此生再无相见时 提交于 2019-12-12 11:50:16

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/32621407/write-a-cypher-query-to-create-links-between-random-nodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!