Search code examples
neo4jcyphermemgraphdb

How do I get the unique paths in a graph in memgraph/cypher?


Suppose I had two nodes: A and B. Now suppose I had two relations that are similar:

A -r1-> B
A -r2-> B

How do I make a query that returns just a path from A -> B? The following query returns two paths that are identical. Can we merge the results?

MATCH path = (start:Fen)-[r*]->(end:Fen)
WHERE start.Name = 'A'
RETURN DISTINCT(path)

What I am trying to solve is to find the most popular paths between nodes. so given the graph:

A -r1-> B
A -r2-> B
A -r3-> C

the query should return

A -r-> B
A -r-> C

since A -> B is the most popular it appears first


Solution

  • You can return pairs of endpoints in the results, in descending order of the number of paths between them, like so:

    MATCH path = (start:Fen)-[*]->(end:Fen)
    WHERE start.Name = 'A'
    RETURN start, end, count(*) AS count
    ORDER BY count DESC
    

    As an aside, you depict your desired result in the form of A -r-> B. Assuming by -r-> you mean all the intermediate nodes and relationships in the path, then these would all be distinct and appear in separate rows.