Date 查询精确范围内的最长日期并在结果中获取所选字段
我是弹性搜索的新手,在查询中使用多个过滤器(特别是带有“max”)时,我面临一些问题 我目前正在开发一个由弹性搜索索引的大型数据库。 有很多文档,每个文档都是关于一个特定服务器的所有信息 这些服务器上偶尔会运行一个软件,用更新的信息创建一个新文档 因此,信息的存储方式如下:Date 查询精确范围内的最长日期并在结果中获取所选字段,date,elasticsearch,max,filtering,aggregate,Date,elasticsearch,Max,Filtering,Aggregate,我是弹性搜索的新手,在查询中使用多个过滤器(特别是带有“max”)时,我面临一些问题 我目前正在开发一个由弹性搜索索引的大型数据库。 有很多文档,每个文档都是关于一个特定服务器的所有信息 这些服务器上偶尔会运行一个软件,用更新的信息创建一个新文档 因此,信息的存储方式如下: Id : item1 ITDiscovery_Date : 29/03/2016 Information1 : ... Information2 : ... Id : item1 ITDiscovery_Date : 12
Id : item1
ITDiscovery_Date : 29/03/2016
Information1 : ...
Information2 : ...
Id : item1
ITDiscovery_Date : 12/03/2016
Information1 : ...
Information2 : ...
Id : item2
ITDiscovery_Date : 16/02/2016
Information1 : ...
Information2 : ...
Id : item2
ITDiscovery_Date : 27/01/2016
Information1 : ...
Information2 : ...
等等
我的问题如下:
我正在尝试获取有关某个特定服务器的最新信息。为此,我想首先筛选服务器的名称(例如item456),然后获取特定日期范围内(例如从2015年1月1日到今天)此服务器的所有文档,然后筛选最长日期,以便获取最新信息,并在结果中获取所选字段(例如Information15、Information28和Information68)
我尝试了一些不同的请求,但无法实现,例如:
{
"fields": [
"Information15",
"Information28",
"Information68"
],
"query": {
"match": {
"Id": "item456"
}
},
"aggs": {
"date_range": {
"filter": {
"range": {
"ITDiscovery_Date": {
"gte": 1420066800000,
"lte": 1459241770000
}
}
},
"aggs": {
"max_date": {
"max": {
"field": "ITDiscovery_Date"
}
}
}
}
}
}
它返回所选日期范围内的所有文档,而不仅仅是具有最长日期的文档:
{
"took" : 34,
"timed_out" : false,
"_shards" : {
"total" : 982,
"successful" : 982,
"failed" : 0
},
"hits" : {
"total" : 33,
"max_score" : 15.364556,
"hits" : [ {
"_index" : "itdiscovery_2016.03.02",
"_type" : "default",
"_id" : "item456",
"_score" : 15.364556,
"fields" : {
"Information15" : [ "XXX" ],
"Information28" : [ "XXX" ],
"Information68" : [ "XXX" ]
}
}, {
"_index" : "itdiscovery_2016.03.23",
"_type" : "default",
"_id" : "item456",
"_score" : 15.359651,
"fields" : {
"Information15" : [ "XXX" ],
"Information28" : [ "XXX" ],
"Information68" : [ "XXX" ]
}
} ]
}, {
...
},
"aggregations" : {
"date_range" : {
"doc_count" : 33,
"max_date" : {
"value" : 1.45922382E12
}
}
}
}
我终于找到了(暂时的)解决办法
我使用过滤查询来获取指定日期范围内的结果。
然后在ITU日期使用sort,并将结果限制为1。
它获得了预期的最新结果
例如:
{
"fields": [
"Information15",
"Information28",
"Information68"
],
"sort": [
{ "ITDiscovery.Date.raw": {"order": "desc", "ignore_unmapped" : true}}
],
"size": 1,
"query": {
"filtered": {
"query": {
"query_string": {
"query": "Id: item456",
"analyze_wildcard": true
}
},
"filter": {
"bool": {
"must": [
{
"range": {
"ITDiscovery.Date": {
"gte": 1420070400000,
"lte": 1459241770000
}
}
}
],
"must_not": []
}
}
}
}
}