0

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

  • A word of warning to anyone borrowing this code - creating a session for every node sync (which were frequent) is a *very bad idea* (as was not closing the session I suspect). Re-using a single session for multiple node syncs made the code run many many times faster, and stopped a bunch of very strange memory errors on my server. – user3654762 Aug 31 '17 at 15:16

1 Answers1

0

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);
}
cybersam
  • 63,203
  • 6
  • 53
  • 76