Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a relationship only if not exist in neo4j

Tags:

neo4j

I want to add a relationship between two nodes, but only if the relationship does not exist. For example:

The Relationship between node1 and node2 currently exists with these properties: time:41221323,link:www.google.com

I am trying to add a relationship with different properties for example:

time:5344241,link:www.google.com

In this case i want to keep the original properties on the relationship.

like image 842
Bakalash Avatar asked Apr 20 '16 13:04

Bakalash


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.

What is optional match in Neo4j?

An OPTIONAL MATCH matches patterns against your graph database, just like a MATCH does. The difference is that if no matches are found, OPTIONAL MATCH will use a null for missing parts of the pattern. OPTIONAL MATCH could be considered the Cypher equivalent of the outer join in SQL.

What must Relationships in Neo4j have?

Relationships always has a direction (one direction). Relationships must have a type (one type) to define (classify) what type of relationship they are. Nodes and relationships can have properties (key-value pairs), which further describe them.


1 Answers

You can use the below CQL query:

MATCH(a: startNodeLabel {attributes to match start node})
MATCH(m:endNodeLabel {attributes to match end node}) 
MERGE(a)-[:relationshipName]->(m)

The above merge statement creates relation between nodes a and m if there is no existing relationship between a and m.

like image 71
Vanaja Jayaraman Avatar answered Sep 20 '22 20:09

Vanaja Jayaraman