Trausti Thor
Trausti Thor

Reputation: 3774

Advanced day query with CouchDB

I have a problem with views in Couch DB (all versions 1.01 - 1.31).

My data looks like this :

{
   "_id": "9a12b7fa4b886640be06f74b814306a6",
   "_rev": "1-420c723f8c8f7921ead3df04bfc9ade5",
   "client_id": "008",
   "day": 1,
   "month": 1,
   "year": 2013,
   "comment": "cool"
}

And I want to see all transactions that client has done in a span of time, lets say 1 month :

so my map function is like :

function(doc) {
  emit([doc.client_id, doc.day,doc.month, doc.year], doc);
}

So I query with startkey and endkey like

http://localhost:5984/test/_design/clients/_view/by_cid_day_month_year?startkey=[%22007%22,1,1,2013]&endkey=[%22007%22,32,1,2013]

But instead of getting all documents from January with client_id = 007, I get all records matching 007.

So there has to be something that I am misunderstanding. What is wrong with my query ? How should it look ?

My thinking is that I could also just see logs from a specific date, or from say 1st jan to 6th jan.

I have tried to make the keys for day, month and year as strings, but the result is always the same, or even sometimes weird, like in the above example, I will find a record in September (9) but if I go to April f.ex. I get all records.

I don't understand this. This should be quite straight forward.

Upvotes: 0

Views: 138

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 181067

Since the match goes from start to end and stops at the first chance, you'll want to emit the most significant search criteria first. In your original query you emit date before month which will lead to the date matching no matter what month or year it is.

If you instead;

emit([doc.client_id, doc.year, doc.month, doc.day], doc);

the comparison will first check year, then month and last date, which is what you mean to do.

As a side note, to match any date, I seem to remember that you could simplify your search to;

...by_cid_year_month_day?startkey=[%22007%22,2013,1]&endkey=[%22007%22,2013,1,{}]

...since leaving the last element out makes the array sort before any array that is longer (any date), and {} will sort after any date. Searching for entire 2013 would then in the same way be;

...by_cid_year_month_day?startkey=[%22007%22,2013]&endkey=[%22007%22,2013, {}]

Upvotes: 2

Related Questions