How to query for most recent entry?


(Jeremy Page) #1

Sorry if this is a dumb question, we're using ES for lots of different things across our environment. I am the infrastructure guy and one of the things I am tasked with is monitoring functionality. What I would like to know is:

How do I query for the timestamp of the most recent entry for a specific type - for instance we're reading STOMP auditing messages from our message queue servers into a _type=mq-message. How do I query either for the most recent entries timestamp or just query for X in the last 5 min.

I am trying the following but I am failing...

  curl -XGET http://localhost:9200/logstash-2015.05.14/_search 
 {
    "query": {
        "filtered": {
            "query": {
                "match_all": {}
            },
            "filter": {
                "term": {
                    "_type": "mq-message"
                }
            },
            "range": {
                "timestamp": {
                    "gt": "now-1h"
                }
            }
        }
    }
}

It says "ElasticsearchParseException[Expected field name but got START_OBJECT "range"


(Colin Goodheart-Smithe) #2

You need to put the range within the filter block. because you will then have multiple clauses in your filter object you will need to combine them using a bool query. Try doing the following:

curl -XGET http://localhost:9200/logstash-2015.05.14/_search
{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "bool": {
          "should": [
            {
              "term": {
                "_type": "mq-message"
              }
            },
            {
              "range": {
                "timestamp": {
                  "gt": "now-1h"
                }
              }
            }
          ]
        }
      }
    }
  }
}

Note that you can also filter the search to a specific type in the URL so the above is equivalent to:

curl -XGET http://localhost:9200/logstash-2015.05.14/mq-message/_search
{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "range": {
          "timestamp": {
            "gt": "now-1h"
          }
        }
      }
    }
  }
}

Hope that helps.


(Jeremy Page) #3

Fantastic, thanks!


(system) #5