0

I want to get all those data in the same order, whatever the order is there in values array

{
  "query": {
    "ids": {
      "values": [
        "BqQI7ncBXJtfdGR-NWLA",
        "P6QAX3gBXJtfdGR-oWLL",
        "NKSJP3gBXJtfdGR-vWIY",
        "PqT-XXgBXJtfdGR-O2Kg"
      ]
    }
  }
}
Gaurav Kumar
  • 349
  • 1
  • 2
  • 13

1 Answers1

2

You need to use a function_score

The function_score allows you to modify the score of documents that are retrieved by a query. This can be useful if, for example, a score function is computationally expensive and it is sufficient to compute the score on a filtered set of documents.

Query

{
  "query": {
    "function_score": {
      "query": {
        "ids": {
          "values": [
                "BqQI7ncBXJtfdGR-NWLA",
                "P6QAX3gBXJtfdGR-oWLL",
                        "NKSJP3gBXJtfdGR-vWIY",
                        "PqT-XXgBXJtfdGR-O2Kg"
          ]
        }
      },
      "script_score": {
        "script": {
          "source": """
                        def count = params.ids.size();
                        def id    = doc['_id'].value;
                        for (int i = 0; i < count; i++) {
                          if (id == params.ids[i]) { return count - i; }
                        }
                    """,
          "params": {
            "ids": [
                       "BqQI7ncBXJtfdGR-NWLA",
                "P6QAX3gBXJtfdGR-oWLL",
                "NKSJP3gBXJtfdGR-vWIY",
                "PqT-XXgBXJtfdGR-O2Kg"
            ]
          }
        }
      }
    }
  },
  "size": 10,
  "from": 0
}
jaspreet chahal
  • 8,817
  • 2
  • 11
  • 29
  • I am getting the below warning by using this query:- #! Deprecation: Loading the fielddata on the _id field is deprecated and will be removed in future versions. If you require sorting or aggregating on this field you should also include the id in the body of your documents, and map this field as a keyword field that has [doc_values] enabled – Gaurav Kumar Jun 29 '21 at 08:25
  • @GauravKumar The _id field is restricted from use in aggregations, sorting, and scripting. In case sorting or aggregating on the _id field is required, it is advised to duplicate the content of the _id field into another field with type as keyword. Currently your query will be working, in future version doc[_id] might not be allowed – jaspreet chahal Jun 29 '21 at 08:56