Searching for a term in normal and nested field. Providing position based sorting

DELETE test

PUT test

GET test/_mapping

PUT test/test/_mapping

{

"properties": {

"name": {

 "type": "text",

 "fields":{

     "keyword":{

      "type":"keyword"

     }

    }

},

"words": {

 "type": "nested",

 "properties": {

  "text": {

    "type": "text",

    "fields":{

     "keyword":{

      "type":"keyword"

     }

    }

  },

  "weight": {

    "type": "long"

  }

 }

}

}

}

PUT test/test/0

{

"name": "pepper",

"words": [

{"text": "kepper", "weight": 20},

{"text": "bell","weight": 10},

{"text": "red","weight": 5}

]

}

PUT test/test/1

{

"name": "red pepper",

"words": [

{"text": "Hey kepper","weight": 20},

{"text": "hot","weight": 11},

{"text": "red","weight": 5}

]

}

PUT test/test/2

{

"name": "hot red pepper",

"words": [

{"text": "Hello kepper", "weight": 20},

{"text": "hot","weight": 11},

{"text": "red","weight": 5}

]

}

######################################################################

We are looking for the position based sorting. So below is the query for above data. We are able to do position based sorting using below query, But when it comes to nested field we are not getting the scores properly.

Situation is : we are searching for anything (example 'pep' or 'kep') it may be either in name or in words. If 'pep' found in name field, then name must be sorted based on position of occurrence, if 'kep' found in words fields then words must be sorted based on position of occurrence. If term is found in both the fields then preference must be given to name field. This query if working fine only if term in present in name field, then getting correct score.

######################################################################

GET test/_search

{ "query": {

"function_score": {

"query": {

 "bool": {

 "should": [

  {

   "query_string": {

    "default_field": "name",

    "query": "*pep*"

   }

  },

  {

    "nested": {

     "path": "words",

     "query": {

       "function_score": {

        "functions": [

          {

           "script_score": {

            "script": "doc['words.text.keyword'].value.indexOf('pep')"

           }

          }

        ],

        "query": {

         "query_string": {

          "default_field": "words.text",

          "query": "*pep*"

         }

        },

        "score_mode": "sum",

        "boost_mode": "replace"

       }

     },

     "inner_hits":{

       "size":1

     }

     ,

     "score_mode": "max"

    }

  }

 ]

}

},

"script_score": {

"script": "doc['name.keyword'].value.indexOf('pep')"

},

"boost_mode": "replace"

}

},

"sort": [

{

"_score":"asc",

"name.keyword": "asc"

}

]

}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.