M4rk
M4rk

Reputation: 2272

How to calculate mutual friends with neo4j?

I want to use neo4j to manage relationship among users.

How can I get mutual friends using it?

Upvotes: 2

Views: 2718

Answers (2)

Niko Gamulin
Niko Gamulin

Reputation: 66565

In case of using cypher the following query returns mutual friends:

start a = node(1), b = node(4) match (a)--(x)--(b) return x;

The example above returns mutual friends of node 1 and 4

enter image description here

Below is the copy of queries and its results for the example from the picture:

neo4j-sh (0)$ start a = node(1), b = node(4) match (a)--(x)--(b) return x;
==> +--------------------+
==> | x                  |
==> +--------------------+
==> | Node[3]{Name->"C"} |
==> +--------------------+
==> 1 row
==> 9 ms
==> 
neo4j-sh (0)$ start a = node(1), b = node(6) match (a)--(x)--(b) return x;
==> +--------------------+
==> | x                  |
==> +--------------------+
==> | Node[5]{Name->"E"} |
==> | Node[2]{Name->"B"} |
==> +--------------------+
==> 2 rows
==> 0 ms

Upvotes: 4

Michael Hunger
Michael Hunger

Reputation: 41676

The easiest way would be to use the shortest path algorithm of length 2, with the two users, across FRIEND_OF relationships. Those are the paths that connect the two users via exactly one friend hop.

PathFinder<Path> finder = GraphAlgoFactory.shortestPath(
        Traversal.expanderForTypes( FRIEND_OF ), 2 );
Iterable<Path> paths = finder.findAllPaths( user1, user2 );

Upvotes: 4

Related Questions