Perform sort on field that's not primary index

2019-09-11 14:03发布

问题:

Error:

No index exists for this sort, try indexing by the sort fields.

I've tried creating indexes on anotherValue, _id+anotherValue, but no difference.

This is my query:

{
  "selector": {
    "_id": { "$gt": null },
    "$or": [
          { "_id": "10" },
          { "value": "10", "anotherValue": "1234" }]
  },
  "sort": [{"anotherValue": "desc"}]
}

Indexes setup:

Your available Indexes:
special: _id

回答1:

Try adding a desc index on anotherValue:

{
  "index": {
    "fields": [
      {"anotherValue":"desc"}
    ]
  },
  "type": "json"
}

and change your query to this:

{
  "selector": {
    "anotherValue": { "$gt": null },
    "$or": [
      { "_id": "10" },
      { "value": "10", "anotherValue": "1234" }
    ]
  },
  "sort": [{"anotherValue": "desc"}]
}

Note: Your original query would also work if you added a text index on all fields:

{
  "index": {},
  "type": "text"
}