简体   繁体   中英

COALESCE in Elasticsearch

I am using MongoId with ruby on rails. For my search I am using elasticsearch.

I have a date field. It is optional field and I use it as a stop date. In my search I would like to know if my stop date is greater than the search stop date. Example

{
  "range": {
    "stop_date": {
      "gt": "#{search_stop}"
    }
  }
}

The issue when the stop date is null I need it to be returned in this query, but it is not as the stop date is null or not in the document.

I need when the stop date is null or not in the document the search to be set as a default value like 21/31/2100.

Any advice will be really appreciated...

There are two approaches to this.

  1. One is to use null_value to stop_date in the mapping. This way , when you are indexing , if stop_date field is missing , the value set as null_value will go to the lucene reverse index. But the issue with this approach is that , this value would be static across all documents and acorss all times. Null_value - http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-core-types.html
  2. Second approach would be to change the query

     { "query": { "filtered": { "filter": { "or": [ { "range": { "stop_date": { "gt": "#{search_stop}" } } }, { "missing": { "field": "stop_date" } } ] } } } } 

    Here a document is matched if the stop_date field is missing or when the date range filter matched.

My recommendation would be to use second one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM