Skip to content

CBLView.documentType

Jens Alfke edited this page Mar 11, 2015 · 2 revisions

CBLView.documentType is a new property that can be used to optimize view indexing. Depending on the specifics of the database and the view, it can speed up indexing by 2x to 4x.

Availability: documentType was added to couchbase-lite-ios in commit aa0375f on 11 March 2015 (see issue #590.) It will be in the 1.1 release. It will make its way to the other platforms too.

What's it for?

There's a very common idiom of using a "type" property to identify different types of documents; sort of an informal, schemaless equivalent of a SQL table. Consequently, it's also very common for a view to apply only to a single type of document, ignoring the others; its map block would look something like

    if ([doc[@"type"] isEqual: @"playlist"]) {
        emit(doc[@"name"], doc[@"trackCount"]);
    }

The CBLView.documentType property optimizes this pattern. Setting it to a non-nil value declares that the view's map block only cares about documents whose "type" property is equal to that value; as a result, only such documents will be passed to the map block.

The reason this is an optimization is that Couchbase Lite now internally tags each document with its "type" value, and the indexer can use that tag to quickly skip past documents that aren't relevant to the view being indexed. That saves the time that would have been spent reading the document body, parsing the JSON, and calling the map block.

In addition, CBLQueryBuilder automatically makes use of this optimization. If it detects that the predicate contains an equality test between the document's "type" and a constant string, it will set the view's documentType to that string.

How to use it

Like the map block, the documentType property is not persistent, so you need to set it on every launch, before the view might be queried or indexed. It's best to set it right before setting the map block:

CBLView* view = [db viewNamed: @"vu"];
view.documentType = @"playlist";
[view setMapBlock: MAPBLOCK({
    emit(doc[@"name"], doc[@"trackCount"]);
}) version: @"2"];

Note that the map block doesn't need to test the "type" property, because it knows the indexer will only call it on documents of type "playlist"!