Search code examples
elasticsearchelasticsearch-dsl

Elasticsearch matched results on top and remaining after them


I am using elasticsearch in my application and I am new to Elasticsearch.

I have an index called files with some tags associated to it. I want to query them using tags. something like this may be

{
  "query": {
    "terms": {
      "tags": [
        "xxx",
        "yyy"
      ]
    }
  },
  "sort": [
    {
      "created_at": {
        "order": "desc"
      }
    }
  ]
}    

The above query results only matched ones. But I need all the results with matched results on top. And also sort by created_at. How to do it?

I TRIED THIS:

{
  "query": {
    "bool": {
      "should": [
        {
          "terms": {
            "name": [
              "cool",
              "co"
            ]
          }
        }
      ],
      "minimum_should_match": 0
    }
  },
  "sort": [
    {
      "_score": {
        "order": "desc"
      }
    },
    {
      "created_at": {
        "order": "desc"
      }
    }
  ]
}

But results zero always.


Solution

  • You can use bool queries with should.

    Since you want all the docs, you can use a match_all. should only affects the scoring and not whether documents are included or not.

    {
      "query": {
        "bool": {
        "must" :
         {
                   "match_all": { }
                }
        },
        "should": [
     {  "terms" : {
          "tags": [
            "xxx",
            "yyy"
          ]
        } }]
      },
        "sort": [
            { "_score": 
               { "order": "desc" 
             }
            },
            { "created_at":  
             { "order": "desc" 
            } 
           }       
        ]
    }  
    
    

    Also, sort can take an array so you can pass in your multiple parameters basis which the results should be sorted.