so I have an elastic search index and I am sending docs to it attached with a timestamp. I am wondering if there is a way to extract the last document based on the time stamp. I.e. say to elastic give me the doc with the last time.
Thanks.
so I have an elastic search index and I am sending docs to it attached with a timestamp. I am wondering if there is a way to extract the last document based on the time stamp. I.e. say to elastic give me the doc with the last time.
Thanks.
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.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)
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 @
).
You can also make a call with the requested information as parameters:
POST /index/_search?size=1&sort=timestamp:desc