【问题标题】:Parsing Elasticsearch json output in Python在 Python 中解析 Elasticsearch json 输出
【发布时间】:2019-05-18 02:17:01
【问题描述】:

我正在从 Elasticsearch 索引中解析数据,并收到了 json 格式的数据,如下所示:

{
    "_shards": {
        "failed": 0,
        "skipped": 0,
        "successful": 5,
        "total": 5
    },
    "hits": {
        "hits": [
            {
                "_id": "wAv4u2cB9qH5eo0Slo9O",
                "_index": "homesecmum",
                "_score": 1.0870113,
                "_source": {
                    "image": "0000000028037c08_1544283640.314629.jpg"
                },
                "_type": "dataRecord"
            },
            {
                "_id": "wwv4u2cB9qH5eo0SmY8e",
                "_index": "homesecmum",
                "_score": 1.0870113,
                "_source": {
                    "image": "0000000028037c08_1544283642.963721.jpg"
                },
                "_type": "dataRecord"
            },
            {
                "_id": "wgv4u2cB9qH5eo0SmI8Z",
                "_index": "homesecmum",
                "_score": 1.074108,
                "_source": {
                    "image": "0000000028037c08_1544283640.629583.jpg"
                },
                "_type": "dataRecord"
            }
        ],
        "max_score": 1.0870113,
        "total": 5
    },
    "timed_out": false,
    "took": 11
}

我正在尝试仅从 json 数据中提取图像参数并将其存储为数组。我尝试了以下方法:

for result in res['hits']['hits']:
    post = result['_source']['image']
    print(post)

还有这个:

respars = json.loads(res['hits']['hits'][0]['_source'])['image']
print(json.dumps(respars, indent=4, sort_keys = True))

这两个都会引发错误:

TypeError: byte indices must be integers or slices, not str

我确信之前在这里提出了类似的问题,但我无法解决这个错误。我该如何解决?

【问题讨论】:

标签: python json elasticsearch


【解决方案1】:

您可以使用 PyPi 的 Elasticsearch-DSL 包,而不是手动处理响应的痛苦。

【讨论】:

  • 谢谢...这个包直接帮助我解析了数据。
【解决方案2】:

要获取_source条目中的所有图像作为列表,您可以使用list comprehension

image_list = [source['_source']['image'] for source in res['hits']['hits']]

输出:

['0000000028037c08_1544283640.314629.jpg',
 '0000000028037c08_1544283642.963721.jpg',
 '0000000028037c08_1544283640.629583.jpg']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2022-07-21
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多