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.
Check out Elastic’s documentation for a complete list of all the Elasticsearch Clients. Use GET requests, the Get API, and the _search API to query documents in an Elasticsearch index.
The document may didn’t exist when you checked it, but maybe someone will kick off reindex or index that particular document. So from this tutorial you can learn whether some document exist or not in Elasticsearch.
You can use the version parameter to retrieve the document only if its current version is equal to the specified one. Internally, Elasticsearch has marked the old document as deleted and added an entirely new document. The old version of the document doesn’t disappear immediately, although you won’t be able to access it.
Retrieves the specified JSON document from an index. If the Elasticsearch security features are enabled, you must have the read index privilege for the target index or index alias. You use GET to retrieve a document and its source or stored fields from a particular index. Use HEAD to verify that a document exists.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With