What is the fastest way to filter views

A view isn’t something that you can dynamically query with additional filters. It basically builds an index which key is the first part of the emit(key, reduce_value) call.

After that, if you query the view and provide a key, it’ll look up that key in said index. So for example if you create a view that emit(doc.firstName, null), you’ll be able to lookup all documents whose firstName is Simon.

Queries can go a little beyond that, because you can also query a range of “keys” (eg. a range of first names).
And if you don’t specify a key, all documents indexed by the view will be returned.

Note that the document id is ALWAYS returned by a view query, no need to use it as the view’s key.

So here, you are re-creating the document id index that Couchbase naturally has, on a subset of the documents in your db. That is a bit redundant and I’m sure it can be improved using the information above:

Say your Result document has a statusCode field. Maybe you want to be able to get all results that have a particular status code? For that, do a emit(doc.statusCode, null); instead of meta.id
That will be a more useful index, because now you can pass in a code to the view query and you’ll get relevant documents.

And the best thing is, if you don’t pass anything you still get all Result documents!

For anything more complicated than that, or if you need more than one query criteria, use N1QL.

1 Like