0
votes

In elasticsearch, I search some tags and sort them from the most matching to the least matching. It's ok.

However, my problem is about order of equal matching situations.

For example:

  1. I stored these tags: "tag1", "tag2", "tag3", "tag4", "tag5"
  2. I stored these tags: "tag6", "tag1"
  3. I stored these tags: "tag4", "tag3", "tag1"
  4. I stored these tags: "tag2", "tag1", "tag5", "tag7"

My search query:

{
    "query" : { 
        "bool" : { 
            "must" : [ 
                { 
                    "terms" : { 
                        "my_field" : ["tag4", "tag6"],
                        minimum_should_match : 1
                    } 
                }, 
                {"term" : {"my_cityId" : 1}}, 
                {"term" : {"my_townId" : 8}} 
            ] 
        } 
    }, 
    "sort" : [ 
        {"_score" : "desc"}, 
        {"my_topTime" : "asc"} 
    ], 
    "from" : 0, 
    "size" : 5 
}

It returns:

  1. "tag6", "tag1"
  2. "tag1", "tag2", "tag3", "tag4", "tag5"
  3. "tag4", "tag3", "tag1"

My search order is tag4 and then tag6. How can it be returned tag4 contained rows first and tag6 after?

1
The order of terms you provide in your query has nothing to do with with the score of the matching documents. The order of those 3 documents in your case depend entire on "my_topTime" . - Ryan Huynh.
By the way, "my_topTime" field values are all equal. It can be ignored. - ozgurm

1 Answers

0
votes

I found a solution to my problem from Boosting Filtered Subsets

I used "function_score" for my filter query, and added "functions" and "score_mode". Beside this, I specified "weight" for each tag in "functions".

The query returned tag4s first and then tag6 contained rows:

  1. "tag1", "tag2", "tag3", "tag4", "tag5"
  2. "tag4", "tag3", "tag1"
  3. "tag6", "tag1"

My new query:

{
    "query" : { 
        "function_score" : { 
            "filter" : { 
                "query" : { 
                    "bool" : { 
                        "must" : [
                            { 
                                "terms" : { 
                                    "my_field" : ["tag4", "tag6"],                                          
                                    minimum_should_match : 1
                                } 
                            } , 
                            {"term" : {"my_cityId" : 1}}, 
                            {"term" : {"my_townId" : 8}} 
                        ] 
                    } 
                } 
            }, 
            "functions" : [ 
                {"filter" : {"term" : { "my_field" : "tag4" }}, "weight" : 2},
                {"filter" : { "term" : { "my_field" : "tag6" }}, "weight" : 1} 
            ], 
            "score_mode": "sum" 
        } 
    }, 
    "sort" : [ 
        {"_score" : "desc"}, 
        {"my_topTime" : "asc"} 
    ], 
    "from" : 0, 
    "size" : 5 
}