Search code examples
neo4jcypher

How to get Node properties as a map from Neo4j driver


I'm struggling to get data in the way I need it from the native driver (jdbcTemplate did this for me out of the box).

My code:

List<Record> result = session.run(cql,params).list();
return result.stream()
    .map(record -> record.asMap())
    .collect(Collectors.toList());

This returns a List<Map<String, Object>> which is kind of what I need except the Object here is of type InternalNode.

What I really want is for this Object itself to be a Map<String, Object> where the keys and values are the node properties. I just can't figure out the interfaces and various asMap method etc.


Solution

  • Without your Cypher query, this is a little bit hard to grasp. I assume based on your result, that you have something like:

    MATCH (n:Node) return n;
    

    The resulting record will be indeed ("n", InternalNode). This means that calling the asMap() on the record just serialises the result into a map without conversion of the containing values. What you could do, depending on your return pattern, is to explicitly ask for the node first and then call the asMap() function.

    var cql = "MATCH (n:Node) return n";
    List<Record> result = session.run(cql).list();
    var resultListMap = result.stream()
                        .map(record -> record.get("n").asMap())
                        .collect(Collectors.toList());
    

    This would then result in a list of maps containing the "flat" properties.

    Another way of doing this without the extraction of the node first is

    var resultListMap = result.stream()
                        .map(record -> record.asMap(value -> value.asMap()))
        // or short     .map(record -> record.asMap(MapAccessor::asMap))
                        .collect(Collectors.toList());
    

    where for every value in the map the asMap() gets called.