python:解析elasticsearch json outpu

2024-09-30 08:37:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析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数据中只提取image参数并将其存储为数组。我尝试了以下方法:

^{pr2}$

还有这个:

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

我敢肯定之前这里也有类似的问题,但我无法克服这个错误。有人能帮忙吗?在


Tags: 数据imageidjsonsourceindextype错误
2条回答

要获取条目中的所有图像,可以使用list comprehension

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

输出:

^{pr2}$

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

相关问题 更多 >

    热门问题