Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 674
user1099123 Avatar asked Oct 17 '25 21:10

user1099123


2 Answers

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.

like image 143
Finbar Good Avatar answered Oct 19 '25 12:10

Finbar Good


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

like image 34
GrandMel Avatar answered Oct 19 '25 12:10

GrandMel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!