1

I would like to sort the documents based on the position of the matching text and then alphabetically.

E.g I have follow 3 values.

PATRICK STREET WEST
MOUNT ST PATRICK ROAD
PATTI MCCULLOCH WAY

I am search with Pat* and I want the results should be sort by the position of the matching text and then alphabetically.

E.g Required result

PATRICK STREET WEST
PATTI MCCULLOCH WAY
MOUNT ST PATRICK ROAD

but I am getting the result in the below order.

PATRICK STREET WEST
MOUNT ST PATRICK ROAD
PATTI MCCULLOCH WAY
Harsh Gupta
  • 307
  • 2
  • 14
  • Not exactly: Actually I want to sort with the matching string first then alphabetically. e.g if I search with Pat then all documents which are starting with Pat should come first and others should go to the next level. – Harsh Gupta Jul 01 '22 at 10:26

1 Answers1

1

This is a bit of a tricky requirement. Let's break this down into the two distinct asks:

  1. Sort results based on the position of the text - there's no query syntax that would allow you to do this but there are some ways to get at this requirement. One option to allow you to boost documents that start with Pat would be to create a second field with the same text that uses a custom analyzer with a keyword_v2 tokenizer and lowercase token filter. That new field would only match if the string of text started with the letters Pat. You could then use scoring profiles or term boosting to weight matches in that field more to bring those results that matched at the beginning to the top.

  2. Sort alphabetically - I'd recommend sorting by search score and then by the text like this: $orderby=search.score() desc,TextField desc. If you follow my recommendations from #1, items where they matched in the beginning of the string should have higher scores than other items and then can be sorted alphabetically within that set. Then all items where the match wasn't in the beginning will come after and will also be sorted alphabetically.

That should at least get you fairly close to the requirement! You could always do a bit of extra sorting on the client side if needed too.