Search code examples
elasticsearchelasticsearch-py

Max value of field using Elasticsearch Python API


I'm trying to get the max value of a field "UID" from Elasticsearch using its Python API. When I try it using the below code I get an error.

res = es.search(index="some_index", body={"query": {"size": 0,
"aggregations": {
"maxuid": {
  "max": {
    "field": "UID"
  }}}}})
print(res) 

elasticsearch.exceptions.RequestError: TransportError(400, u'parsing_exception', u'no [query] registered for [aggregations]')

I have a curl command for the same request which works, but when I use query in the body for the Python API it raises the above error.

This is the curl request which works and gives me the expected results. How to use this in the Elasticsearch Python API is the problem I'm facing.

GET some_index/some_doc/_search{
"size": 0,
"aggregations": {
"maxuid": {
"max": {
"field": "UID"
}}}}

Any help on this is greatly appreciated. Thanks.


Solution

  • Something like this would work:

    res = es.search(
          index="some_index", 
           body={
            "aggs": {
              "maxuid": {
                "max": { "field": "UID"}
              }
           }
        }
    )
    print(res)
    

    You can't specify aggregations inside query clause, aggregations and query are two different clauses and that's the reason you're getting that exception.

    A rough structure looks like this:

    res = es.search(
           index="some_index", 
           body={
            "query": {},
            "size": 0,
            "aggs": {
              "maxuid": {
                "max": { "field": "UID"}
              }
            }
        }
    )
    

    I haven't run the request so you might have to tweak it a bit.

    PS: I am not a python guy :)