Kien Nguyen
Kien Nguyen

Reputation: 2701

Neo4j Cypher - How to limit 50% of MATCH results

I want to limit by 50% of results from MATCH but it looks like LIMIT doesn't accept dynamic value.

I tried:

MATCH (:Profile) 
WITH COUNT(*) AS c
MATCH (n:Profile)
WITH n ORDER BY rand() LIMIT toInt(c * 0.5) 
RETURN n

Then I got the error:

It is not allowed to refer to variables in LIMIT

So is there any way to do that without using 2 separate queries?

Upvotes: 0

Views: 552

Answers (2)

cybersam
cybersam

Reputation: 67019

If you have the apoc plugin installed, you can use the apoc.coll.randomItems function to get a random 50%:

MATCH (n:Profile)
WITH COLLECT(n) AS people
WITH apoc.coll.randomItems(people, SIZE(people)/2) as profile_lst
UNWIND profile_lst as prof
RETURN prof

Upvotes: 0

jose_bacoy
jose_bacoy

Reputation: 12704

This is how I see it.

  1. Get all profiles and create a randomized number with each row
  2. Collect all profiles into a list of profiles and sorted by randomized number (r)
  3. Calculate the 50% of the size of the profile list
  4. Unwind the list from start to cnt then return each node
MATCH (n:Profile) 
WITH n, rand() as r ORDER by r 
WITH collect(n) as profile_lst
WITH profile_lst, toInt(size(profile_lst)/2) as cnt
UNWIND profile_lst[0..cnt] as prof
RETURN prof

Upvotes: 2

Related Questions