如何获取按字段分组的最新文档?

时间:2016-07-19 18:58:20

标签: elasticsearch

我有一个index,其中包含许多documents格式:

{
    "userId": 1234,
    "locationDate" "2016-07-19T19:24:51+0000",
    "location": {
        "lat": -47.38163,
        "lon": 26.38916
    }
}

在这个索引中,我有来自用户的增量位置,每隔几秒更新一次。

我想执行一个搜索,它会返回每个用户的最新位置(按locationDate排序)(按userId分组)

弹性搜索可以实现吗?我能做的最好的事情就是从最后30秒获得所有位置,使用:

{"query":{
  "filtered" : {
    "query" : {
      "match_all" : { }
    },
    "filter" : {
      "range" : {
        "locationDate" : {
          "from" : "2016-07-19T18:54:51+0000",
          "to" : null,
          "include_lower" : true,
          "include_upper" : true
        }
      }
    }
  }
}}

之后我用手将它们整理出来,但我想直接在弹性搜索上进行此操作

重要提示:我正在使用elasticsearch 1.5.2

1 个答案:

答案 0 :(得分:1)

试试这个(使用聚合):

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "range": {
          "locationDate": {
            "from": "2016-07-19T18:54:51+0000",
            "to": null,
            "include_lower": true,
            "include_upper": true
          }
        }
      }
    }
  },
  "aggs": {
    "byUser": {
      "terms": {
        "field": "userId",
        "size": 10
      },
      "aggs": {
        "firstOne": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "locationDate": {
                  "order": "desc"
                }
              }
            ]
          }
        }
      }
    }
  }
}