A newer version of this documentation is available.

View Latest

Indexing Metadata Information

    +

    Couchbase Server allows indexing on selected metadata fields, for example the expiration and CAS properties. This improves performance of queries involving predicates on the metadata fields, such as expired documents or recently modified documents.

    Overview

    The META() function enables you to return the metadata for a keyspace or document. To index a selected metadata field, you must use a nested expression containing the META() function and the required property, for example META().id.

    The property name must be separated from the META() function by a dot (.) and only the following metadata properties can be indexed. If you attempt to build an index on a metadata field that is not indexable, an error is returned.

    cas

    Value representing the current state of an item which changes every time the item is modified. For details, refer to Concurrent Document Mutations.

    expiration

    Value representing a document’s expiration date. A value of 0 (zero) means no expiration date. For details, refer to Core Operations.

    Note that this property gives correct results only when used in a Covered Index.

    id

    Value representing a document’s unique ID number.

    The META() function does not require a keyspace parameter when creating an index, since it implicitly uses the keyspace being indexed.

    Examples

    Example 1. Find two documents that have no expiration date
    Index
    CREATE INDEX idx_expir ON `travel-sample` ( META().expiration );
    Query
    SELECT META().id, META().expiration
    FROM `travel-sample`
    WHERE META().expiration = 0
    ORDER BY META().id
    LIMIT 2;
    Results
    [
      {
        "expiration": 0,
        "id": "airline_10"
      },
      {
        "expiration": 0,
        "id": "airline_10123"
      }
    ]
    Example 2. Find all documents whose meta ID tag starts with a letter higher than "g"
    Index
    CREATE INDEX idx_id ON `travel-sample` (META().id );
    Query
    SELECT name, META().id
    FROM `travel-sample`
    WHERE META().id > "g"
    LIMIT 2;
    Results
    [
      {
        "id": "hotel_10025",
        "name": "Medway Youth Hostel"
      },
      {
        "id": "hotel_10026",
        "name": "The Balmoral Guesthouse"
      }
    ]
    Example 3. Find the two most recently modified hotel documents
    Index
    CREATE INDEX idx_cas ON `travel-sample` ( META().cas );
    Query
    SELECT name, META().cas
    FROM `travel-sample`
    WHERE type="hotel"
    ORDER BY META().cas DESC
    LIMIT 2;
    Results
    [
        {
            "cas": 1503510338735374337,
            "name": "Hotel Formule 1"
        },
        {
            "cas": 1503510338734850048,
            "name": "Harbour Cottage Gardenstown"
        }
    ]