Skip to content

Instantly share code, notes, and snippets.

@jexp
Last active October 6, 2022 15:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jexp/cdaca7e32d8fca630016 to your computer and use it in GitHub Desktop.
Save jexp/cdaca7e32d8fca630016 to your computer and use it in GitHub Desktop.
Neo4j Example Social Network

Social Network

A simple social network of people knowing each other.

Data Setup with LOAD CSV

LOAD CSV FROM "https://gist.githubusercontent.com/jexp/cdaca7e32d8fca630016/raw/people.csv" as row
MERGE (p1:Person {name: row[0]})
MERGE (p2:Person {name: row[1]})
MERGE (p1)-[:KNOWS]-(p2);

Friend of Friends query

MATCH (person:Person)-[:KNOWS]-(friend)-[:KNOWS]-(foaf)
WHERE person.name = "Joe"
  AND NOT (person)-[:KNOWS]-(foaf)
RETURN DISTINCT foaf

Friends of Friends

Find all of Joe’s second-degree friends.

MATCH (user:Person)-[:KNOWS]-(friend)-[:KNOWS]-(foaf)
WHERE user.name = "Joe" AND NOT(user)-[:KNOWS]-(foaf)
RETURN foaf

Common Friends

Find all friends that Joe has in common with Sally.

MATCH (user:Person)-[:KNOWS]-(friend)-[:KNOWS]-(foaf:Person)
WHERE user.name = "Joe" AND foaf.name = "Sally"
RETURN friend

Connecting Paths

Find all friends on the shortest path that connects Joe to Billy.

MATCH path = shortestPath((p1:Person)-[:KNOWS*..6]-(p2:Person))
WHERE p1.name = "Joe" AND p2.name = "Billy"
RETURN path
Jim Mike
Jim Billy
Anna Jim
Anna Mike
Sally Anna
Joe Sally
Joe Bob
Bob Sally
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment