What is the fastest way to filter views


#1

Consider I have a view as you see below;

function (doc, meta) {
if(doc._class == “Result”)
{
emit(meta.id,null);
}
}

I know that I am not able to query this view by using N1QL like in relational databeses but what is the fastest way to filter this query?

How can I add additional “if statements” to thi view or make the view act like it has additional if statements?


#2

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.


#3

Thank you for your reply.

Do you think adding more than one field to a key could work?

emit([doc.statusCode,doc.name,doc.result], null);

What if I compose and process the key as an array then I filter the array key regarding to its indexes? Do you think it will work much faster than N1QL?


#4

I think N1QL performance is on par with views in Couchbase Server 4.5.

The multi-key array can work, but it is still pretty limited, in the sense that keys inside are not truly independent. Using partial keys has a few quirks.


#5

N1QL performance is on par with views if we use GSI i guess. Do you give me some information about how to use GSI correctly?


#6

GSI is simply used as the default mode when creating indexes through N1QL. See the index documentation here for instance.