Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the most recent record from ElasticSearch index

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?

like image 659
Yasir Avatar asked Dec 21 '13 20:12

Yasir


People also ask

How do I get Elasticsearch index data?

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 .

How do I get more than 10 results in Elasticsearch?

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.

What is Elasticsearch relevance score?

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.


2 Answers

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"       }     }   ] } 
like image 191
mconlin Avatar answered Sep 17 '22 07:09

mconlin


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"         }       }     }   } } 
like image 41
Adrien Chaussende Avatar answered Sep 21 '22 07:09

Adrien Chaussende