Edit Page

Collection Indexes

Before running the example requests

The following step by step tutorial assumes that RESTHeart is running on localhost with the default configuration: the database restheart is bound to / and the user admin exists with default password secret.

To run RESTHeart please first read the setup section.

To create the restheart db, run the following:

PUT / HTTP/1.1

The examples on this page use the inventory collection. To create the inventory collection, run the following:

PUT /inventory HTTP/1.1

To populate the inventory collection, run the following:

POST /inventory HTTP/1.1

[
   { "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" },
   { "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" },
   { "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" },
   { "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" },
   { "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
]

List the collection indexes

To list the collection indexes use the following request:

GET /inventory/_indexes HTTP/1.1
Response
[
    {
        "v": 2,
        "key": {
            "_id": 1
        },
        "ns": "restheart.inventory",
        "_id": "_id_"
    }
]

Create an index

To create an index you have to specify the keys and the index options:

{ "keys":  <keys>, "ops": <options> }

Example - create an unique, sparse index on property ‘qty’

To create an unique, sparse index on property qty run the following:

PUT /inventory/_indexes/qtyIndex HTTP/1.1

{"keys": {"qty": 1},"ops": {"unique": true, "sparse": true }}

See also Indexes in MongoDB documentation https://docs.mongodb.com/manual/indexes/

Example - create a text index on property ‘item’

To create a text index on property item run the following:

PUT /inventory/_indexes/itemTextIndex HTTP/1.1

{ "keys": { "item": "text" } }

Delete an index

To delete an index use the following request:

DELETE inventory/_indexes/qtyIndex HTTP/1.1

Notes

Invalid options

When creating an index the index options must be valid.

An example of invalid options is specifying the attribute unique on a property that is not actually unique; in this case the response will be 406:

Response
HTTP/1.1 406 Not Acceptable
 
{
    "_exceptions": [
        {
            "exception": "com.mongodb.DuplicateKeyException",
            "exception message": "Write failed with error code 11000 and error message 'E11000 duplicate key error index: test.coll.$name2 dup key: ...."
        }
    ],
    "http status code": 406,
    "http status description": "Not Acceptable",
    "message": "error creating the index",
    ...
}

Indexes cannot be updated

To update an index, it must be deleted and recreated:

Trying to update an existing index returns 406 Not Acceptable.