I have a graph in which the connection of the friends and the cities where they live are shown. The connection of the friends is specified by means of black arrows and that of the cities is specified with dotted lines. I want to get the longest path of friends who live in a common city, between Mr. A and Mr. D. The answer would be the route: A-> B-> E-> D. What query should be written for it?
Asked
Active
Viewed 119 times
0
-
Does the direction of relationship matter in your case? Can it also be D -> E -> B -> A ? – Tomaž Bratanič Sep 27 '20 at 11:45
-
Yes, the direction matters – mohsen ahmadi Sep 28 '20 at 07:21
1 Answers
1
Native query (without using APOC add-on):
MATCH path = (city:City)<-[:LIVES_IN]-(:Person)-[:KNOWS*]->(:Person)-[:LIVES_IN]->(city)
WHERE ALL(person IN nodes(path)[2..-2] WHERE (person)-[:LIVES_IN]->(city))
RETURN nodes(path)[1..-1]
ORDER BY length(path) DESC
LIMIT 1
To search for the longest path of a specific city (e.g. P1), change the first line to:
MATCH path = (city:City {name: "P2"})<-[:LIVES_IN]-(:Person)-[:KNOWS*]->(:Person)-[:LIVES_IN]->(city)
APOC versions might be more performant, but, honestly, it would need to be measured. One of the possibilities:
MATCH (person:Person)-[:LIVES_IN]->(city:City)
WITH city, collect(person) AS persons
CALL apoc.path.expandConfig(persons, {
relationshipFilter: "KNOWS>",
whitelistNodes: persons,
minLevel: 1
})
YIELD path
RETURN nodes(path)
ORDER BY length(path) DESC
LIMIT 1

Mafor
- 9,668
- 2
- 21
- 36
-
I have 183678 cities and 5058 person . When I use your suggested query, it takes too long to answer the query. – mohsen ahmadi Sep 29 '20 at 07:08