I'm currently iterating over an array where each index contains two nodes and a relationship (Part_1 -> Part_2), and I'm using the Neo4jTemplate.save() method to persist it into the database. However, some indexes have repeated nodes that will have relationships with other nodes (Part_2 -> Part_3). My version currently creates a new node and relationship every time instead of merging if a node already exists.
I read this post, but I don't understand how to implement it so that two of the same nodes will have the same ID. My current code works like this:
- Create two nodes
- Create their relationship
- Add relashionship to the node
- Persist it using Neo4jTemplate.save()
What do I need to change to MERGE instead of CREATE? Do I need to do a check before I persist or is there a way to check while persisting in SDN 4?
EDIT:
I've decided to use the Neo4jTemplate.query() method to write Cyper queries, however I don't know how to create the parameters correctly for merging multiple nodes. I can create a MERGE statement correctly like this for one node:
Map<String, Object> params = new HashMap<String, Object>();
Map<String, Object> node = new HashMap<String, Object>();node.put("name", "Part_1");
params.put("props", node_1);
String query = "MERGE( n1:Part {name:{props}.name} )";template.query(query, params);
My goal is to call merge on two nodes and then call merge again to create the relationship in one statement. My code right now looks like this:
Map<String, Object> params = new HashMap<String, Object>();
List<Map<String, Object>> maps;
Map<String, Object> node1 = new HashMap<String, Object>();
Map<String, Object> node2 = new HashMap<String, Object>();node1.put("name1", "Part_1");
node2.put("name2", "Part_2");
maps = Arrays.asList(node_1, node_2)params.put("props", maps);
String query = "MERGE( n1:Part {name:{props}.name1} )
MERGE( n2:Part {name:{props}.name2 )
MERGE(n1)-[:CREATED]->(n2)";template.query(query, params);
All the examples I've seen so far with multiple nodes in the parameters simply just iterate through the whole thing when called. I haven't found any examples that have parameters where you can specify the certain node in it that you're referring to. How do I create a parameter where I refer to a certain node? Thanks in advance!