首页 > 解决方案 > 无法使用 python 从 Kibana 读取聚合数据

问题描述

因此,我正在处理 kibana 航班示例数据,我的第一个语句范围包括一个 if 语句,该语句在我所做的 DSL 查询搜索的结果中查找 hits 标签,它位于此代码之上,与此无关因为我想尽可能地减少这个。然后它抓取其中的信息,然后我告诉在第二个匹配项中查看也包含 _source 的信息,并打印其中的信息长度。如果它包含有关 Dest 的任何信息,请为我抓取并展示给我。这很好用,因为我还导出了下面的结果。

我的问题在第二个陈述范围内,当我在逻辑上应用相同的事情时,我似乎无法做同样的事情。聚合数据的结果看起来有点不同,但差别不大,只是括号中的括号,我正在尝试获取其中的信息。

我的第二个 if 语句的错误如下

    if "hits" in r["hits"]:
        print (len(r["hits"]["hits"]))
        for item in r["hits"]["hits"]:
            if "_source" in item:
                if "Dest" in item["_source"]:
                    print(item["_source"]["Dest"])

    if "aggregations" in r:
        print (len(r["aggregations"]["shabz"]))
        for item in r["aggregations"]["shabz"]:
            if "buckets" in item:
                print(item["buckets"]["key"])

if __name__== "__main__":
    get_data_from_es()

结果

python3 read_example2.py 

10
Manchester Airport
London Gatwick Airport
Manchester Airport
London Luton Airport
London Gatwick Airport
Manchester Airport
London Gatwick Airport
London Luton Airport
London Heathrow Airport
London Luton Airport
3
Traceback (most recent call last):
  File "read_example2.py", line 71, in <module>
    get_data_from_es()
  File "read_example2.py", line 68, in get_data_from_es
    print(item["buckets"]["key"])
TypeError: string indices must be integers

我正在尝试从这部分结果中获取数据

"aggregations" : {
    "shabz" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 19,
      "buckets" : [
        {
          "key" : "IT",
          "doc_count" : 10
        },
        {
          "key" : "GB",
          "doc_count" : 8

我可以从 Kibana 的控制台中看到这一点,所以通过我的 if 语句,我实际上是在尝试获取信息,告诉我有多少个键以及其中的内容,例如 IT、GB 等.

如果您在结果中查找 3,那 3 基本上是“shabz”中的 3 个信息字符串

为什么 if 语句和 for 循环不遍历我不知道的其余信息:(

标签: pythonelasticsearchkibanaaggregation

解决方案


推荐阅读