我正在与Elasticsearch一起使用,我需要构建一个类似于JSON的字典对象以查询复杂的聚集。
每个聚集都具有以下格式:
{
"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中实现此数据结构,第二段代码?在dict中为每个聚合项添加新的叶子。
谢谢
最佳答案
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'}}}}]
关于python - 在特定深度的字典上添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59738479/