Sort Result by Fuzzy Search Score
If you use fuzzy search, you might want to sort records in the result according to relevance. The relevance is expressed as a number called score.
Prerequisites
Context
Usually you want the records that fully match the search term to be on top (score = 1), the records with partial match to be further down (score < 1). To achieve this, you have to:
Procedure
- Define a virtual name for the score (called score alias), which you can use as the element name in the definition of the sort criteria. Note that you may define the alias only if a search term is provided.
- Extend the sort criteria defined by the client by appending a criterion to the score alias. Optionally, for better performance you can provide the sort criterion for the score only if the client does not define any other sort criteria.
Results
The code would look like this:
IF io_query_options->get_text_search_term ( ) IS NOT INITIAL.
io_query_options->set_text_search_score_alias( 'SEARCH_SCORE' ).
io_query_options->get_sort_elements(
IMPORTING et_sort_elements = DATA(lt_sort_elements) ).
APPEND VALUE #( element_name = 'SEARCH_SCORE' descending = abap_true )
TO lt_sort_elements.
io_query_options->set_sort_elements( lt_sort_elements ).
ENDIF.