ElasticSearch如何查询最长的任务



我在Elastic Search中有以下格式的数据:

POST slots/slot/1
{
taskId:1,
datetime: "2020-05-10T08:45:44",
status: "START",
}
POST slots/slot/2
{
taskId:1,
datetime: "2020-05-10T08:49:54",
status: "STOP",
}
...

我想找到一种方法来检索前三个运行时间最长的任务(这意味着任务,它同时存在START和STOP-json对象,其START/STOP时间之间的差异是最长的(-我想检索taskId和runningTime(=任务运行的时间(。

有可能在ElasticSearch中完成这项任务吗?ElasticSearch适用于此类任务吗?

请宽容一点,我真的是ElasticSearch技术的新手。

这个很棘手。假设每个唯一的taskId都有精确的2个文档,其中一个是START,另一个为STOP。在这种情况下,我们可以做以下操作:

GET slots/_search
{
"size": 0,
"aggs": {
"by_ids": {
"terms": {
"field": "taskId",
"size": 10000,
"min_doc_count": 2
},
"aggs": {
"start_bucket": {
"filter": {
"term": {
"status.keyword": "START"
}
},
"aggs": {
"datetime_term": {
"max": {
"field": "datetime"
}
}
}
},
"stop_bucket": {
"filter": {
"term": {
"status.keyword": "STOP"
}
},
"aggs": {
"datetime_term": {
"max": {
"field": "datetime"
}
}
}
},
"diff_in_millis": {
"bucket_script": {
"buckets_path": {
"start": "start_bucket.datetime_term",
"stop": "stop_bucket.datetime_term"
},
"script": "return params.stop - params.start"
}
},
"final_sort": {
"bucket_sort": {
"sort": [
{
"diff_in_millis": {
"order": "desc"
}
}
],
"size": 3
}
}
}
}
}
}

根据本次讨论,

需要注意的是,这会对bucket的最终列表执行排序。因此,如果一个术语不在列表中,它就不会被排序。这与根据术语agg本身进行排序形成对比,后者会更改列表的内容。

换句话说,我们需要将顶级size设置为任意高,以便聚合所有taskIDs。和/或用一个只包含2020年或上个月的日期过滤器等来预过滤上下文,这样我们就可以减少需要覆盖的内容,并节省一些CPU紧张的时间。

如果一切顺利,并且您的status有一个.keyword字段(此处有更多信息(,我们可以对其进行筛选,那么您最终将获得所需的所有信息:

{
...
"aggregations":{
"by_ids":{
"doc_count_error_upper_bound":0,
"sum_other_doc_count":0,
"buckets":[
{
"key":2,            <-- taskID (this one was added by myself)
"doc_count":2,
"start_bucket":{
...
},
"stop_bucket":{
...
},
"diff_in_millis":{
"value":3850000.0        <-- duration in millis
}
},
{
"key":1,                  <-- task from the question
"doc_count":2,
"start_bucket":{
...
},
"stop_bucket":{
...
},
"diff_in_millis":{
"value":250000.0        <-- duration in millis
}
}
]
}
}
}

编辑/更正:

需要"min_doc_count": 2b/c我们只对实际完成的任务感兴趣。如果你想包括那些已经运行但尚未完成的任务,请创建另一个奖励任务;(

最新更新