【问题标题】:Add item on dict at specific depth在特定深度的 dict 上添加项目
【发布时间】:2020-01-14 16:59:38
【问题描述】:

我正在使用 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中实现这个数据结构,第二段代码呢?为每个聚合项放入一个新叶子。

谢谢

【问题讨论】:

    标签: python list dictionary elasticsearch recursion


    【解决方案1】:

    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'}}}}]
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多