Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 502
Newtang Avatar asked Jul 06 '12 00:07

Newtang


People also ask

How do you create a relationship between existing nodes in Neo4j?

In Neo4j to create relationship between nodes you have to use the CREATE statement like we used to create nodes. lets create relation between two already created nodes.

Can relationships have properties in Neo4j?

The Neo4j Graph Data Science Library provides multiple operations to work with relationships and their properties stored in a projected graphs. Relationship properties are either added during the graph projection or when using the mutate mode of our graph algorithms.

Which clause is used to add new properties to an existing node or relationship?

SET clause is used to add new properties to an existing Node or Relationship.

WHAT IS WITH clause in Cypher?

The WITH clause allows query parts to be chained together, piping the results from one to be used as starting points or criteria in the next. It is important to note that WITH affects variables in scope.


1 Answers

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.

like image 147
Andres Avatar answered Oct 13 '22 20:10

Andres