Get last document from ElasticSearch
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.QueryBuilders
import org.elasticsearch.search.builder.SearchSourceBuilder
import org.elasticsearch.search.sort.SortOrder
val searchRequest = new SearchRequest("index")
val searchSourceBuilder = new SearchSourceBuilder
val 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)
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": {}
}
}