1
votes

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.

2
What is the criteria for selecting the 20 users? Just any 20 users that have commented on any post, and with those 20 users, get the last 5 comments from each of them on any post?InverseFalcon
@InverseFalcon yupRishik Rohan

2 Answers

1
votes

If I understand the question correctly, you would like to fetch the last five comments - i.e. 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
0
votes

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