Collecting the result of cypher query into a hash

2019-09-07 17:43发布

问题:

This is a followup of Finding connected nodes question.

The code is

    firstNode = graphDb.createNode();//creating nodes
    firstNode.setProperty( "person", "Andy " ); 
    Label myLabel = DynamicLabel.label("person");
    firstNode.addLabel(myLabel); ...

    relationship = firstNode.createRelationshipTo( secondNode, RelTypes.emails );// creating relationships
    relationship.setProperty( "relationship", "email " );....


    ExecutionEngine engine = new ExecutionEngine(graphDb);
        ExecutionResult result = engine.execute("MATCH (sender:person)-[:emails]- (receiver)RETURN sender,  count(receiver)as count, collect(receiver) as receivers ORDER BY count DESC ");
        System.out.println(result.dumpToString());

The result I got was:

 sender                  | count | receivers                                                                 
Node[2]{person:"Chris"} | 3     | [Node[4]{person:"Elsa "},Node[0]{person:"Andy "},Node[1]{person:"Bobby"}] 
Node[4]{person:"Elsa "} | 3     | [Node[5]{person:"Frank"},Node[2]{person:"Chris"},Node[3]{person:"David"}]
Node[1]{person:"Bobby"} | 3     | [Node[2]{person:"Chris"},Node[3]{person:"David"},Node[0]{person:"Andy "}]
Node[5]{person:"Frank"} | 2     | [Node[3]{person:"David"},Node[4]{person:"Elsa "}

How to collect the sender as key and receivers as values? For ex : {Frank =[David, Elsa], Chris =[Elsa, Andy, Nobby]..

Any idea?

Initially I tried iterating something like this

        for (Map<String,Object> row : result) {
               Node x = (Node)row.get("receivers");
               System.out.println(x);

               for (String prop : x.getPropertyKeys()) {
                  System.out.println(prop +": "+x.getProperty(prop));

               }

This throws classcast exception. It works for column "sender" and not for "receivers".

I am very new to cypher. I don't know how to transform the result into a hash map. How is this possible ?

回答1:

You can rewrite the cypher to return a map instead... (split for readability)

MATCH (sender:person)-[:emails]->(receiver)
WITH sender, collect(receiver.person) as receivers
RETURN {sender: sender.person,  receivers: receivers)
ORDER BY size(receivers) DESC