Skip to content

Instantly share code, notes, and snippets.

@heronrs
Forked from jexp/neo4j-social-network.adoc
Created October 16, 2018 02:41
Show Gist options
  • Save heronrs/6190eca98d98e4168b3bad538d8e2b18 to your computer and use it in GitHub Desktop.
Save heronrs/6190eca98d98e4168b3bad538d8e2b18 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
@heronrs
Copy link
Author

heronrs commented Oct 18, 2018

MLM sample:

CREATE (p:Person {name:"Level 1"})
WITH p
FOREACH (name in ["Level 2","Level 2","Level 2","Level 2"] |
CREATE (p)-[:DOWNLINE]->(:Person {name:name}))


MATCH (p:Person {name:"Level 2"})
FOREACH (name in ["Level 3","Level 3","Level 3","Level 3"] |
CREATE (p)-[:DOWNLINE]->(:Person {name:name}))


MATCH (p:Person {name:"Level 3"})
FOREACH (name in ["Level 4","Level 4","Level 4","Level 4"] |
CREATE (p)-[:DOWNLINE]->(:Person {name:name}))

MATCH (p:Person {name:"Level 4"})
FOREACH (name in ["Level 5","Level 5","Level 5","Level 5"] |
CREATE (p)-[:DOWNLINE]->(:Person {name:name}))

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