cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Find last session

Hi everyone!

I am creating a web event action domain and I would like to get the last session of the user.

I thought that adding a new relationship to the last session, it would be enough but having an indexed timestamp of the session, for me it does not make sense because I can query that one.

But the problem comes when I try to get the last node with cypher. I try in some ways but the query was not successful

MATCH (u:User { uuid: 'xxxx' })-[:ACTIVITY_AT]->(s:Session)
MATCH (u:User { uuid: 'xxxx' })-[:ACTIVITY_AT]->(s2:Session)
WHERE s.timestamp > s2.timestamp
return s

I know that query does not make sense but I do not know which condition apply to get the last node.

I might be wrong with that design because if I would add to each session NEXT relationship and find a node that does not have NEXT relationship as an output, I would get the desired node. But why to add more relationships if I can use the index?

Thanks!

1 ACCEPTED SOLUTION

If you want to go with indexes, at the least you would need a composite index on the uuid (for the associated user) and the session's timestamp.

For a non-index approach, all you would need is a sort and a limit:

MATCH (:User { uuid: 'xxxx' })-[:ACTIVITY_AT]->(s:Session)
WITH s
ORDER BY s.timestamp DESC
LIMIT 1
RETURN s

View solution in original post

4 REPLIES 4

If you want to go with indexes, at the least you would need a composite index on the uuid (for the associated user) and the session's timestamp.

For a non-index approach, all you would need is a sort and a limit:

MATCH (:User { uuid: 'xxxx' })-[:ACTIVITY_AT]->(s:Session)
WITH s
ORDER BY s.timestamp DESC
LIMIT 1
RETURN s

Would it be also the same cypher for the indexed nodes or is it another way to do it?

What do you think, if we add LAST_SESSION relationship to the last session node, like this we would traverse that relationship and we would get the last session. That thought came for example, if we need to get all the users last session. Like this the cypher would be easier and it would not have do many operations to get the result

In that case,

MATCH (u:User)-[:LAST_SESSION]->(s:Session)
return s

Thanks for your time!

That's true, it would help, but you would need to make sure you're properly updating the relationship (delete the old, create a new) so it's always up to date.

As always giving a hand, thanks for your help and time. I will continue with my research how can I optimise that domain because now I need to think about the events of each session.