Indexing your Data

    +

    Description — Couchbase Lite database data model concepts - indexes
    Related Content — Databases | Documents | Indexes |

    Before we begin querying documents, let’s briefly mention the importance of having an appropriate and balanced approach to indexes.

    Creating indexes can speed up the performance of queries. A query will typically return results more quickly if it can take advantage of an existing database index to search, narrowing down the set of documents to be examined.

    Example 1. Creating a new index

    This example creates a new index for the type and name properties, shown in this data model:

    {
        "_id": "hotel123",
        "type": "hotel", (1)
        "name": "Apple Droid"
    }

    The code to create the index will look something like this:

    // For value types, this is optional but provides performance enhancements
    var index = IndexBuilder.ValueIndex(
        ValueIndexItem.Expression(Expression.Property("type")),
        ValueIndexItem.Expression(Expression.Property("name"))); (1)
    db.CreateIndex("TypeNameIndex", index);
    1 Where there are multiple expressions, the first becomes the primary key, the second the secondary key and so on.

    When planning the indexes you need for your database, remember that while indexes make queries faster, they may also:

    • Make writes slightly slower, because each index must be updated whenever a document is updated

    • Make your Couchbase Lite database slightly larger.

    So too many indexes may hurt performance. Optimal performance depends on designing and creating the right indexes to go along with your queries.