graphneo4jpathnodeslongest-path

get longest path between two nodes with common nodes


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?

enter image description here


Solution

  • 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