嵌套字段上按日期排序的聚合

gorkyyrv  于 2021-06-15  发布在  ElasticSearch
关注(0)|答案(1)|浏览(282)

我正在开发一个查询,其中我计算最近的文档包含多少个唯一的“cp”。json由几个嵌套字段组成。当我添加到带有嵌套字段的json时,我很难只显示带有最近日期的json值。我已经完成了嵌套聚合,最后我使用top\u hits filter按降序排序,它会返回大小的最后一个。但它仍在归还所有日期不同的文件。
json码:

"data" : [
        {
          "addresses" : [
            {
              "cp" : "33.33.33",
              "services" : [
                {
                  "field1" : "true",
                  "field2" : "1234",
                }
              ]
            }
          ],
        }
      ],
      "created_at" : "2020-09-03 14:39:01",
      "@timestamp" : "2020-09-04T05:53:22.341661Z",
    }
  },

查询:

{"size": 0, 
  "aggs": {
    "nested": {
      "nested": {
        "path": "data.addresses"

          },
          "aggs": {
            "nested": {
              "nested": {
                "path": "data.addresses.services"
              },
              "aggs": {
                "filter": {
                  "filter": {
                    "term": {
                      "data.addresses.services.field1.keyword": "true"
                    }
                  },
                  "aggs": {
                    "unique": {
                      "cardinality": {
                        "field": "data.addresses.services.field2.keyword"
                      }
                    },
                    "range":{
                      "top_hits": {
                        "size": 1,
                        "sort": [
                          {"created_at.keyword": {"order": "desc"}}]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

我尝试过按预定义字段“created\u at”或@timestamp排序,但结果是一样的。有什么建议能帮助我解决问题吗?

neskvpey

neskvpey1#

对于这种情况,解决方法是添加

"order": {
          "_key": "desc":

而不是最热门的。
查询

{"size": 0, 
  "aggs": {
    "filtrofecha": {
      "terms": {
        "field": "created_at.keyword",
        "order": {
          "_key": "desc"
        },
        "size": 1
      },
      "aggs": {
        "nested": {
          "nested": {
            "path": "data.addresses"
              },
              "aggs": {
                "nested": {
                  "nested": {
                    "path": "data.addresses.services"
                  },
                  "aggs": {
                    "filter": {
                      "filter": {
                        "term": {
                          "data.addresses.services.field1.keyword": "true"
                        }
                      },
                      "aggs": {
                        "unique": {
                          "cardinality": {
                            "field": "data.addresses.services.field2.keyword"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

相关问题