Search code examples
pythonneo4jcypherneo4j-driver

(Neo4j-driver) - How to do batch insert relationship with Python


I'm trying to do batch create relationships between nodes in the neo4j database. I was trying with this code but it doesn't work!

relations = [{'from': 'man', 'to': 'woman', 'properties': {'cost': 0}},
{'from': 'woman', 'to': 'baby', 'properties': {'cost': 0}]

query = """
    UNWIND {{relations}} as row
    MATCH (from:SINGLE_NODE {{row.from}})
    MATCH (to:SINGLE_NODE {{row.to}})
    CREATE/MERGE (from)-[rel:IS_CONNECTED]->(to)
    (ON CREATE) SET rel += row.properties
    """.format(relations=relations)

session.run(query, relations=relations)

So anyhow can I do to add relation by using batch?


Solution

  • There are several syntax issues with your query.

    In the following line there no mention of the node property you're trying to match with the parameters row.from and row.to.

    MATCH (from:SINGLE_NODE {{row.from}})
    MATCH (to:SINGLE_NODE {{row.to}})
    

    From their values, I guess these should be gender property and the query should be similar to:

    MATCH (from:SINGLE_NODE {{gender:row.from}})
    MATCH (to:SINGLE_NODE {{gender:row.to}})
    

    In the following statements, it should be either CREATE OR MERGE, and on the second line, no braces around ON CREATE. Use ON CREATE only if you are using MERGE on first-line otherwise just use SET.

    CREATE/MERGE (from)-[rel:IS_CONNECTED]->(to)
    (ON CREATE) SET rel += row.properties
    

    So it should be one of these:

    CREATE (from)-[rel:IS_CONNECTED]->(to)
    SET rel += row.properties
    

    OR

    MERGE (from)-[rel:IS_CONNECTED]->(to)
    ON CREATE SET rel += row.properties