Sarim
Sarim

Reputation: 41

How to reduce query execution time using mango query in CouchDB?

I am doing pagination of 15000 records using mango query in CouchDB, but as I skip the records in more numbers then the execution time is increasing.

Here is my query:

{
  "selector": {
    "name": {"$ne": "null"}
  },
  "fields": ["_id", "_rev", "name", "email" ],
  "sort": [{"name": "asc" }],
  "limit": 10,
  "skip": '.$skip.'
}

Here skip documents are dynamic depends upon the pagination number and as soon as the skip number increases the query execution time also get increase.

Upvotes: 1

Views: 1351

Answers (1)

Glynn Bird
Glynn Bird

Reputation: 5637

CouchDB "Mango" queries that use the $ne (not equal) operator tend to suffer performance issues because of the way the indexing works. One solution is to create and index that *only contains documents where name does not equal null by using CouchDB's relative new partial index feature.

Partial indexes allow the database to be filtered at index time, so that the built index only contains documents that pass the filter test you specify. The index can then be used with a query at query time to further winnow the data set down.

An index is created by calling the /db/_index endpoint:

POST /db/_index HTTP/1.1
Content-Type: application/json
Content-Length: 144
Host: localhost:5984

{
  "index": {
    "partial_filter_selector": {
      "name": {
        "$ne": "null"
      }
    },
    "fields": ["_id", "_rev", "name", "email"]
  },
  "ddoc": "mypartialindex",
  "type" : "json"
}

This creates an index where only documents whose name is not null are included. We can then specify this index at query time:

{
  "selector": { 
    "name": {
      "$ne": "null"
    }
  },
  "use_index": "mypartialindex"
}

In the above query, my selector is choosing all records, but the index it is accessing is already filtered. You may add additional clauses to the selector here to further filter the data at query time.

Partial indexing is described in the CouchDB documentation here and in this blog post.

Upvotes: 1

Related Questions