【问题标题】:How do I sort a top hit in a nested aggregate by a field in the root document?如何按根文档中的字段对嵌套聚合中的热门命中进行排序?
【发布时间】:2017-02-26 20:44:40
【问题描述】:

我正在嵌套聚合中执行热门聚合。我希望通过根文档中的时间戳字段来排序最高命中,以便获得嵌套文档的最新版本(可能被索引到多个根文档中)。虽然语法似乎让我这样做,但提取的排序键似乎是“垃圾”;每个文档的数量都相同。 (以下只是一个更复杂的聚合的 sn-p - 否则,该方法可能没有意义 - 但它具有我的问题的本质。)

{
   "size": 0,
   "aggs": {
      "nested_doc": {
         "nested": {
            "path": "nested_doc"
         },
         "aggs": {
            "most_recent": {
               "top_hits": {
                  "sort": "_index_time"
               }
            }
         }
      }
   }
}

在我的结果中,排序键与任何这样的“_index_time”都不匹配,并且更改排序顺序没有效果。 “_index_time”在根文档中被声明为整数。如果我将查询中的“_index_time”更改为一些无意义的字符串,查询会出错,所以我知道我的要求是有意义的,但它没有执行排序——或者,至少,它没有正确要排序的数据。

如何正确排序根属性上的嵌套聚合?

或者,我尝试将 copy_to: 'nested_doc._index_time' 添加到 '_index_time' 声明中,虽然这让我可以指定 'nested_doc._index_time' 作为排序键,但它仍然导致无意义的排序键。字段是否定义不正确?

    _index_time: { type: 'integer'},

【问题讨论】:

    标签: elasticsearch aggregation elasticsearch-aggregation


    【解决方案1】:

    我遇到了同样的问题,然后我在嵌套聚合中提供了一种解决方案。在此我们可以在index_time 上添加一个最大聚合的并行聚合。然后根据您添加的最大聚合对其进行排序。 您只需要根据您在第一级的聚合调整order 语句即可。

    请查看以下查询:

    {
       "size": 0,
       "aggs": {
          "nested_doc": {
             "nested": {
                "path": "nested_doc"
             },
             "order": {
                "max_date": "asc"
             }
             "aggs": {
                "most_recent": {
                   "top_hits": {
                      "sort": "_index_time"
                   }
                },
                "max_date": {
                     "max": {
                        "field": "_index_time"
                     }
                 }
    
             }
          }
       }
    }
    

    希望这能解决您的问题。

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2019-08-31
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多