Reputation: 1039
I'm trying to determine the "distance" between nodes in a graph. Using the example movie database, I would like to return actor nodes with the distance away from Kevin Bacon. Using the image below for effectively what I'm looking for.
How do I build this into my cypher query? This seems possible, I just can't think of a way to do it as my cypher-foo isn't very advanced yet :(
MATCH p=(bacon:Person {name:"Kevin Bacon"})-[*1..5]-(hollywood)
WHERE hollywood.name in (['Helen Hunt', 'Ed Harris'])
RETURN p
FYI - My neo4j database is v4.0
Upvotes: 0
Views: 1333
Reputation: 67044
This query:
MATCH p=(bacon:Person {name:"Kevin Bacon"})-[*1..5]-(hollywood)
WHERE hollywood.name IN ['Helen Hunt', 'Ed Harris']
UNWIND
REDUCE(s = [], i IN RANGE(0, LENGTH(p)) |
s + {dist: i, node: NODES(p)[i]}
) AS data
RETURN data.dist AS distance, COLLECT(DISTINCT data.node) AS nodes
returns this result:
╒══════════╤═════════════════════════════════════════════════════════════════════╕
│"distance"│"nodes" │
╞══════════╪═════════════════════════════════════════════════════════════════════╡
│0 │[{"name":"Kevin Bacon","born":1958}] │
├──────────┼─────────────────────────────────────────────────────────────────────┤
│1 │[{"title":"Apollo 13","tagline":"Houston, we have a problem.","releas│
│ │ed":1995},{"title":"A Few Good Men","tagline":"In the heart of the na│
│ │tion's capital, in a courthouse of the U.S. government, one man will │
│ │stop at nothing to keep his honor, and one will stop at nothing to fi│
│ │nd the truth.","released":1992},{"title":"Frost/Nixon","tagline":"400│
│ │ million people were waiting for the truth.","released":2008}] │
├──────────┼─────────────────────────────────────────────────────────────────────┤
│2 │[{"name":"Tom Hanks","born":1956},{"name":"Ed Harris","born":1950},{"│
│ │name":"Bill Paxton","born":1955},{"name":"Cuba Gooding Jr.","born":19│
│ │68},{"name":"Jack Nicholson","born":1937},{"name":"Ron Howard","born"│
│ │:1954}] │
├──────────┼─────────────────────────────────────────────────────────────────────┤
│3 │[{"title":"Cast Away","tagline":"At the edge of the world, his journe│
│ │y begins.","released":2000},{"title":"Twister","tagline":"Don't Breat│
│ │he. Don't Look Back.","released":1996},{"title":"As Good as It Gets",│
│ │"tagline":"A comedy from the heart that goes for the throat.","releas│
│ │ed":1997},{"title":"Apollo 13","tagline":"Houston, we have a problem.│
│ │","released":1995}] │
├──────────┼─────────────────────────────────────────────────────────────────────┤
│4 │[{"name":"Helen Hunt","born":1963},{"name":"Ed Harris","born":1950}] │
└──────────┴─────────────────────────────────────────────────────────────────────┘
Notice that the movie "Apollo 13" appears in the results at distances of 1 and 3. And that "Ed Harris" appears at distances of 2 and 4. This is because there are (undirected) paths of different lengths from "Kevin Bacon" to those two nodes.
Upvotes: 0