簡體   English   中英

在 Python 中解析 Elasticsearch json 輸出

[英]Parsing Elasticsearch json output in 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 數據中提取圖像參數並將其存儲為數組。 我嘗試了以下內容:

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

我確信這里早些時候提出了類似的問題,但我無法解決這個錯誤。 我該如何解決?

您可以使用 PyPi 中的Elasticsearch-DSL包,而不是經歷手動處理響應的痛苦。

要將_source條目中的所有圖像作為列表獲取,您可以使用列表理解

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

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM