Solve the problem that Elasticsearch cannot obtain the maximum value sorted by _id

Recently when I was working on a blockchain browser, I used blockNumber as the document_id of elasticsearch. I needed to do a query operation, so I changed it to mysql query.

SELECT MAX(`_id`) FROM `block`; 

Corresponding query in Kibana

GET /block/_search
{
  "query": {
    "bool": {
      "must": [
        {"match": {
          "transactionHandled": true
        }}
      ]
    }
  },
  
  "sort": [
    {
      "_id": {
        "order": "desc"
      }
    }
  ]
}

The result of the query is always that the document with "_id" as "99" is ranked first, which is obviously not in line with my expectations. By querying the information, we get the following solutions:

The reason is that your IDs are strings, and strings are sorted lexicographically (not numerically), so in the string world 9999 > 1000000.

What you should do is create another numeric field in the document that contains the equivalent number to the ID field and sort by that numeric field.

Guess you like

Origin blog.csdn.net/HardRedStone/article/details/119919336