Reputation:
I am currently new to neo4j and exploring with cypher queries for a task at hand. I am using neo4j bolt driver in Java Here is what I am trying to achieve. I have something like below data available as a Java ArrayList(stored in a HashMap):
employerId 2 : [employeeId 1, employeeId 2, employeeId3, ...]
Which basically shows relationship between employer and employee (these are the employees of employer 2)
Now, I need to find these employees & employer in the graph(they may or may not exist already) and create a "(x:Employer) -[Employs]->(y:Employee)" relationship between them.
One way (maybe, naive) that I can think of, is to search for employer and employee every time and run a separate CREATE query for each.
match (employer:Employer{name:"John"}), (name:Employee{name:"Snow"}) CREATE (employer)-[pr:EMPLOYES]->(employee)
But I feel that it would unnecessary search for the same Employer node multiple times. And as time is an important criterion for me right now, I am looking for a better way(if exists)
As a newbie to neo4j, all I can think of is, to do a search for the employer ID once, and then run multiple queries using that result, with Employee ID being searched every time. But I am unable to find the correct query to do this. Moreover, will this be the right approach? I need to prepare this query from Java. So should I query multiple times or send a single query?
Upvotes: 0
Views: 945
Reputation: 66999
This query below looks similar to the one from @Lju. However, it has a few improvements.
MERGE
for the Employer
only needs to be done once, so it should come before the UNWIND
. Otherwise, it would be done for every Employee
.$employerName
and $names
.WITH
clause between the 2 MERGE
clauses was just passing all identifiers forward, it is not needed. (However, Cypher syntax does require a WITH
clause between a MERGE
and an UNWIND
).Query:
MERGE (employer:Employer {name: $employerName})
WITH employer
UNWIND $names AS name
MERGE (employee:Employee {name: name})
MERGE (employer)-[:Employs]->(employee)
RETURN *
Upvotes: 1