How can I filter based on first two characters of a number or string?


I wanted to ask, how can I filter a string or a number based on the first two characters. For example, one starts with 20 and another one with 17; I want to filter based on all the records that start with a 20 or 17.

Example of records:

    // Filter all the records based on the first two characters
    "to_filter": 206789993
    "to_filter": 176958849


Hey @danieldmuller984! Would you mind sharing a couple more details?

By default when doing a search function, the API will search from the beginning of strings to match. If what you’re looking for is to search based on the full number and get back “fuzzy” results based on the first two digits, I might suggest doing a modification to the number before sending it to Algolia to strip anything past the first two digits and then sending that as a query.

It’s probably going to depend on the actual use case here, so let me know.

Yes, it’s not the search query, the one I want to use. It’s filtering the results based on what I’ve explained first.

I do one query with “John” and then I filter the results based on one specific parameter called “example”, this parameter holds records that start with 20, 17 and so on.

This parameter is larger, 8 or 10 characters, separated by dots and a hyphen. The characters after the first two are not useful. That’s why I want to filter based on the starting two. I can’t cut this parameter before sending it to the index, because it’ full value is useful and valuable info.

Late to the party here, but your best bet may be to set up a secondary attribute with the just the two digit prefix and make that filterable attribute. It will allow for the fastest search and means you won’t be fighting against the fuzzing capabilities of the search.

I’m also looking to do this.
In my case I simply want to filter the search results by the first two or three characters of a partial URL which will tell me the language.
e.g. filtering for “en/” includes “en/brands/sony” and excludes “ja/brands/sony”

Is this possible?

Same response – I would recommend adding the language as a filterable attribute, rather than trying to do this using prefix search on the URL string.