How to calculate mutual friends with neo4j?

橙三吉。 提交于 2020-01-01 03:44:14

问题


I want to use neo4j to manage relationship among users.

How can I get mutual friends using it?


回答1:


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 );



回答2:


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

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


来源:https://stackoverflow.com/questions/6325294/how-to-calculate-mutual-friends-with-neo4j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!