Neo4j Cypher: using LIMIT and COLLECT (or using LIMIT twice in the same request)

I have a timeline type query that retrieves messages and users who “love” the message.

START me=node:node_auto_index(UserIdentifier='USER0') MATCH me-[rels:FOLLOWS*0..1]-myfriend WITH myfriend MATCH myfriend-[:POSTED*]-statusupdates<-[r?:LIKE]-likers WHERE myfriend <> statusupdates RETURN distinct statusupdates, FILTER (x in collect(distinct likers) : x <> null), myfriend ORDER BY statusupdates.PostTime DESC LIMIT 25; 

I limit the number of messages I receive to 25. I would also like to limit the number of users who liked the post. Is there a way to use multiple constraints in a query? Ideally, I would like to do something like the following:

 START me=node:node_auto_index(UserIdentifier='USER0') MATCH me-[rels:FOLLOWS*0..1]-myfriend WITH myfriendMATCH myfriend-[:POSTED*]-statusupdates<-[r?:LIKE]-likers WHERE myfriend <> statusupdates RETURN distinct statusupdates, LIMIT FILTER (x in collect(distinct likers) : x <> null) 6, myfriend ORDER BY statusupdates.PostTime DESC LIMIT 25; 

Or:

 START me=node:node_auto_index(UserIdentifier='USER0') MATCH me-[rels:FOLLOWS*0..1]-myfriend WITH myfriendMATCH myfriend-[:POSTED*]-statusupdates<-[r?:LIKE]-likers WHERE myfriend <> statusupdates RETURN distinct statusupdates, FILTER (x in collect(distinct likers) : x <> null), myfriend LIMIT likers 6 ORDER BY statusupdates.PostTime DESC LIMIT 25; 

Which would limit the number of characters returned for each message to 6. How can I achieve this?

+4
source share
2 answers

The problem with user restrictions is that there is no way to optimize this at the other end of the request. You basically have to do two matches. In addition, LIMIT after WITH is only available in 1.9.M01

So, I think this does what you want:

 START me=node:node_auto_index(UserIdentifier='USER0') MATCH me-[rels:FOLLOWS*0..1]-myfriend-[:POSTED*]-statusupdates<-[r?:LIKE]-likers WITH distinct likers // you can also order by something here, if you want. LIMIT 6 START me=node:node_auto_index(UserIdentifier='USER0') // at this point, likers is already bound, so it limited to the 6 MATCH me-[rels:FOLLOWS*0..1]-myfriend-[:POSTED*]-statusupdates<-[r?:LIKE]-likers RETURN distinct statusupdates, likers, myfriend ORDER BY statusupdates.postTime LIMIT 25; 

Unverified code. I hope this works - next time we’ll create a sample for us in the console so we can play. :)

+8
source

In Neo4j 2.0 you can use collection slices. That is, you can make queries similar to

MATCH (n)-[r*0..1]-(x) RETURN n, LABELS(n), COLLECT([x,id(x),LABELS(x),r])[0..10] LIMIT 5

In the above example, up to 5 n-nodes would be returned with 0 to 10 related nodes in the collection.

+3
source

Source: https://habr.com/ru/post/1446350/


All Articles