Sachin Vairagi
Sachin Vairagi

Reputation: 5334

Neo4j CSV import - create or update

I have following query to create person node -

USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "http://192.168.11.121/movie-reco-db/person_node.csv" as row
CREATE (:Person {personId: row.person_id, name: row.name});

I set index on personId , person_node.csv is the file I exported from MySql database , this query is working fine but the problem is that the CSV file will have new records on each time I export , If I run this query again then it is creating duplicate nodes , If I set UNIQUE index on personId then it is says -

Node 0 already exists with label Person and property "personId"=[1]

And does not insert new records. So is there any elegant way to update record if already exists or create new one if not.

Upvotes: 0

Views: 805

Answers (1)

InverseFalcon
InverseFalcon

Reputation: 30397

You're looking for the MERGE operation, which will attempt a match, and if it doesn't find the thing, it will create it. Be aware that if the entirety of the thing you are merging does not exist (for example, merging a node with a personId and a name, but an existing node has that personId but a slightly different name) it will create the node.

If you have a unique ID for the node, merge on that, then use ON CREATE to add the remaining properties (ON CREATE only gets executed when MERGE causes a create instead of matching on existing entities in your db, there is another command ON MATCH that only gets executed when it matches instead of creates).

Your final query will look like:

USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "http://192.168.11.121/movie-reco-db/person_node.csv" as row
MERGE (p:Person {personId: row.person_id})
ON CREATE SET p.name = row.name;

Upvotes: 2

Related Questions