neo4jneo4j-java-api

Neo4J Driver Node Merge/Creation - is there a cleaner way to deal with properties


I am currently playing with Neo for creating a monitoring API (Currently using the 1.4.2 Java driver). Part of this involves creating my own MonitorNode/MonitorEdge graph (those are my own classes), then syncing those with my Neo instance. My MonitorNode has a String/Object map of properties that I would like to sync (plus a vertexId that I am using as my master lookup key, and a type). I can craft a MERGE/SET cypher command that does pretty much exactly what I need it to do, but since I already have a string/object map is there a cleaner way of saying "here are the properties I want to set" without having to specify a SET command for each and every property?

There are relatively few examples out there for updating data via the Java driver (that I have found - please feel free to link any resources), and I feel I may be missing something easy here.

private void syncNode(MonitorNode node) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("vertexId", node.getVertexId());
    StringBuilder builder = new StringBuilder();
    builder.append("MERGE(n:" + node.getType() + " {vertexId: {vertexId}})");
    if (node.getProperties() != null) {
        for (Entry<String, Object> e : node.getProperties().entrySet()) {
            builder.append(" SET n." + e.getKey() + " = {" + e.getKey() + "}");
            params.put(e.getKey(), e.getValue());
        }
    }
    Session session = driver.session();
    session.run(builder.toString(), params);
}

Thanks,

Dave


Solution

  • The SET n += map syntax updates the properties of the n node from the map.

    This should work:

    static final Map<String, Object> EMPTY_MAP = new HashMap<String, Object>();
    
    private void syncNode(MonitorNode node) {
        Map<String, Object> props = node.getProperties();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("vertexId", node.getVertexId());
        params.put("props", props == null ? EMPTY_MAP : props);
        StringBuilder builder = new StringBuilder();
        builder.append("MERGE(n:" + node.getType() + " {vertexId: $vertexId})");
        builder.append(" SET n += $props");
        Session session = driver.session();
        session.run(builder.toString(), params);
    }