Graph Neo4j-查询每组N个项目

Graph Neo4j-查询每组N个项目,graph,neo4j,cypher,greatest-n-per-group,graph-databases,Graph,Neo4j,Cypher,Greatest N Per Group,Graph Databases,以下是我的疑问: MATCH (u:User{id:1})-[r:FOLLOWS]->(p:Publisher)<-[:PUBLISHED]-(i:Item)-[:TAGGED]->(t:Tag)<-[f:FOLLOWS]-u RETURN a, count(t) ORDER BY count(k) DESC LIMIT 100 MATCH(u:User{id:1})-[r:FOLLOWS]->(p:Publisher)(t:Tag)p。这些属性指定用户希望从每个发布服

以下是我的疑问:

MATCH (u:User{id:1})-[r:FOLLOWS]->(p:Publisher)<-[:PUBLISHED]-(i:Item)-[:TAGGED]->(t:Tag)<-[f:FOLLOWS]-u
RETURN a, count(t) ORDER BY count(k) DESC LIMIT 100

MATCH(u:User{id:1})-[r:FOLLOWS]->(p:Publisher)(t:Tag)p
。这些属性指定用户希望从每个发布服务器查看的项目数。如何重写查询以允许此操作?

这里有一个想法。例如,假设
遵循
关系设置了最小值和最大值。您可以使用以下查询根据这些值限制查询返回的数据。我也没有重写整个查询以包含标记和限制

// find the user and the publisher and the relationship 
// which has the min/max parameters
match (u:User {id: 1})-[r:FOLLOWS]->(p:Publisher)
with u, p, r

// macth the items that the publisher published
match p-[:PUBLISHED]-(i:Item)

// order them just because we can
with u, p, r, i
order by i.name

// collect the ordered items as the total list of items
with u, p, r, collect(i.name) as items

// make sure the collection is >= the minimum size of the list
// if so then return the items in the collection up to the max length 
// otherwise return and empty collection
// you might want to do something else
with u, p, r, case 
  when length(items) >= r.min then items[..r.max]
  else []
end as items
return u.name, p.name, r.min, r.max, items
不幸的是,您已经执行了查询以获取项目,只是为了显示目的而将其过滤掉。最好事先知道此人的偏好,这样您就可以在查询中使用limit和参数为项目应用max limit。这将消除不必要的数据库点击。根据出版商的不同,可能会有很多很多项目,提前限制这些项目可能是有利的

这里也有一些变体可供试验。你也可以这样做

// slight variation where the minimum is enforced with where instead of case
match (u:User {id: 1})-[r:FOLLOWS]->(p:Publisher)
with u, p, r
match p-[:PUBLISHED]-(i:Item)
with u, p, r, i
order by i.name
with u, p, r, collect(i.name) as items
where length(items) >= r.min
return u.name, p.name, items[..r.max]
甚至这个

// only results actually between the min and max are returned
match (u:User {id: 1})-[r:FOLLOWS]->(p:Publisher)
with u, p, r
match p-[:PUBLISHED]-(i:Item)
with u, p, r, i
order by i.name
with u, p, r, collect(i.name) as items
where length(items) >= r.min
and length(items) <= r.max
return u.name, p.name, items[..r.max]
//只返回实际介于最小值和最大值之间的结果
匹配(u:User{id:1})-[r:FOLLOWS]->(p:Publisher)
用u,p,r
匹配p-[:已发布]-(i:项)
有u,p,r,i
按姓名订购
以u、p、r、collect(i.name)作为项目
其中长度(项目)>=r.min
和长度(项目)