Neo4j cypher query: get last N elements

I have a graph that contains a relationship between users, showing what user has visited another's profile, and when:

(visitor:User)-[:VISITED]->(visitee:User)

But I don't want to store every visit since the beggining of time. I only want the last X users that a user has visited. So before adding a new relationship I must delete the oldest one, but I don't know how to delete it. I can only get a list ordered by date:

MATCH (visitor:User)-[r:VISITED]->(User)
WHERE visitor.user_id = %s
RETURN r
ORDER BY r.date

What I need is to delete the first relationship in this list. How can I do that?

Upvotes: 2

Views: 1533

Answers (1)

Chris Leishman
Chris Leishman

Reputation: 1798

The simplest would be to use an ORDER BY and a LIMIT before the DELETE. I.e.:

MATCH (visitor:User)-[r:VISITED]->(User)
WHERE visitor.user_id = %s
WITH r ORDER BY r.date LIMIT 1
DELETE r

A more efficient mechanism may be to keep a linked list of visit (there's some discussion on this here: http://docs.neo4j.org/chunked/stable/cypherdoc-linked-lists.html)

Upvotes: 5

Related Questions