Find full date, not only year (Elasticsearch)

190 Views Asked by At

In normal situation I have fill date, but for some records I have dates in format yyyy / yyyy-MM. And in search results I don't want dates that have only year.

Structure definition:

[premiere_date] => Array
  (
    [type] => date
    [format] => dd.MM.yyyy||MM.yyyy||yyyy||yyyy-MM-dd
 )

Example data:

{'name': 'a', 'premiere_date': '1984-11-22'},
{'name': 'b', 'premiere_date': '1984-12'},
{'name': 'c', 'premiere_date': '1985'},

In result i want:

{'name': 'a', 'premiere_date': '1984-11-22'},
{'name': 'b', 'premiere_date': '1984-12'},

I tried add format to range filter, bit it don't work

{
    "query": {
        "bool": {
            "filter": [
                {
                    "range": {
                        "premiere_date": {
                            "gte": "1983-12-22",
                            "lt": "1988-03-21",
                            "format": "yyyy-MM-dd"
                        }
                    }
                }
            ]
        }
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

Elasticsearch converts values of the "date" data type to an long number representing milliseconds since the epoch UTC. This is the representation which is indexed and searched. So Elasticsearch does not implicitly know the original date value from the source document has only the year. Your application must add another field representing the date's resolution, and the search must also filter on that field. For example,

{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "premiere_date": {
             "gte": "1983-12-22",
             "lt": "1988-03-21"
          }
        }
      },
      "must_not": {
        "term": {
          "premiere_date_resolution": "year"
        }
      }
    }
  }
}