如何通过<field>获取最旧的条目

时间:2016-07-04 14:09:04

标签: elasticsearch

对于以下事件:

{
    "time": 10,
    "name": "John",
    "status": true 
},
{
    "time": 20,
    "name": "John",
    "status": false
},
{
    "time": 20,
    "name": "Mary",
    "status": false
},
{
    "time": 10,
    "name": "Mary",
    "status": true
}

对于给定的time,搜索最早的那些(字段name (1))的正确方法是什么?

对于上面的例子,这意味着

{
    "time": 20,
    "name": "John",
    "status": false
},
{
    "time": 20,
    "name": "Mary",
    "status": false
},

我尝试使用order in aggregations,按照

的方式
{
  "query": {
    "match_all": {

    }
  },
  "aggs": {
    "shortlist": {
      "terms": {
        "field": "name",
        "size": 1,
        "order" : { "time" : "asc" }
      }
    }
  }
}

但是我得到了

"error": {
      "root_cause": [
         {
            "type": "aggregation_execution_exception",
            "reason": "Invalid term-aggregator order path [time]. Unknown aggregation [time]"
         }
坦率地说,我不明白。

(1)这实际上是一个纪元时间戳,但为了简单起见,我使用了一个简短的int

1 个答案:

答案 0 :(得分:4)

这样的事情应该这样做:

{
  "size": 0,
  "aggs": {
    "by_name": {
      "terms": {
        "field": "name",
        "size": 10
      },
      "aggs": {
        "top1": {
          "top_hits": {
            "size": 1,
            "sort": [{"time":{"order": "desc"}}]
          }
        }
      }
    }
  }
}