Search code examples
searchtypesense

How can I easily get search context around search term with Typesense?


I currently use Typesense to search in an HTML database. When I search for a term, I would like to retrieve N characters before and N characters after the term found in search.

For example, I search for "query" and this is the sentence that matches:

Let's repeat the query we made earlier with a group_by parameter

I would like to easy retrieve a fixed number of letters (or words) before and after the term to show it in a presumably small area where the search results is retrieved, without breaking any words.

For this particular example, I would be showing:

..repeat the query we made earlier..

Is there a feature like this in Typesense?

I have checked Typesense's documents, without any luck.


Solution

  • The feature you're referring to is called snippets/highlights and it's enabled by default. You can control how many words are returned on either side of the matched text using the highlight_affix_num_tokens search parameter, documented under the table here: https://typesense.org/docs/0.23.1/api/search.html#results-parameters

    highlight_affix_num_tokens

    The number of tokens that should surround the highlighted text on each side. This controls the length of the snippet.