使用时间过滤搜索结果

时间:2018-05-24 08:50:33

标签: elasticsearch filter

考虑索引中的弹性搜索文档" order / orders"代表事件的不同阶段

{"order_id": 10001, "order_status": "New",       "time": 20180524101505}
{"order_id": 10002, "order_status": "New",       "time": 20180524101505}
{"order_id": 10001, "order_status": "Paid",      "time": 20180524102505}
{"order_id": 10002, "order_status": "Cancelled", "time": 20180524111505}
{"order_id": 10001, "order_status": "shipped",   "time": 20180525082505}
{"order_id": 10003, "order_status": "New",       "time": 20180525101505}
{"order_id": 10001, "order_status": "Delivered", "time": 20180526082505}
{"order_id": 10001, "order_status": "Closed",    "time": 20180526082605}

如何进行搜索,其结果将是该事件的最新阶段。基本上我需要做的是根据"时间"进行排序。并获得个人结果

{"order_id": 10002, "order_status": "Cancelled", "time": 20180524111505}
{"order_id": 10001, "order_status": "Closed",    "time": 20180526082605}
{"order_id": 10003, "order_status": "New",       "time": 20180525101505}

2 个答案:

答案 0 :(得分:2)

我建议使用max聚合,而不是使用top_hits聚合,因为您需要检索每个订单的最新文档:

{
  "aggs": {
    "byOrderId": {
      "terms": {
        "field": "order_id"
      },
      "aggs": {
        "latest": {
          "top_hits": {
            "sort": {"time": "desc"},
            "size": 1
          }
        }
      }
    }
  }
}

答案 1 :(得分:0)

您需要orderId使用VB Attributes - What are they and why should we use them (ChristopherMcClellan)进行汇总,然后使用terms-aggregation进行子汇总

这里的例子是:

{
  "aggs": {
    "byOrderId": {
      "terms": {
        "field": "order_id"
      },
      "aggs": {
        "maxTime": {
          "max": {
            "field": "time"
          }
        }
      }
    }
  }
}