Dogahe
Dogahe

Reputation: 1430

How to define an index to use in a Mango Query

I am trying to create a CouchDB Mango Query with an index with the hope that the query runs faster. At the moment I have the following Mango Query which returns what I am looking for but it's slow. Therefore, I assume, I need to create an index to make it faster. I need help figuring out how to create that index.

    selector: {
      categoryIds: {
        $in: categoryIds,
      },
    },
    sort: [{ publicationDate: 'desc' }],

You can assume that my documents are let say news articles from different categories. Therefore in each document I have a field that contains one or more categories that the news article belongs to. For that I have an array of categoryIds for each document. My query needs to be optimized for queries like "Give me all news that have categoryId1 in their array of categoryIds sorted by publicationDate". What I don't know how to do is 1. How to define an index 2. What that index should be 3. How to use that index in "use_index" field of the Mango Query. Any help is appreciated.

Update after "Alexis Côté" answer:

If I define the index like this:

{
  "_id": "_design/0f11ca4ef1ea06de05b31e6bd8265916c1bbe821",
  "_rev": "6-adce50034e870aa02dc7e1e075c78361",
  "language": "query",
  "views": {
    "categoryIds-json-index": {
      "map": {
        "fields": {
          "categoryIds": "asc"
        },
        "partial_filter_selector": {}
      },
      "reduce": "_count",
      "options": {
        "def": {
          "fields": [
            "categoryIds"
          ]
        }
      }
    }
  }
}

And run the Mango Query like this:

{
   "selector": {
      "categoryIds": {
         "$in": [
            "e0bd5f97ac35bdf6893351337d269230"
         ]
      }
   },
   "use_index": "categoryIds-json-index"
}

It still does return the results but they are not sorted in the order I want by publicationDate. So I am not clear what you are suggesting the solution is.

Upvotes: 1

Views: 2376

Answers (1)

Alexis Côté
Alexis Côté

Reputation: 3690

  1. You can create an index as documented here
  2. In your case, you will need an index on the "categoryIds" field.
  3. You can specify the index using "use_index": "_design/<name>"

    Note:The query planner should automatically pick this index if it's compatible.

Upvotes: 0

Related Questions