Get result from last 2 days with python and ElasticSearch

Viewed 135

I have this python code that get results from ElasticSearch

from elasticsearch import Elasticsearch
es = Elasticsearch([{'host':'127.0.0.1' , 'port' : 1234}])
query = 'name:Jon'
es.search(index='MyIndex' , q=query , size =50)

That works ! but ...

  1. How can I get only results from last 2 days?
  2. How can I get results sorted by news item first?
1 Answers

queries in python elasticsearch module can be like elastic queries.

query = 
'{
     
      "sort": [
        {
          "date": {
            "order": "desc"
          }
        }
      ],
    "query": {
        "bool": {
          "must": [
            {
              "range": {
                "date": {
                  "gte": "2021-02-09 00:00",
                  "format": "yyyy-MM-dd HH:mm"
                }
              }
            },
            {
              "term": {
                "name": {
                  "value": "jon"
                }
              }
            }
          ]
        }
      }
    }'
Related