RooSoft
RooSoft

Reputation: 1501

Elasticsearch: filter by max field value in a given mapping

About this Elasticsearch mapping

PUT /some-index/_mapping/some-mapping
{
  "properties": {
    "group-id": {
      "type": "keyword"
    },
    "id": {
      "type": "keyword"
    },
    "some-other-field": {
      "type": "keyword"
    }
  }
}

Lets say we have values such as these

[
  { "group-id": "1", "id": "1", "some-other-field": "some" },
  { "group-id": "2", "id": "2", "some-other-field": "other" },
  { "group-id": "2", "id": "3", "some-other-field": "field" }
]

Trying to build a query

Return all records with largest group-id. In this specific example, it should exactly return the last 2 items including id and some-other-field. Of course, the largest group-id could get bigger as new records get indexed. If that occurs, a completely new set of results should be returned as the previous ones wouldn't contain the largest group-id anymore.

Upvotes: 1

Views: 374

Answers (1)

alr
alr

Reputation: 1804

If you need to support by a largest ID, you should change the type of your fields to a number.

You could use a max aggregation to find out the maximum value first (if this is a numeric field), and then execute a second query, searching for all documents with that maximum value (dont be afraid to execute more than one query to answer your question, it is perfectly fine).

Upvotes: 1

Related Questions