1
votes

I'm trying to get the last 10 transactions for a specific user.

For example, I have these documents:

{ "user": 1, "date": 1442408126 }
{ "user": 1, "date": 1442408130 }
{ "user": 1, "date": 1442408140 }
{ "user": 2, "date": 1442408126 }

And I defined this view:

// MAP:
function (doc, meta) {
  if(meta.type == "json") {
    if(doc.user && doc.date) {  
      var eventKey = dateToArray(new Date(parseInt(doc.date)));
      eventKey.unshift(doc.user);

      emit(eventKey, {"date":doc.date});
    }
  }
}

// REDUCE:
function(key, values, rereduce) {
  return values.slice(0,10);
}

When reduce=true and group_level=1, this is the result (which is good):

Key    Value
[1]    [ { "date": 1442408140 }, { "date": 1442408130 }, { "date": 1442...
[2]    [ { "date": 1442408126 } ]

now, when I query the view with startKey=[1] and endKey=[2] (stale=false&startkey=%5B1%5D&endkey=%5B2%5D&group=true&group_level=1&reduce=true&connection_timeout=60000&limit=10&skip=0), I get the row that I want:

Key    Value
[1]    [ { "date": 1442408140 }, { "date": 1442408130 }, { "date": 1442...

BUT, I want to use key=[1] and not do a range search.

When I use the key parameter (stale=false&group=true&group_level=1&key=%5B1%5D&reduce=true&connection_timeout=60000&limit=10&skip=0), I get an empty result.

Using startKey=[1] and endKey=[1] with inclusive_end=true also returns an empty list.

what am I doing wrong?

2
How are you using the key parameter? By querying the view with startKey[1] ? - sweetiewill
No, I'm trying to use "key=[1]", but I don't mind any solution that allows me to query by a specific key. - asafd

2 Answers

0
votes

For Couchbase, believe there is a built-in _count function that automatically handles the rereduce so that you get a count of all items in a result set, not the count of the reduced set.

Can reference the Reduce Functions on the documentation page.

0
votes

found the answer: when using a view with a complex key, one cannot use the 'key' parameter in a query. In this case we have to use startKey and endKey while the endKey is the same as the startKey but with an addition of an empty object at the end. For example startKey=[1], endKey=[1,{}]

More details here: http://ryankirkman.com/2011/03/30/advanced-filtering-with-couchdb-views.html