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

111 Views Asked by At

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

2

There are 2 best solutions below

1
On BEST ANSWER

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.

1
On

If you have a this type of dataset:

CREATE (:Node {name: 'A'});
CREATE (:Node {name: 'B'});
CREATE (:Node {name: 'C'});
CREATE (:Node {name: 'D'});
CREATE (:Node {name: 'E'});
MATCH (a:Node {name: 'A'}), (b:Node {name: 'B'})
CREATE (a)-[:r1]->(b)
CREATE (a)-[:r2]->(b);
MATCH (a:Node {name: 'A'}), (c:Node {name: 'C'})
CREATE (a)-[:r3]->(c);
MATCH (d:Node {name: 'D'}), (e:Node {name: 'E'})
CREATE (d)-[:r4]->(e);
MATCH (b:Node {name: 'B'}), (d:Node {name: 'D'})
CREATE (b)-[:r5]->(d);
MATCH (c:Node {name: 'C'}), (e:Node {name: 'E'})
CREATE (c)-[:r6]->(e);

This should work in Memgraph:

MATCH (start:Node {name: 'A'})-[r]->(end:Node)
WITH start, end, collect(r) AS rels
ORDER BY size(rels) DESC
RETURN start.name AS StartNode, end.name AS EndNode, size(rels) AS RelationshipCount

As result I get A->B count:2, A->C count:1