Lozzano
Lozzano

Reputation: 582

CouchDB map/reduce function to show limited results for a user by date

I am one of many SQL users who probably have a hard time transitioning to the NoSQL world, and I have a scenario, where I have tonnes of entries in my database, but I would only like to get the most recent ones, which is easy, but then it should all be for the same user. I'm sure it's simple, but after loads of trial and error without a good solution, I'm asking you for help!

So, my keys look like this.. (because I'm thinking that's the way to go!)

emit([doc.eventTime, doc.userId], doc);

My question then is, how would I go about only getting the 10 last results from CouchDB? For that one specific user. The reason why I include the time as key, is because I think that's the simplest way to sort the results descending, as I want the ten last actions, for example.

If I had to do it in SQL i'd do this, to give you an exact example.

SELECT * FROM table WHERE userId = ID ORDER BY eventTime DESC LIMIT 10

I hope someone out there can help :-)

Upvotes: 0

Views: 170

Answers (2)

Matt Jennings
Matt Jennings

Reputation: 1148

Change your key to:

emit([doc.userId, doc.eventTime], null);

Query with:

view?descending=true&startkey=[<user id>,{}]&endkey=[<user id>]&limit=10

Upvotes: 1

gro
gro

Reputation: 755

So add something like this to a view...

"test": {
           "map": "function(doc) { key = doc.userId; value = {'time': doc.eventTime, 'userid': doc.userId}; emit(key, value)}"
       }

And then call the view...(assuming userId = "123"

http://192.168.xxx.xxx:5984/dbname/_design/docname/_view/test?key="123"&limit=10

You will need to add some logic to the map to get the most recent, as I don't believe order is preserved in any manner.

Upvotes: 0

Related Questions