遍历Elasticsearch脚本中字段上的对象项列表

时间:2018-12-26 13:43:04

标签: python elasticsearch

我在Elasticsearch文档中有一个对象列表。每个对象都有一个日期字段。我想计算两个对象日期值之间的最小差。

我的Elasticsearch版本是6.5

input example ex:
{
    'activity':
            [
          {
             date:'2018-01-01',
             task:'meeting'
          },
          {
             date:'2018-01-15',
             task:'conference'
          },
          {
             date:'2018-01-27',
             task:'meeting'
          },
          {
             date:'2018-02-01',
             task:'party'
          }
        ]
}

我已经尝试了这两种映射,但是都无法正常工作。

Mappping 1
{
  "activity" : {
    "properties" : {
      "date" : {
        "type" : "date",
      },
      "task" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
      }
    }
  },
}

Mappping 2
o
{
"activity": {
    "type": "nested",
    "properties": {
        "date": {
            "type": "date"
        },
        "task": {
            "type": "text",
            "fields": {
                "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                }
            }
        }
    }
}

}

代码是:-

this code return minimum difference between two dates

    "script_fields" : { 
        "min_no_of_days" : {
            "script" : {
                "lang": "painless",
                "inline": "int min_days = -1; 
                     for (i=1, i<=ctx._source['activity'].length; i++) 
                        {
                            days_diff = ctx._source['activity'][i].date - ctx._source['activity'][i-1].date;
                            if (min_days == -1 || min_days < days_diff){min_days =days_diff;}
                        }
                     return min_days; "
            }
        }
    }

上面的脚本将在所有记录的每个文档上运行,并返回每个文档的最小天数差。 我什至试图返回活动字段的长度,但没有成功

我希望这是结果

{
    "min_no_of_days":5
}

0 个答案:

没有答案