In Cypher, how can I create a relationship if it doesn't exist; update property if it does
This is exactly why we added CREATE UNIQUE
in 1.8.
START a=node(...), b=node(...)
CREATE UNIQUE a-[r:CONNECTED_TO]-b
SET r.weight = coalesce(r.weight?, 0) + 1
Read more about CREATE UNIQUE
here, the question mark here, and coalesce here.
To complete Andres answer, question mark at the end of a property is now an error with Neo4j 2. So request will be :
MATCH a, b
WHERE a(...) AND b(...)
CREATE UNIQUE a-[r:CONNECTED_TO]->b
SET r.weight = coalesce(r.weight, 0) + 1
For future reference, CREATE UNIQUE has since been deprecated (see here). It looks like you can do something similar with MATCH and MERGE:
MATCH (a:Person {name: 'Wonder Woman'})
MERGE (b:Person {name: 'Aries'})
MERGE (a)-[r:FOUGHT]->(b)
ON CREATE SET r.weight = 1
ON MATCH SET r.weight = r.weight + 1
So here, Wonder Woman fought Aries at least once, else it will increment the weight.