Rajkumar S
Rajkumar S

Reputation: 2521

Do a CouchDB reduce query for a single key

I have a CouchDB with following doc:

{
  "name":"Chris",
  "tags":["mustache", "music", "couchdb"]
}

{
  "name":"Noah",
  "tags":["hypertext", "philosophy", "couchdb"]
}

{
  "name":"Jan",
  "tags":["drums", "bike", "couchdb"]
}

Map Function:

function(dude) {
  if(dude.name && dude.tags) {
    dude.tags.forEach(function(tag) {
      emit(tag, 1);
    });
  }
}

Reduce Function:

function(keys, values) {
  return sum(values);
}

Now, if I query the view with the ?group=true parameter, I get back the count for each tag:

{"rows":[
{"key":"bike","value":1},
{"key":"couchdb","value":3},
{"key":"drums","value":1},
{"key":"hypertext","value":1},
{"key":"music","value":1},
{"key":"mustache","value":1},
{"key":"philosophy","value":1}
]}

What query should I use to get the value of just "couchdb" alone?

This example was taken from the CouchDB book, while my live application has 1000s of keys and most of the time I just needs to find the count of one individual key.

I am not able to use key= parameter, which is really what I want, as it returns an empty result.

If I query ?group=true&startkey="couchdb"&endkey="drums" I get the count of couchdb alone, but I cannot use startkey= and endkey= because I do not know what the next key will be in a live DB.

What solutions would you recommend in this situation?

Upvotes: 2

Views: 1132

Answers (1)

Bernhard Gschwantner
Bernhard Gschwantner

Reputation: 1537

key="couchdb"&group=true should work.

We have several views and queries in production that work exactly like that, and I just tried one of them. If you get an empty result, maybe the key is not exactly the same that you emit. Double check if you emit a single string as the key (your posted map function does that right) and if there are any capitalization differences (use toLowerCase() to be sure - which should not be necessary in your example).

In other situations (any tag starting with "couchdb") you could use an endkey with a high character at the end ("couchdb\ufff0"), but this doesn't help here.

Upvotes: 4

Related Questions