Getting top n records for each group in neo4j

后端 未结 3 916
心在旅途
心在旅途 2021-02-15 03:15

I need to group the data from a neo4j database and then to filter out everything except the top n records of every group.

Example:

I have two node

3条回答
  •  误落风尘
    2021-02-15 03:45

    Try

    MATCH (o:Order)-[r:ADDED]->(a:Article)
    WITH o, r, a
    ORDER BY o.oid, r.t
    WITH o, COLLECT(a)[..2] AS topArticlesByOrder UNWIND topArticlesByOrder AS a
    RETURN a.aid AS articleId, COUNT(*) AS count
    

    Results look like

    articleId    count
       8           6
       2           2
       4           5
       7           2
       3           3
       6           5
       0           7
    

    on this sample graph created with

    FOREACH(opar IN RANGE(1,15) |
        MERGE (o:Order {oid:opar})
        FOREACH(apar IN RANGE(1,5) |
            MERGE (a:Article {aid:TOINT(RAND()*10)})
            CREATE o-[:ADDED {t:timestamp() - TOINT(RAND()*1000)}]->a
        )
    )
    

提交回复
热议问题