Home > Enterprise >  In elastic how can I add sort to my query so that it returns the results in a sorted order
In elastic how can I add sort to my query so that it returns the results in a sorted order

Time:07-28

"query": {

        "bool": {

            "must":[

                {

                    "range": {

                        "Date": {

                            "gte": firstDate,

                            "lte": lastDate

                        }

                    }

                },

               

               
            ]

        }

    }

Above is my query how can I add the sort feature so that I get the values returned sorted as right now they are not being returned sorted

CodePudding user response:

You can use Sort search to sort the results by one or more fields.

Example:

{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "Date": {
              "gte": "firstDate",
              "lte": "lastDate"
            }
          }
        }
      ]
    }
  },
  "sort": [
    {
      "firstDate": {
        "order": "desc"
      }
    }
  ]
}

CodePudding user response:

You could insert a sort clause

{
    "sort": [
        {
            "Date": {
                "format": "strict_date_optional_time_nanos",// From https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-date-format.html
                "order" : "desc"                
            }
        }
    ],
    "query": {
        "bool": {
            "must": [
                {
                    "range": {
                        "Date": {
                            "gte": firstDate,
                            "lte": lastDate
                        }
                    }
                }
            ]
        }
    }
}
  • Related