【问题标题】:Select average time between two properties in elasticsearch index选择弹性搜索索引中两个属性之间的平均时间
【发布时间】:2020-10-09 18:04:50
【问题描述】:

给定一个包含两个日期字段的弹性搜索索引,我如何查询这两个日期之间的平均时间?

{
    "mappings": {
        "properties": {
            "dateInserted": {
                "type": "date",
                "format": "dateOptionalTime"
            },
            "dateUpdated": {
                "type": "date",
                "format": "dateOptionalTime"
            }
        }
    }
}
[
    {
        "dateInserted": "2020-10-01 00:00:00",
        "dateUpdated": "2020-10-01 01:00:00"
    }, {
        "dateInserted": "2020-10-01 02:00:00",
        "dateUpdated": "2020-10-01 04:00:00"
    }
]

文档 A 的间隔为一小时,文档 B 的间隔为两小时,因此预期结果为 1.5 小时。

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    avg aggregation 脚本应该没问题:

    {
      "size": 0,
      "aggs": {
        "avg_duration": {
          "avg": {
            "script": {
              "source": """
                def duration = doc.dateUpdated.value.getMillis() - doc.dateInserted.value.getMillis();
                return duration / (float) (1000*60*60)
              """
            }
          }
        }
      }
    }
    

    或者,更紧凑:

    {
     ...
     "source": "def duration = doc.dateUpdated.value.getMillis() - doc.dateInserted.value.getMillis(); return duration / (float) (1000*60*60)"
     ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 2019-11-13
      • 2018-05-12
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多