简体   繁体   中英

neo4j cypher count relations between same type of nodes

I am too new in graph databases and I have a problem in getting data from model like this.

在此处输入图片说明

I am trying to count common likes between User1 and all other users in same group as user1. Here is the result I am trying to get for User1 :

User , Count, Drinks
User3,     2, [ Cola, Beer ]
User2,     1, [ Cola ]
User5,     1, [ Tea ]
User4,     0, [ ]
User6,     0, [ ]

It seems easy task to do but not for me.

I can get the users and counts with users having relations with but not with users without relations. Please can anyone help me with this? Thanks in advance!

The solution I propose has the following logic :

  • Find the user 1
  • Find other users that are not user 1
  • Find an OPTIONAL MATCH for a path between user1, a drink and the current iteration of the other user

This is based on the following test graph :

http://console.neo4j.org/r/xc3cqt

The query :

MATCH (u:User { id:1 })
MATCH (o:User)
WHERE o <> u
OPTIONAL MATCH (u)-[r:LIKES]->(d)<-[:LIKES]-(o)
RETURN o.id, count(r) as c, collect(DISTINCT (d.name)) AS drink

Result for your provided graph :

o.id    c           drink
2       1           [Cola]
5       1           [Tea]
4       0           []
3       2           [Beer, Cola]
6       0           []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM