首页 > 解决方案 > 在特定深度的 dict 上添加项目

问题描述

我正在使用 Elasticsearch,我需要构建一个类似 JSON 的 dict 对象来查询复杂的聚合。

每个聚合都具有以下格式:

{
"aggs": {
    "agg_by_field_1": {
        "terms": {
            "script": {
                "source": "whatever"
                }
            }
         }
    }
}

但是每个聚合也有一个带有下一个聚合的叶子:

{
"aggs": {
    "agg_by_field_1": {
        "terms": {
            "script": {
                "source": "whatever"
            }
        },
        "aggs": {
            "agg_by_field_2": {
                "terms": {
                    "script": {
                        "source": "whatever_2"
                        }
                    }
                 }
            }
         }
    }
}

现在我对list每个聚合都有一个简单的了解:

[
    {
        "agg_by_field_1": {
            "terms": {
                "script": {
                    "source": "whatever"
                }
            }
        }
    },
    {
        "agg_by_field_2": {
            "terms": {
                "script": {
                    "source": "whatever_2"
                }
            }
        }
    },
]

那么,我怎样才能在python中实现这个数据结构,第二段代码呢?为每个聚合项放入一个新叶子。

谢谢

标签: pythonlistdictionaryelasticsearchrecursion

解决方案


Python 开箱即用地支持这种结构。这称为嵌套Dictionary. 您可以在此处阅读更多相关信息:https ://www.programiz.com/python-programming/nested-dictionary

事实上,您的代码无需更改任何内容即可正常工作:

>>> d = {
... "aggs": {
...     "agg_by_field_1": {
...         "terms": {
...             "script": {
...                 "source": "whatever"
...             }
...         },
...         "aggs": {
...             "agg_by_field_2": {
...                 "terms": {
...                     "script": {
...                         "source": "whatever_2"
...                         }
...                     }
...                  }
...             }
...          }
...     }
... }
>>> d
{'aggs': {'agg_by_field_1': {'terms': {'script': {'source': 'whatever'}}, 'aggs': {'agg_by_field_2': {'terms': {'script': {'source': 'whatever_2'}}}}}}}
>>> d = [
    {
        "agg_by_field_1": {
            "terms": {
                "script": {
                    "source": "whatever"
                }
            }
        }
    },
    {
        "agg_by_field_2": {
            "terms": {
                "script": {
                    "source": "whatever_2"
                }
            }
        }
    },
]
>>> d
[{'agg_by_field_1': {'terms': {'script': {'source': 'whatever'}}}}, {'agg_by_field_2': {'terms': {'script': {'source': 'whatever_2'}}}}]


推荐阅读