heyu
heyu

Reputation: 185

elasticsearch: how to sort by list of tags and a numeric field

I have 3 documents in a mapping look like this

{ "tags":["a"], "count":10 }
{ "tags":["a","b","c"], "count":50 }
{ "tags":["a","c"], "count":100 }

When I search by tags, say, {"should":["tags":"a", "tags":"b"]}

Want the result to be sorted by number of tag match, then by count desc, like this:

{ "tags":["a","b","c"], "count":50 }
{ "tags":["a","c"], "count":100 }
{ "tags":["a"], "count":10 }

How can I achieve this? I tried sort [_score, {"count":"desc"}], however, because of the score values are all different, the {"count":"desc"} part never worked.

Any help is appreciated. Thanks.

Upvotes: 2

Views: 810

Answers (2)

CodeQ
CodeQ

Reputation: 11

This will sort results by score and by count:

{
    "query": {
        "bool": {
            "should": [
                {"term": {"tag": "a"}},
                {"term": {"tag": "b"}}
            ]
        }
    },
    "sort": {
        "_score": {
            "order": "desc"
        },
        "count": {
            "order": "desc"
        }
    }
}

Upvotes: 1

chengpohi
chengpohi

Reputation: 14217

 {
   "sort": [{"count": "desc"}],
   "query": {
     "filtered": {
       "filter": {
         "bool": {
           "should": [
             {"term": {"tag": "a"}},
             {"term": {"tag": "b"}}
         }
       }
     }
   }
 }

use filter query to ignore document score, and use sort to sort.

Upvotes: 0

Related Questions