简体   繁体   中英

Elasticsearch script filter on object array

I've got a following elasticsearch document:

{
"json":{
  "freeSlots":[
         {
            "day":"2015-04-21",
            "beginTime":"08:00:00",
            "endTime":"09:00:00"
         },
         {
            "day":"2015-04-21",
            "beginTime":"14:00:00",
            "endTime":"17:00:00"
         }
      ]
   }
}

and I expected that this kind of query would return it:

{
"query" : {
    "filtered" : {
        "query" : {
            "match_all" : {}
        }
     },
     "filter" : {
         "script": {
             "script" : "doc['json.freeSlots.endTime'].value - doc['json.freeSlots.beginTime'].value > param1",
             "params" : {
                 "param1" : 7200000
             }
          }
     }
 }

Unfortunately it considers only first element of array and its difference between endTime and beginTime is less than 7200000 ms. How can I change this query so that it returns any document containing an object within freeSlots array which duration (difference between endTime and beginTime ) is greater than 7200000 ms? Date mappings are set.

I'd index each slot as a separate document: { "day":... "beginTime":... "endTime":... }

Then use this query:

{ "query": { "filter": { "script": { "params": { "delta": 7200000 }, "script": "(doc['endTime'].value - doc['beginTime'].value) > delta" } }, "filtered": { "query": { "match_all": {} } } } }

Also, you may need to configure the script in the server (AFAIK recent versions don't suppport this kind of dynamic script).

One way of debugging what's going on is to use a script_field to output some values:

... "script_fields": { "delta": { "file": "debug_script_fields", "lang": "groovy" } } ...

In the server, in config/scripts add a file debug_script_fields.groovy :

doc['endTime'].value - doc['beginTime'].value

If the value is not what you expect it's unlikely that the filtered query will work.

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