Philip Koch
Philip Koch

Reputation: 347

CouchDB _changes-API filter

I'm trying to get a filtered _changes-API stream on CouchDB 2.1.1 to work, but I run into issues. I only want to receive documents via the changes feed that contain the field "type" with the value "article".

According to the documentation something like this should work:

function (doc, req) {
  if (doc.type && doc.type == 'article') {
    return true;
  }
  return false;
}

I created the function above in a new view called type_article in a _design document called filters using Fauxton. When I click on the view I don't see any results there.

Now I want to retrieve the filtered changes feed from the DB using the filter as a GET-parameter: localhost:5984/my_database/_changes?filter=filters/type_article

The response of CouchDB is {"error":"not_found","reason":"missing json key: filters"}

Do you have an idea how I can get the filter-functionality to work?

PS: I also tried using the 'emit()' function instead of returning true and false, this returned the expected results, but when trying to query _changes the same error appeared.

Upvotes: 2

Views: 1240

Answers (2)

eiri
eiri

Reputation: 321

Just a note, you actually can use view as a filter for _changes. In this case a document counted passed if a map function emits at least one record for it.

For example, if a design document (called "ddoc") looks something like this:

{"views":
    {"type_article":
        {"map":
            "function(doc) {
                if (doc.type && doc.type == 'article') {
                    emit(doc.name);
                }
            }"
        }
    }
}

Then a query would look like localhost:5984/my_database/_changes?filter=_view&view=ddoc/type_article. Note a missing _design prefix and a keyword _view for an attribute filter. Here is a link on an according documentation section: [link]

The only thing to be aware here is that this filter not actually using built view index and therefore not faster than an ordinary filter function.

Upvotes: 1

Philip Koch
Philip Koch

Reputation: 347

I found the problem. When you create a view in the Fauxton using small + sign next to the Design Documents menu entry you can only created views. Views are different than filters. To create a filter that works with the _changes feed click on 'Create Document' and create a document like this:

{
  "_id": "_design/filters",
  "filters": {
    "type_article": "function (doc, req) {\n  if (doc.type && doc.type == \"article\") {\n    return true;\n  } else { \n return false; \n}\n}"
  }
}

This will create a new design document called filters with a function type_article.

Upvotes: 1

Related Questions