Elasticsearch tips and tricks

  1. Find record having max value for a field
  2. Get latest record from Elasticsearch
  3. Latest record with ES _timestamp value in results
  4. Get record count from last x mins

Max value

GET http://elasticsearch-server:9200/my_index_name_*/_search?size=0
{
    "aggs" : {
        "max_timestamp" : { "max" : { "field" : "TimeStamp" } }
    }
}
# replace TimeStamp to any other named field for which we want to fetch the max

 

Latest record from ES

GET http://elasticsearch-server:9200/my_index_name_*/_search
{
  "query": {
    "match_all": {}
  },
  "size": 1,
  "sort": [
    {
      "_timestamp": {
        "order": "desc"
      }
    }
  ]
}

Latest record with ES _timestamp value in results

GET http://elasticsearch-server:9200/my_index_name_*/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
        "timestamp": {
            "script": "_doc['_timestamp'].value"
        }
    },
  "size": 1,
  "sort": [
    {
      "_timestamp": {
        "order": "desc"
      }
    }
  ]
}

Get record count from last x mins

curl -XGET 'elastic-hostname.tld:9200/indexPattern-*/log/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "query": {
        "range" : {
            "keyContainingDateTime" : {
                "gte" : "now-2m",
                "lt" :  "now"
            }
        }
    }
}

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *