I would like to return the most recent record (top 1) from ElasticSearch index similar to the sql query below;
SELECT TOP 1 Id, name, title FROM MyTable ORDER BY Date DESC;
Can this be done?
You can use the search API to search and aggregate data stored in Elasticsearch data streams or indices. The API's query request body parameter accepts queries written in Query DSL. The following request searches my-index-000001 using a match query. This query matches documents with a user.id value of kimchy .
If a search request results in more than ten hits, ElasticSearch will, by default, only return the first ten hits. To override that default value in order to retrieve more or fewer hits, we can add a size parameter to the search request body.
Elasticsearch uses search relevance to score documents of a dataset. It returns an ordered list of data sorted by a relevance score. We can customize the score by adding and modifying variables that will shift the scale between precision and recall.
Do you have _timestamp enabled in your doc mapping?
{ "doctype": { "_timestamp": { "enabled": "true", "store": "yes" }, "properties": { ... } } }
You can check your mapping here:
http://localhost:9200/_all/_mapping
If so I think this might work to get most recent:
{ "query": { "match_all": {} }, "size": 1, "sort": [ { "_timestamp": { "order": "desc" } } ] }
For information purpose, _timestamp is now deprecated since 2.0.0-beta2. Use date
type in your mapping.
A simple date mapping JSON from date
datatype doc:
{ "mappings": { "my_type": { "properties": { "date": { "type": "date" } } } } }
You can also add a format
field in date
:
{ "mappings": { "my_type": { "properties": { "date": { "type": "date", "format": "yyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" } } } } }
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