Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Cypher

You're reading from   Learning Cypher Write powerful and efficient queries for Neo4j with Cypher, its official query language

Arrow left icon
Product type Paperback
Published in May 2014
Publisher
ISBN-13 9781783287758
Length 162 pages
Edition Edition
Arrow right icon
Author (1):
Arrow left icon
Onofrio Panzarino Onofrio Panzarino
Author Profile Icon Onofrio Panzarino
Onofrio Panzarino
Arrow right icon
View More author details
Toc

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
WHERE r IS NULL
CREATE (a) -[rn:Knows]-> (b)
RETURN a,rn,b

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

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime