Introduction to Neo4j
Introduction to Neo4j
Let’s create our first basic graph! we’ll create something similar to what you saw in the video (or similar to what you see in this image).
Of course, if you are not a Barcelona supporter you can change it to be whatever you want.
CREATE (m:Player{name:"Lionel Messi"}), (b:Team{name:"Barcelona"})
WITH m, b
CREATE (m)-[p:PlaysFor]->(b)
SET p.since=2001
//SET p.since=date("2001-02-01") // For some reason the GraphGists don't support dates
RETURN m, p, b
A network of friends
But the previous one was a rather simple example, how about we create a network of friends to see what else we can do…
// Create nodes
CREATE (rob:Person{name:'Roberto'}), (isidro:Person{name:'Isidro'}),
(tony:Person{name:'Antonio'}), (nora:Person{name:'Nora'}),
(lily:Person{name:'Lilian'}), (freddy:Person{name:'Alfredo'}),
(lucas:Person{name:'Lucas'}), (mau:Person{name:'Mauricio'}),
(alb:Person{name:'Albina'}), (reg:Person{name:'Regina'}),
(j:Person{name:'Joaquín'}), (julian:Person{name:'Julián'})
// Create relationships
CREATE
(rob)-[:FriendsWith]->(isidro), (rob)-[:FriendsWith]->(tony), (rob)-[:FriendsWith]->(reg),
(rob)-[:FriendsWith]->(mau), (rob)-[:FriendsWith]->(julian),
(tony)-[:FriendsWith]->(reg), (tony)-[:FriendsWith]->(j),
(alb)-[:FriendsWith]->(reg), (lily)-[:FriendsWith]->(isidro), (lily)-[:FriendsWith]->(j),
(mau)-[:FriendsWith]->(lucas), (lucas)-[:FriendsWith]->(nora), (freddy)-[:FriendsWith]->(nora);
// Query the relationships
MATCH friendships=()-[:FriendsWith]-()
RETURN friendships
🤔
Let’s find who are friends with Lucas (note that we don’t care about the direction of the relationship, we are not using an arrow →
in the relationship):
MATCH friends=(a:Person{name:'Lucas'})-[:FriendsWith]-(friend)
RETURN friends
What about the friends of friends of friends of Lucas? imagine doing someting like this in SQL…
MATCH friends=(a:Person{name:'Lucas'})-[:FriendsWith*3]-(friend)
RETURN friend.name
Or something more advanced, which one is the shortest path between Joaquín and Lucas:
MATCH (lucas:Person{name:'Lucas'}), (joaquin:Person{name:'Joaquín'}),
p = shortestPath((lucas)-[*]-(joaquin))
RETURN p
Is this page helpful?