如何在neo4j中将复杂的密码查询更改为简单查询?

时间:2012-12-09 22:36:07

标签: neo4j cypher

我想找到拥有最多朋友数和最少朋友数的用户。 这是我的疑问:

"start n=node:users({query}) match p=n-[?:Friend*]->x 
with distinct n,count(distinct x) as  cnt  "
+ "start n=node:users({query}) match p=n-[?:Friend*]->x 
with distinct n,count(distinct x) as cnt1, min(cnt) as minnumber "
+ "start n=node:users({query}) match p=n-[?:Friend*]->x
with distinct n,count(distinct x) as friendsNumber, max(cnt1) as 
maxnumber, minnumber  "
+ "where  friendsNumber=minnumber or friendsNumber=maxnumber  return n.name,
friendsNumber"

n是用户,x是他的朋友。 但我使用了三个嵌套查询,我认为它的表现并不好。还有另外一种方法吗? 感谢。

2 个答案:

答案 0 :(得分:0)

也许查询两次会更好

START n=node:users({query})
MATCH n-[:Friend]->x
WITH n,count(x) as cnt
RETURN n, cnt order by cnt desc limit 1;

START n=node:users({query})
MATCH n-[:Friend]->x
WITH n,count(x) as cnt
RETURN n, cnt order by cnt asc limit 1;

答案 1 :(得分:0)

您不希望在此处使用可变长度路径。也没有可选择的关系因为你对有朋友的人感兴趣。

我认为在这里运行两个查询可能是最明智的:

start n=node:users({query}) 
match p=n-[:Friend]->x
with ID(n),count(distinct x) as  cnt
with max(cnt) as max,min(cnt) as min

start n=node:users({query}) 
match p=n-[:Friend]->x
with n,count(distinct x) as  cnt
where cnt=max or cnt=min
return n.name

这样的事情也应该有效:http://console.neo4j.org/r/xf3hm0

start n=node(*) 
match p=n-[:KNOWS]-x 
with n,count(distinct x) as  cnt 
with collect([n,cnt]) as data, max(cnt) as max,min(cnt) as min 
return extract(pair in 
   filter(pair in data 
     where tail(pair)=max OR tail(pair)=min) : 
   head(pair)) as person