Search code examples
neo4jcypher

How to verify if a node exist and if not exist then a created during an import of .csv to neo4j


I am importing some .cvs files for my database in neo4j, but I have the data of people in three different files, so when I import the data of the person from another file that has more data, I get an error when trying to import people nodes, because I already have other nodes with those dni (constraint) in my database.

So I want to create the new node or, if it exists, retrieve its pointer to create relationships with other nodes that I keep creating while I import.

I have tried several things on the internet but I still can't find the solution

Here my code:

LOAD CSV WITH HEADERS FROM 'file:/D:/ACCOUNT.csv' AS line FIELDTERMINATOR ';'

MERGE (persona :Persona { dni: line.DNI, 
nombre: line.NOMBRE, 
sexo: line.SEXO, 
fechaNacimiento: line.FNACIMIENTO,
direccion: line.DIRECCION
})

I have tried with apoc and "with" but I still can't find the solution. when this code finds another node with a person label and ID equal to the one entered, it gives me an error


Solution

  • To get this working, you'll have to understand how MERGE works. The statement

    MERGE (persona :Persona { dni: line.DNI, nombre: line.NOMBRE, sexo: line.SEXO, 
           fechaNacimiento: line.FNACIMIENTO,direccion: line.DIRECCION
    })
    

    will create a new Persona node for every distinct combination of the above properties. So, for a node with the same dni, but with other values of other properties, this will fail. To fix this, you should try merging the nodes on the basis of their dni, and then set the properties like this:

    MERGE (persona :Persona { dni: line.DNI })
    ON CREATE
    SET  persona.nombre =  line.NOMBRE, 
         persona.sexo = line.SEXO, 
         persona.fechaNacimiento = line.FNACIMIENTO,
         persona.direccion = line.DIRECCION
    

    The above query will ignore setting properties if a matching node is found. To set some properties when a match is found, use ON MATCH, like this:

    MERGE (persona :Persona { dni: line.DNI })
    ON CREATE
    SET  persona.nombre =  line.NOMBRE, 
         persona.sexo = line.SEXO, 
         persona.fechaNacimiento = line.FNACIMIENTO,
         persona.direccion = line.DIRECCION
    ON MATCH
    // Matching logic here