How can I perform a "match or create" operation in py2neo v3?
<p>I want to create a Node/Relationship only if a Node/Relationship with the same attribute<strong>s</strong> doesn't already exist in the graph. If they do, I would like to fetch the relevant item.</p>

<p>Right now I am doing something that I suppose is both unidiomatic and inefficient. Assuming each <code>Person</code> node has a unique pair (<code>name</code>, <code>age</code>), I do something like this:</p>

<pre><code>try:
    node = graph.data('MATCH (n:Person) WHERE n.name = {name} AND'
                      'n.age = {age} RETURN n LIMIT 1',
                      name=my_name, age=my_age)[0]['n']
except IndexError:
    node = Node('Person', name=my_name, age=my_age)
</code></pre>

<p>To my understanding <a href="http://py2neo.org/v3/database.html#py2neo.database.Graph.find_one" rel="nofollow"><code>find_one()</code></a> works only if you have just one property to search for, and <a href="http://py2neo.org/v3/database.html#py2neo.database.Graph.match_one" rel="nofollow"><code>match_one()</code></a> allows no properties for relationships.</p>

<p>You can use the Cypher <a href="http://neo4j.com/docs/developer-manual/current/cypher/#query-merge" rel="nofollow">MERGE</a> clause to perform a "match or create":</p>

<pre><code>node = graph.data('MERGE (n:Person) WHERE n.name = {name} AND'
                  'n.age = {age} RETURN n LIMIT 1',
                  name=my_name, age=my_age)[0]['n']
</code></pre>

<p>py2neo does have <a href="http://py2neo.org/2.0/essentials.html#py2neo.Graph.merge" rel="nofollow">merge</a> and <a href="http://py2neo.org/2.0/essentials.html#py2neo.Graph.merge_one" rel="nofollow">merge_one</a> functions, but they only take a single property, so using Cypher would be the more general approach.</p>

python database neo4j py2neo