简体   繁体   中英

neo4j : LIMIT and ORDER BY in COLLECT

Consider this cypher query

MATCH (a : User)-[c : Commented]->(b) RETURN DISTINCT a.username AS
username, b.postId AS postId, COLLECT({commentBody : c.comments,
commentedOn : c.time})[0..5] AS commentData LIMIT 20;

query returns me 'c' starting from 1st and limits it to 5. How can I fetch last five 'c' and then order them by commentedOn. Note** count of number of relations between 'a' and 'c' is not known, could be 1 could be 1000.

What I am trying to achieve is, return up to 20 'a' nodes with last to last-5 related relations 'c' for that path. for eg. your instagram home page could have 20 posts and each one of them may have many comments under one post collection, right? I am able to achieve till here, I can collect first 5 relations 'c', my question here is how do I collect last 5 relations 'c' given I have to match 20 'a' nodes.

If I understand the question correctly, you would like to fetch the last five comments - ie sort them by their timestamp (descending) and take the top 5. Use WITH to chain queries together, for example:

MATCH (a : User)-[c : Commented]->(b)
WITH DISTINCT
  a.username AS username,
  b.postId AS postId,
  c.comments AS commentBody,
  c.time AS commentedOn
ORDER BY commentedOn DESC
LIMIT 5
RETURN
   username, collect({postId : postId, commentBody : commentBody, commentedOn : commentedOn}) AS commentData
LIMIT 20

You'll want to make use of WITH so you can use the first part of your query to match on 20 users, then with those users, collect the last 5 comments of each.

Something like this should work or at least get you lose

MATCH (a : User)
// only interested in users that have commented
WHERE (a)-[:Commented]->()
WITH a LIMIT 20
// for those 20 users, get all their comments
MATCH (a)-[c : Commented]->(b)
// order results by time so we collect comments in order later
WITH a, c, b
ORDER BY c.time DESC
// return results, getting only the slice of 5 collected comments for each user
RETURN a.username AS username, COLLECT({commentBody : c.comments, commentedOn : c.time, postId : b.postId})[0..5] AS commentData

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