Codementor Events

A slight change from the previous post's .cypher MATCH and CREATE

Published Jul 14, 2017
A slight change from the previous post's .cypher MATCH and CREATE

From the previous post, I wrote a series of Cypher commands that would match musicians with albums and create a relationship between them. Here's one such command:

MATCH (M:Musician {name:"Miles Davis"}), (M:Album {name:"In a Silent Way"}) 
MERGE (M)-[:PLAYED_ON {instrument:"Trumpet"}]->(A);

I learned that I could also do

MERGE (M:Musician {name: "Miles Davis"})
WITH M MATCH (A:Album {name: "In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument: "Trumpet"}]->(A);

The second form would create a :Musician node with the provided name if it didn't exist already, or return the existing node. In either case, it would MERGE the bound :Musician node with the :Album node. It felt faster than the first form, although I don't have any benchmarks. Maybe some time.

It might still be necessary to CREATE the :Album node first though. I tried it — on another album I hadn't created yet and cypher-shell gave me back 0 nodes, 0 relationships. I may try this again to double-check.

As you can tell, I'm still learning Cypher.

In any event, below is the rewritten cypher code to associate the musicians with the :Album In a Silent Way:

MERGE (M:Musician {name:"Miles Davis"})
WITH M MATCH (A:Album {name:"In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument:"Trumpet"}]->(A);

MERGE (M:Musician {name:"Wayne Shorter"})
WITH M MATCH (A:Album {name:"In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument:"Soprano Sax"}]->(A);

MERGE (M:Musician {name:"John McLaughlin"})
WITH M MATCH (A:Album {name:"In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument:"Electric Guitar"}]->(A);

MERGE (M:Musician {name:"Chick Corea"})
WITH M MATCH (A:Album {name:"In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument:"Electric Piano"}]->(A);

MERGE (M:Musician {name:"Herbie Hancock"})
WITH M MATCH (A:Album {name:"In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument:"Electric Piano"}]->(A);

MERGE (M:Musician {name:"Joe Zawinul"})
WITH M MATCH (A:Album {name:"In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument:"Organ"}]->(A);

MERGE (M:Musician {name:"Dave Holland"})
WITH M MATCH (A:Album {name:"In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument:"Double Bass"}]->(A);

MERGE (M:Musician {name:"Tony Williams"})
WITH M MATCH (A:Album {name:"In a Silent Way"})
MERGE (M)-[:PLAYED_ON {instrument:"Drums"}]->(A);

I can choose not to CREATE the :MUSICIAN nodes with the names above — the first MERGE will create those that don't exist.

Here's the resulting graph:
In a Silent Way.graph.png.png

I've also decided to create a separate .cypher for each of the next :Album nodes, although I'm keeping the ones already in my existing .cypher. Stay tuned.

Discover and read more posts from Daniel Escasa
get started
post commentsBe the first to share your opinion
Show more replies