Search code examples
neo4jcypherlimit

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?


Solution

  • 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