Ram
Ram

Reputation: 97

Neo4j - Returning multiple sets of rows for each node

I am having 1000 employee nodes and they belong to 7 divisions.I am trying to get the top 10 messages sent by each employee in finance division to other employees in descending order. I also want the division of employee to whom he has sent the message. I am using the following query according to the answers given in these two questions: return top n results for each query in Neo4j and Getting top n records for each group in neo4j, but the result I am getting is top 10 messages sent by each employee to other employees of each division (a total of 70 messages for each employee). I want the results including all divisions collectively and not 10 results for each division.

The query I used is:

MATCH(e:Employee{div:'finance'}),(b:Employee)
OPTIONAL MATCH (e)-[r:Message]->(b)
WITH e.name as em, b.division_name as bm,coalesce(r.NUMBER_OF_MESSAGES,0) 
as msg 
ORDER BY msg DESC 
WITH collect(msg) AS bts, em, bm
UNWIND bts[0..10] AS r
RETURN em, bm, r

What changes should I make to this query? Thanks in advance

Upvotes: 1

Views: 644

Answers (1)

Bruno Peres
Bruno Peres

Reputation: 16365

Ram, I believe a good choice to do it is using the APOC Procedure apoc.cypher.run. With this procedure you will able to run a "sub query" for each employee that works in the finance division. Please, install APOC Procedures and try it:

MATCH(e:Employee{div:'finance'})
CALL apoc.cypher.run('
    WITH {e} AS e
    OPTIONAL MATCH (e)-[r:ACTED_IN]->(b:Employee)
    RETURN e.name, b.division_name, coalesce(r.NUMBER_OF_MESSAGES,0) as messages
    ORDER BY messages DESC
    LIMIT 10',
{e:e}) YIELD value
return value

Note: Remember to install APOC procedures according the version of Neo4j. See this link.

Upvotes: 4

Related Questions