danpaz/bodybuilder

Sort() incorrectly merges two sort entries involving the same field, even if the filters would create unique sort criteria...

Closed this issue · 0 comments

If you have a sort query like so for ElasticSearch 7.5:

bodybuilder()
        .query('match', 'message', 'this is a test')
        .sort([
  	    { "nested_entity.name": { 
                    "order": "asc", 
                    "nested": { 
                         "path": "nested_entity", 
                         "filter" : { 
                                "term": { "nested_entity.subfield.text" : "text1" }
                          }
                     }
               }
           },
  	    { "nested_entity.name": { 
                    "order": "desc", 
                    "nested": { 
                         "path": "nested_entity", 
                         "filter" : { 
                                "term": { "nested_entity.subfield.text" : "text2" }
                          }
                     }
               }
           },
         ])
        .build()

Body builder will collapse those two sort queries into a single one like so:

{
  "sort": [
    {
      "nested_entity.name": {
        "order": "desc",
        "nested": {
          "path": "nested_entity",
          "filter": {
            "term": {
              "nested_entity.subfield.text": "text2"
            }
          }
        }
      }
    }
  ],
  "query": {
    "match": {
      "message": "this is a test"
    }
  }
}

This is incorrect behavior. It's possible to have multiple nested_entity in the document, and you could possibly want to sort by all the ones matching text1, and then all the ones matching text2. This is likely due to the fact that both sort options use the same field nested_entity.name even though they are not identical when you drill down all the way into the filters required.