0
votes

I've been trying to get a subgraph based on a node query. The query should ignore the relationship directions as long as all of the nodes in the subgraph are connected: ex: u1 -FRIEND-> u2 -FRIEND-> u3 u4 -FRIEND-> u5 -FRIEND-> u6

searching for u1 or u2 or u3, should return a set of: [u1,u2,u3]

I used the following Cypher query:

MATCH (a:User)-[:FRIEND_OF*0..]-(b)
WHERE a.userId = 'some_id'
WITH a, collect(DISTINCT b) AS sets
RETURN DISTINCT sets

The problem is that I'm getting all of the set's permutations like:

DATA: u1 -FRIEND-> u2 -FRIEND-> u3
RETURN: [u1,u2,u3],[u1,u3,u2],[u2,u1,u3]...

how can I distinct the different sets to return only one permutation?

I also would like to support a case a user can be in different subgraphs so the response should be couple of subgraphs.

thanks

1

1 Answers

1
votes

This query should work:

MATCH p=(a:User)-[:FRIEND_OF*0..]-(b)
WHERE a.userId = 'some_id'
WITH DISTINCT a, b
ORDER BY ID(b)
WITH a, COLLECT(b) AS sets
RETURN DISTINCT sets;

It gets distinct a/b pairs, orders the b nodes by native ID, puts the ordered nodes in collections, and finally returns distinct collections.

You may want to create an index for :User(userId) for better performance.