AndrewM
AndrewM

Reputation: 79

Return only particular relationships (from multiple of one type) between two nodes

Let's say I have: two types of nodes: User, Place and relationship between these two: Rates (User RATES Place, can rate same place multiple times)

I want to get list of most recent ratings (per user) for particular Place (providing placeId) for all users

So from following situation:

USER_1 RATES (createdAt: yesterday) PLACE_1
USER_1 RATES (createdAt: today) PLACE_1
USER_2 RATES (createdAt: yesterday) PLACE_1
USER_2 RATES (createdAt: today) PLACE_1

I want to retrieve:

USER_1 RATES (createdAt: today) PLACE_1
USER_2 RATES (createdAt: today) PLACE_1

Is it doable via cypher query or should I rather change logic and mark particular RATES relationship as most recent?

Upvotes: 2

Views: 85

Answers (1)

Muldec
Muldec

Reputation: 4901

MATCH (u)-[r:RATE]->(p)
With u, r, p
order by r.createdAt desc
with u, collect(r) AS rates, p 
return u, head(rates), p

First, get all relations and order them by createdAt from most recent to less recent (DESC)

Then create a list of rates given by a user to a place with collect

Finally, return the first element of each list with head to retrieve the most recent rate

Upvotes: 1

Related Questions