Get last document from ElasticSearch Get last document from ElasticSearch elasticsearch elasticsearch

Get last document from ElasticSearch


Yes, you can simply request one single document (size: 1) and sorted by decreasing timestamp

POST index/_search{   "size": 1,   "sort": { "timestamp": "desc"},   "query": {      "match_all": {}   }}


Get last document from elasticsearch using java high-level REST client

The given solution is in Scala language:

import org.elasticsearch.action.search.{SearchRequest, SearchResponse}import org.elasticsearch.index.query.QueryBuildersimport org.elasticsearch.search.builder.SearchSourceBuilderimport org.elasticsearch.search.sort.SortOrderval searchRequest = new SearchRequest("index")val searchSourceBuilder = new SearchSourceBuilderval queryBuilder = QueryBuilders.boolQuery()queryBuilder.must(QueryBuilders.termQuery("field.keyword", "field value"))searchSourceBuilder.query(queryBuilder)                   .sort("timestamp", SortOrder.DESC)                   .size(1)searchRequest.source(searchSourceBuilder)val searchResponse = high_level_client.search(searchRequest)


A complete curl command would look something like this.Including security options reading user/password from netrc and using cacert.

curl -s \     --netrc-file ~/.netrc \     --cacert ~/ca/ca.crt \     -H 'Content-Type: application/json' \     'https://localhost:9200/logstash-*/_search?pretty' \     -XPOST \     -d '         {            "size": 1,            "sort": { "@timestamp": "desc"},            "query": {               "match_all": {}            }        }'

The POST request credits go to the answer from @Val

File locations and index names must of course be adapted to your use case. In addition you must know the name of the timestamp field you wish to sort on. It is usually @timestamp (with the @).