Nicole Marie
Nicole Marie

Reputation: 131

Picking random pairs in Neo4j

I have a bunch of "a"s. Each "a" have some number of "b"s with" r" relationship. I need to pick 5 random "r"s. However, no 2 "r" can use the same "a".

I have tried picking 5 "a"

MATCH (a:solution)
WITH a, rand() AS number
RETURN a 
ORDER BY number
LIMIT 5

But I do not know how to get only one "r" from each of the "a"s

Also tried picking 5 "r"

MATCH ()-[r]->()
WITH r, rand() AS number
RETURN ()-[r]->()
ORDER BY number
LIMIT 5

However, I can not figure out how to make it so more than one "r" coming of an "a"

I need (a,b) output.

This is what the data looks like

enter image description here

Upvotes: 2

Views: 241

Answers (2)

InverseFalcon
InverseFalcon

Reputation: 30397

You're close, we can use those a's from your first query and match to b's through r's. However we can't use LIMIT on those b's, since LIMIT affects all rows in your query, and you really just want to limit the r's for each a. We can instead collect() the r's for each a into a list, and take the head of the list as r.

MATCH (a:solution)
WITH a, rand() AS number
WITH a 
ORDER BY number
LIMIT 5
MATCH (a)-->(b)
RETURN a, HEAD(COLLECT(b)) as b

If you have any restrictions on the relationship type or the label on b, feel free to add those into the match.

EDIT

Edited to work with b nodes instead of the relationship between a and b (it's important to be clear in your requirements, your queries were only working with a and r previously).

Keep in mind the selection of a is random, but for every a, the selection of b is not random. A modified version of cybersam's query should do the trick for you if you need b's selection to be random too.

Upvotes: 1

cybersam
cybersam

Reputation: 66967

This solution is similar to the one from @InverseFalcon, but it will also truly randomly pick a r result for each of 5 randomly picked a nodes.

MATCH (a:solution)
WITH a, rand() AS number
ORDER BY number
LIMIT 5
MATCH (a)-[r]->()
WITH a, COLLECT(r) AS rs
RETURN a, rs[TOINT(SIZE(rs)*rand())] AS r;

Upvotes: 1

Related Questions