Elasticsearch查询以获取具有最近日期形式一个月的不同结果

时间:2016-12-09 04:14:55

标签: elasticsearch lucene kibana querydsl

我是ElasticSearch的新手。任何人都可以帮我找到查询。 我的弹性搜索中有以下记录

Name    Work         Time Stamp
--------------------------------------------
Steve,  eating,     2016-11-12 05:36:40
Steve,  sleeping,   2016-11-12 06:14:50
Steve,  going,      2016-11-12 07:21:22
Steve,  driving,    2016-11-12 08:20:10
Steve,  reading,    2016-11-12 09:24:30
James,  eating,     2016-11-12 11:36:40
James,  sleeping,   2016-11-12 05:14:50
James,  going,      2016-11-12 08:21:22
James,  driving,    2016-11-12 10:20:10
James,  reading,    2016-11-12 09:24:30
Crag,   sleeping,   2016-05-12 09:24:30

我需要以下数据

Name    Work        Time Stamp
-------------------------------------------
Steve,  reading,    2016-11-12 09:24:30
James,  eating,     2016-11-12 11:36:40

1 个答案:

答案 0 :(得分:0)

以正确的方式索引数据非常重要:

1)因为你想按日期排序,你必须“说”弹性特定字段是日期字段,所以你需要映射数据:

  PUT stack 
{
  "mappings": {
    "stack": {
      "properties": {
        "time": {
               "type": "date"
            }
      }
    }
  }
}

2)然后插入数据:

    POST /_bulk
{"index":{"_index":"stack","_type":"stack"}}
{"name":"Steve","work":"eating","Time":"2016-11-12"}
{"index":{"_index":"stack","_type":"stack"}}
{"name":"Steve","work":"sleeping","Time":"2016-11-13"}
{"index":{"_index":"stack","_type":"stack"}}
{"name":"James","work":"eating","Time":"2016-11-12"}
{"index":{"_index":"stack","_type":"stack"}}
{"name":"James","work":"sleeping","Time":"2016-05-15"}

3)然后搜索:

GET stack/_search
{
    "size": 0, 
    "aggs": {
        "top-tags": {
            "terms": {
                "field": "name",
                "size": 3
            },
            "aggs": {
                "top_tag_hits": {
                    "top_hits": {
                        "sort": [
                          { "Time":   { "order": "desc" }}
                        ],
                        "size" : 2
                    }
                }
            }
        }
    }
}