2

I want to use neo4j to manage relationship among users.

How can I get mutual friends using it?

M4rk
  • 2,172
  • 5
  • 36
  • 70

2 Answers2

4

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
Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286
  • in case we dont know the `b` node at the start, we can use `START a=node(1) MATCH a--x--b WHERE a--b RETURN x` – ulkas Jul 24 '14 at 08:10
4

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 );
Michael Hunger
  • 41,339
  • 3
  • 57
  • 80