Skip to content

Instantly share code, notes, and snippets.

@frytoli
Last active February 4, 2021 16:01
Show Gist options
  • Save frytoli/e68a93bd100cb2b2608f638f77500c40 to your computer and use it in GitHub Desktop.
Save frytoli/e68a93bd100cb2b2608f638f77500c40 to your computer and use it in GitHub Desktop.

Example Using Cypher with Neo4j

https://neo4j.com/docs/getting-started/current/cypher-intro/

  1. Create nodes and relationships for example graph (Note that Neo4j does not support bidirectional relationships. Therefore, it's Arlo's world and we're all living in it.):
CREATE (olivia:Person { name:"Olivia", age:26 })
CREATE (arlo:Dog { name:"Arlo", age:4 } )
CREATE (carly:Person {name:"Carly", age:27 } )
CREATE (leroy:Dog { name:"Leroy", age:3 })
CREATE (madeline:Person { name:"Madeline", age:24 })
CREATE (razz:Dog { name:"Razzamatazz", age:2 } )

CREATE (olivia)-[:IS_OWNER { adopted: [2016]}]->(arlo)
CREATE (carly)-[:IS_OWNER { adopted: [2018]}]->(leroy)
CREATE (madeline)-[:IS_OWNER { adopted: [2018]}]->(razz)
CREATE (arlo)-[:IS_FRIENDS]->(leroy)
CREATE (arlo)-[:IS_FAMILY]->(razz)
  1. Create a constraint to ensure all dog names will be unique from this point forward (Note that this will create an index on the Dog property "name" as long as the constraint exists):
CREATE CONSTRAINT ON (dog:Dog) ASSERT dog.name IS UNIQUE

2.5. If the constraint is removed, so will the index. If desired, explicity create on index on Dog "name":

CREATE INDEX FOR (dog:Dog) ON (dog.name)
  1. Let's add two more nodes (one Person, one Dog) and associated relationship nodes, for fun (Note the flexibility of the data models):
MATCH (d:Dog { name:"Arlo" })
CREATE (d)-[:IS_FRIENDS]->(d2:Dog { name:"Rue", birthplace:"Florida" })
CREATE (p:Person {name: "Jean", age:27})-[:IS_OWNER { adopted:[2015]}]->(d2)
  1. Let's find the names and birthplace (if applicable) of all Dogs that Arlo is friends with:
MATCH (d:Dog { name:"Arlo"})-[:IS_FRIENDS]->(d2:Dog)
RETURN d2.name, d2.birthplace

Output:

+-----------------------------------+
| d2.name         | d2.birthplace   |
+-----------------------------------+
| "Rue"           | "Florida"       |
+-----------------------------------+
| "Leroy"         | null            |
+-----------------------------------+

2 rows
  1. How about all of the People who own the Dogs that Arlo is friends with, whose age is > 25:
MATCH (d:Dog {name: "Arlo"})-[:IS_FRIENDS]->(d2)
MATCH (p:Person)-[:IS_OWNER]->(d2)
WHERE p.age > 25
RETURN p

Output: Return of nodes for Carly and Jean

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment