Search code examples
neo4jcypherpy2neo

Use parameters to create or merge relationships


I often add large amounts relationships between existing nodes and I'm wondering if parameters could increase performance. So far I do this by building individual Cypher strings and submitting them in Cypher transactions (using py2neo 1.6.4).

The queries look like:

MATCH (a:Label1 {name: 'value'}), (b:Label2 {name: 'value'})
MERGE (a)-[r:RELATES {name: 'foo', value: 'bar'}]->(b)
RETURN r

Would parameters increase performance? How can I use parameters with this query?

I tried using FOREACH around the whole query and pass parameters, but MATCH is not allowed inside FOREACH. I don't see if/how I can parameterize both the MATCH and the CREATE/MERGE.

An alternative would be to use MERGE only, but this will create new nodes if a part of the query doesn't match.


Update

I think the answer is that I can't parameterize the complete query. But as the Wes Freeman suggests performance increases if I use parameters for the MERGE, even if the query contains only one set of parameters for one relationship.


Solution

  • You can pass in an array and do something like this:

    MATCH (a:Label1 {name: {name1}}), (b:Label2 {name: {name2}})
    FOREACH (rel in {rels}|
      MERGE (a)-[r:RELATES { name: rel.name, value: rel.value }]->(b)
    )
    

    Of course, it's hard to pull out the r values afterward.

    Params:

    {
     "name1":"value",
     "name2":"value",
     "rels":[{"name":"foo","value":"bar"}, ...]
    }