Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last document from ElasticSearch

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.

like image 869
ScipioAfricanus Avatar asked Jun 27 '16 20:06

ScipioAfricanus


People also ask

How do I query documents in an Elasticsearch index?

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.

Does document exist or not in Elasticsearch?

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.

How to retrieve a deleted document 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.

How do I retrieve JSON from an index in Elasticsearch?

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.


2 Answers

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": {}
   }
}
like image 80
Val Avatar answered Sep 17 '22 22:09

Val


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)
like image 41
Keshav Lodhi Avatar answered Sep 20 '22 22:09

Keshav Lodhi