In Cypher, how can I create a relationship if it doesn't exist; update property if it does

Newtang picture Newtang · Jul 6, 2012 · Viewed 10.7k times · Source

In Cypher in Neo4J, given two nodes, if there's no relationship between them, I'd like to create a relationship (of type Foo) with a weight property of one. If this relationship already exists, I'd like to increment its weight property.

Is there a good way to do this in a single Cypher query? Thanks!

Edit: Some additional details: The nodes are already created, unique, and in an index.

Answer

Andres picture Andres · Jul 6, 2012

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.