How to apply filter in computed field used script in elaticsearch


(yanianthe) #1

My use case is to filter in my computed field used script field,is there any way I can reuse the script field definition in order to apply "terms query" in the "bool" ?

{ "query": { "bool": 
            { "must": [ 
                          { "script": { "script": {
                                        "inline":"def monthyear =doc['GoUpDate'].date.year + '-' + doc['GoUpDate'].date.monthOfYear; int flag= 0; for(int i =0;i<params.enums.length;i++){ if(params.enums[i]==monthyear) { flag=1; break; } };return flag ",
                                        "lang":"painless",
                                        "params":{"enums":["2015-1","2015-2"]} } } } ] } },
"script_fields": { "test1": { "script": 
                            { "lang": "painless", "inline": "doc['GoUpDate'].date.year + '-' + doc['GoUpDate'].date.monthOfYear " } } } }

thanks!


(Luiz Santos) #2

Hi @yanianthe,

I will try a different approach to filter these dates, please let me know if it work for you.
I think it's more straightforward: use range query with format + date math.

The idea is to filter GoUpDate field by month without extract the month using script.

POST my_index/doc/1
{
  "GoUpDate": "2015-01-18T00:00:00"
}

POST my_index/doc/2
{
  "GoUpDate": "2015-02-18T00:00:00"
}

POST my_index/doc/3
{
  "GoUpDate": "2015-03-18T00:00:00"
}

GET my_index/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "range": {
            "GoUpDate": {
              "gte": "2015-01||/M",
              "lte": "2015-01||/M",
              "format": "yyyy-MM"
            }
          }
        },
        {
          "range": {
            "GoUpDate": {
              "gte": "2015-02||/M",
              "lte": "2015-02||/M",
              "format": "yyyy-MM"
            }
          }
        }
      ]
    }
  },
  "script_fields": {
    "test1": {
      "script": {
        "lang": "painless",
        "source": "doc['GoUpDate'].value.year + '-' + doc['GoUpDate'].value.monthOfYear "
      }
    }
  }
}

Results in docs 1 and 2 only:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
  },
  "hits": {
"total": 2,
"max_score": 1,
"hits": [
  {
    "_index": "my_index",
    "_type": "doc",
    "_id": "2",
    "_score": 1,
    "fields": {
      "test1": [
        "2015-2"
      ]
    }
  },
  {
    "_index": "my_index",
    "_type": "doc",
    "_id": "1",
    "_score": 1,
    "fields": {
      "test1": [
        "2015-1"
      ]
    }
  }
]
  }
}

Hope it helps.

Cheers,
LG


(yanianthe) #3

thanks a lot!


(system) #4

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.