1

I have documents and a view where you can search by the keywords list. A document may look like:

{
  _id: "foo",
  keywords: ["bar", "baz"],
}

Then, I have the view:

map: function (doc) {
  doc.keywords.forEach(function(word) {                                  
    emit(word, doc);                                            
  });
}

This works great in that I get the foo document back, but the issue is if I don't provide a key I get this document twice which makes sense because it has two keywords. However, I only need/want the document once.

I have also added

reduce: function (key, value, rereduce) {                               
  return value;                                                   
}

but this gives me reduce_overflow_error. If I use return null then the value I get for the document is null which is no good either.

I've also read about using a list function for this, but I'm not sure where the list function is supposed to go in the couchapp. This also seems pretty complicated for what I think should be fairly simple.

How can I stop the duplicates from coming when querying the view?

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405

1 Answers1

0

I find your query confusing, but let me help you with an error.

In the reduce function you have multiple values (ie. an array of documents with the same key). So if you rewrite your reduce function as below, you would get an index of keywords with exactly one document per keyword back, however a reduced document does not link to the origin document anymore.

function (key, values, rereduce){
    return values[0];
}

If your use case was to get a count of documents per keyword you would write it as:

function (key, values, rereduce){
    if (rereduce){
        var sum = 0;
        for (i=0; i< values.length(); i++){
            sum = sum + values[i];
        }
        return sum;
    }
    return values.length();
}

In any case where you want the index items to refer you to the document that contains the key, you cannot use the reduce function.

Hans
  • 2,800
  • 3
  • 28
  • 40