How to sort results with a term

Hi everyone,

I'm interested in searching docs with term and sorting them in the order:

  1. all docs should be sorted by field "date";

  2. first should come results where the field "isPerpetual": true and then all other fields with sorting by "date" field. Docs where "isPerpetual": true should be sorted by date too. Then comes all other documents where "isPerpetual": false and this lost should be sorted by date field too.

I have docs in my index:

{
"id": 1,
"date": 2024-01-01,
"price": 20,
"isPerpetual": true
},
{
"id": 2,
date": 2024-02-01,
"price": 30,
"isPerpetual": false
},
{
"id": 3,
date": 2024-03-01,
"price": 40,
"isPerpetual": true
},
{
"id": 4,
date": 2024-02-02,
"price": 30,
"isPerpetual": false
},
{
"id": 5,
date": 2024-04-01,
"price": 30,
"isPerpetual": true
}

Hello,

Could you please try below query & confirm if this is the way you need your data ?

{
  "query": {
    "match_all": {}
  },
  "sort": [
    { "isPerpetual": { "order": "desc" } },
    { "date": { "order": "asc" } }
  ]
}

Thanks!!