1

Following query gives the vocabulary size of my document in elasticsearch:

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

The output is:

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

Now I want to print the value of the field "value"(=178050) in python.

I wrote the following in python:

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

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

How can I print that value? Thanks.

0

2 Answers 2

1

Given that your result dictionary looks like this:

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

You can access the result like @mohammedyasin recommended:

res['aggregations']['vocab']['value']

if res is a str, you can convert it to a dictionary using json.loads

import json
res = json.loads(s)
value = res['aggregations']['vocab']['value']
Sign up to request clarification or add additional context in comments.

1 Comment

Please upvote/mark as answered if the answer helped.
1

This is you expecting?. In python we can get the value from dict by key.

from your output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.