Neo4j - Search list with mutual count

2019-03-04 19:32发布

I have created some nodes and relations in neo4j and want to query with cypher. I am explaining more about it as below.

UserID  UserName 
------  --------
1       UserA
2       UserB
3       UserC
4       UserD
5       UserE
6       UserF

and relationship between nodes are as follows :

UserID  FriendID  ApprovalStatus (1.Request Accepted, 2.Request Pending)
------  --------  ------------------------------------------------------
1       2         1 
1       3         2 
1       6         2 
2       3         1 
2       4         1 
2       5         2 
3       6         1
3       5         2

My Login User is node 1 (eg. UserA), and trying to search from node. and I am expecting this result from neo4j.

Record #  UserID  UserName  MutualCount       ApprovalStatus 
--------  ------  --------  ---------------   --------------  
1         2       UserB      1 (eg. node 3)   1               
2         3       Userc      0                2  
3         4       UserD      0                null
4         5       UserE      0                null
5         6       UserF      0                2 

check the following points : Record # 1 : Node3 (UserC) is mutual between Node1 & Node2 with because it has ApprovalStatus=1 with both nodes.

Record # 2 :
There is no mutual between node1 & node3, and ApprovalStatus = 2 because Node1 has sent request to node3, but it is pending yet.

Record # 3 :
Same situation as mentioned in Record # 2

Record # 4 & 5:
here is no mutual between node1 & node4, and ApprovalStatus = null because Node1 has never sent request to node4 & node5.

I have created some dummy data on here

So, you can test query. I am trying to get this result from last 10-15 days, but I can not get success. Is there any way to achieve this result.

Thanks.

标签: neo4j cypher
1条回答
The star\"
2楼-- · 2019-03-04 20:24

The relationship table in your question doesn't have any mutual relationships, which is what it looks like you are looking for, so I created a very similar example that adds an additional relationship from B to A.

I added statuses "accepted" and "requested" to the :FRIEND relationships, but as @Stefan mentions in the comments, it would be easier to use different relationship types such as :REQUESTED_FRIEND and :FRIEND to distinguish between the two. In that case you could drop the WHERE clause from the following query:

START n=node(*) 
MATCH n-[r:FRIEND]->m, m-[r2:FRIEND]->n 
WHERE r.status='accepted' AND r2.status='accepted' 
RETURN n, COUNT(m) AS MutualCount, COLLECT(m.name)

which returns:

n                   MutualCount     MutualWith
(5 {name:"B"})      1               [A]
(6 {name:"A"})      1               [B]
查看更多
登录 后发表回答