couchdbcouchdb-mango

Unable to run a Mango query


This is my query:

{
   "selector": {
      "_id": {
         "$regex": "^rati"  //need to find all documents in ratings partition
      }
   },
   "fields": [
      "MovieID",
      "UserId",
      "Rating"
   ],
   "limit": 10,
   "sort": [
      {
         "MovieID": "asc"
      }
   ]
}

When I run this query I have that error: Error running query. Reason: (no_usable_index) No global index exists for this sort, try indexing by the sort fields.

If I remove

"sort": [
          {
             "MovieID": "asc"
          }
       ]

everything works good. Honestly I'm going crazy, I can't understand where I'm wrong.

I've tried this query:

{
   "selector": {
      "_id": {
         "$regex": "^rati"
      },
      "MovieID": {
         "$gte": 0
      }
   },
   "fields": [
      "_id",
      "MovieID",
      "UserId",
      "Rating"
   ],
   "limit": 10,
   "sort": [
      {
         "_id": "asc"
      }
   ]
}

but is the same.


Solution

  • You need to create an Index for the field MovieID

    //Create via POST /db/_index HTTP/1.1 Content-Type: application/json
    
    {
        "index": {
            "fields": ["MovieID"]
        },
        "name" : "MovieID-index",
        "type" : "json"
    }
    

    Afterward include the field MovieID as part of the Selector.

    Try this here:

    {
       "selector": {
          "_id": {
             "$regex": "^rati"  //need to find all documents in ratings partition
          },
          "MovieID": {"$gte": 0} // include MovieID, If the ID is non-numeric change the selecor type.
       },
       "fields": [
          "MovieID",
          "UserId",
          "Rating"
       ],
       "limit": 10,
       "sort": [
          {
             "MovieID": "asc"
          }
       ]
    }