如何在python中打印elasticsearch的查询结果?

2024-05-14 03:30:53 发布

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

以下查询给出了我的文档在elasticsearch中的词汇量大小:

GET my_index/my_type/_search
{
  "size": 0, 
  "aggs": {
     "vocab": {
        "cardinality": {
           "field": "text"}}}}

输出为:

^{pr2}$

现在我想在python中打印字段“value”(=178050)的值。在

我用python写了以下内容:

query_body={
  "size": 0, 
  "aggs": {
     "vocab": {
        "cardinality": {
           "field": "text"}}}}

res = es.search(index = INDEX_NAME, body=query_body)

如何打印该值?谢谢。在


Tags: text文档fieldsearchsizegetindexmy
2条回答

这是你想要的吗?。 在python中,我们可以通过键得到值。在

从您的输出:

output = {
"took": 0,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 84678,
"max_score": 0,
"hits": []
},
"aggregations": {
"vocab": {
"value": 178050**
  }
 }
}

print (output["aggregations"]["vocab"]["value"]) # It will print the value or use output.get("aggregations").get("vocab").get("value")
178050

假设您的结果字典如下所示:

{
    "took": 0,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "failed": 0
    },
    "hits": {
        "total": 84678,
        "max_score": 0,
        "hits": []
    },
    "aggregations": {
        "vocab": {
            "value": 178050
        }
    }
}

您可以像@mohammedyasin推荐的那样访问结果:

^{pr2}$

如果resstr,则可以使用json.loads将其转换为字典

import json
res = json.loads(s)
value = res['aggregations']['vocab']['value']

相关问题 更多 >