Elastic Search Sorting on a number field that matches phrase field

45 Views Asked by At

I want to do sorting on nested field quality score where the trade name matches the search term.

My code is as below which works fine when search term is one word. It fails to sort when search term is a phrase. How can I solve this? :

 sortDesc = _sortTerm switch
            {
                "Quality" => new SortDescriptor<Provider>().Field(so => so
                                                   .Field(f => f.Metrics.First().Data.Trades.First().QualityScore)
                                                   .Order(SortOrder.Descending)
                                                   .Nested(n => n
                                                       .Path(p => p.Metrics)
                                                        .Filter(q => q.Match(m => m
                                                              .Field(f => f.Metrics.First().Data.Trades.First().Name.Suffix("keyword"))
                                                              .Query(_searchTerm?.ToLower()))))
                                                  )
}


Thank you so much in advance.

1

There are 1 best solutions below

1
ESCoder On

If you want to sort on the nested numeric field, based on the match phrase results, you need to use the query as shown below :

Adding a working example, to replicate your requirements

Index Mapping:

{
    "mappings": {
        "properties": {
            "Metrics": {
                "type": "nested"
            }
        }
    }
}

Index API

{
    "Metrics": {
        "FIELDNAME": "hello worlds",
        "age": 2
    }
}

{
    "Metrics": {
        "FIELDNAME": "hello worlds",
        "age": 3
    }
}

{
    "Metrics": {
        "FIELDNAME": "hello world",
        "age": 1
    }
}

Search Query:

{
    "sort": [
        {
            "Metrics.age": {
                "order": "desc",
                "nested": {
                    "path": "Metrics"
                }
            }
        }
    ],
    "query": {
        "nested": {
            "path": "Metrics",
            "query": {
                "match_phrase": {
                    "Metrics.FIELDNAME": "SEARCH PHRASE"
                }
            }
        }
    }
}