Elasticsearch-dsl sort, find last X entries
Asked Answered
U

3

5

I'm trying to find the last 30 entries into my index/doc type

I've tried nothing and I'm all out of ideas!

My current approach I find all the results over the last 5 minutes, then filter through the results and grab out the last 30 entries, but this is slower than the correct approach.

s = Search(using=es, index="history", doc_type=p)
   .filter('range', timestamp={'gte': mins})
   .extra(size=1000)

And I've tried

s = Search(using=es, index="history", doc_type=p)
   .sort("timestamp", {'order': "desc"})
   .extra(size=30)
Unwished answered 13/3, 2017 at 7:22 Comment(0)
P
4

the proper way to sort on timestamp in descending order is either s = s.sort('-timestamp') or s = s.sort({"price" : {"order" : "desc"}}).

You were specifying your sort incorrectly.

Pappano answered 16/3, 2017 at 6:52 Comment(1)
Is there a typo in the second option? s = s.sort({"timestamp" : {"order" : "desc"}})?Sonnnie
D
2

Check if timestamp is enabled in doctype.If it's enable, then only we can use timestamp in elasticsearch dsl.

#Add Query
s = Search(using=es, index="history", doc_type=p).query("query_string", query="*").sort("timestamp", {'order': "desc"})

#To specify the from/size parameters i.e for first 30 entries
s=s[0:30]

#Call elasticsearch
s.execute()
Drongo answered 13/3, 2017 at 9:3 Comment(0)
C
2

https://elasticsearch-dsl.readthedocs.io/en/latest/api.html?highlight=sort#elasticsearch_dsl.Search.sort

timestamp will sort in ascending order.

s = Search().sort('timestamp')

timestamp will sort in descending order.

s = Search().sort('-timestamp')
Cornhusking answered 8/1, 2021 at 4:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.