Book Image

Learning Cypher

By : Onofrio Panzarino
Book Image

Learning Cypher

By: Onofrio Panzarino

Overview of this book

Table of Contents (13 chapters)

Modifying existing data

The last query in the previous section creates a relationship between two nodes. If we run that query twice, we will have two relations between those nodes. In most cases, this redundancy is unnecessary and useless for us. Suppose our social network was online and had a button called "Add Friend". In this scenario, if two users, say A and B, click on this button at the same time to add each other as friends, the relation would be doubled in the database. This is a waste of storage. In this context, we need to check the database and create the relation only if it does not exist. This is why an OPTIONAL MATCH clause is required to prevent double storage. This is illustrated in the following query:

MATCH (a:User {name: "Jack", surname: "Roe"}), 
      (b:User {name: "Jack", surname: "Smith"})
OPTIONAL MATCH (a) -[r:Knows]- (b)
WITH a,r,b
CREATE (a) -[rn:Knows]-> (b)
RETURN a,rn,b

This query, first of all, finds the users Jack Roe and Jack Smith in the...