Search code examples
viewcouchdbpollingwatch

CouchDB change API on view


Say I have a document "schema" that includes a show_from field that contains a timestamp as a Unix epoch. I then create a view keyed by this show_from date and only return those documents with a key on or before the current timestamp (per the request). Thus documents will appear in the view "passively", rather than from any update request.

Is it possible to use the CouchDB change API to monitor this change of view state, or would I have to poll the view to watch for changes? (My guess is the latter, because the change API seems only to be triggered by updates, but just for the sake of confirmation!)


Solution

  • The _changes feed can be filtered in a number of ways. One of the ways of filtering the _changes feed is reusing a view's map function.

    GET /[DB]/_changes?filter=_view&view=[DESIGN_DOC]/[VIEW_NAME]

    Note:

    For every _changes request, CouchDB is going to look at each change and run it over the filter function (or in this case the view's map function). None of this is cached for subsequent requests (as on mapreduce views). So it can be quite taxing on resources, unless the changeset is small.

    For a large dataset (with many changes) it can be useful to bootstrap with the view, and only incrementally keep track of changes.

    Additional info:

    Using _changes you can poll for changes since a given sequence point, for the latest N changes, etc. You can also use long polling, or a continuous feed. As long as the changeset to consider (and filter through) is small, it makes sense to use _changes.


    But if the view is itself ordered chronologically, as it seems to be your case, it may be pointless to use changes. Just query the view.