如何计算项目然后同时返回第一项和计数?

时间:2017-06-28 22:26:01

标签: neo4j cypher

我有一个Item节点,可以被User节点LIKE,我想要实现的是:

  • 列出用户喜欢的所有唯一Item节点,按LIKE
  • 的时间排序
  • 对于上面列出的每个项目节点,还列出最近最喜欢该项目节点的用户节点

这是我正在尝试使用的查询:

MATCH (i:Item)<-[like:LIKES]-(u:User) 
WITH i, like, u, COUNT(u) as u_count
ORDER BY like.created DESC LIMIT 1
RETURN i, like.created, u, u_count;

但是,此查询仅列出第一个Item节点。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

在您的查询中,您计算​​每个已创建属性的每个项目的用户数。我的期望是,除非每个项目有多个同时喜欢,否则用户数将始终为1。然后,您将该聚合结果限制为单行。

我认为这是一种方法,可以满足您的目标。

// match the users and likes
MATCH (i:Item)<-[like:LIKES]-(u:User) 

// order the item likes by most recent timestamp
WITH i, like.created AS created, u
ORDER BY created DESC

// collect the ordered likes and users per item
WITH i, collect(created) AS liked, collect(u.name) AS users

// return the item, the time is was last liked, the user that last liked and the total number of likes
RETURN i.name, liked[0], users[0], size(liked) AS likes

// order by the most recent like
ORDER BY liked[0] DESC