I'm trying to make a React instantsearch that lets you search phone numbers. They need to be displayed in this format: "(123)456-7890" but I want to be able to be able to search with either "(123)456-7890" or "1234567890".
I thought I could just store it in the index formatted and then the typo tolerance would take care of non-formatted queries. But I get no results with the query "1234567890". It apparently has to do with the fact that the formatting splits the number into three words and the query is just one word. Bizarrely, this means that adding the parentheses doesn't get you more matching characters on the search, but leaving them out can cause the query not to match at all.
I then tried just storing it as non-formatted (only digits) in the index. This time, both the formatted and unformatted queries got a match. But when typing it in digit-by-digit, the result disappears when I get to "(123)", only reappearing when I get to "(123)456-7". It seems like a frustrating and bizarre user experience to be typing exactly the number the result shows and having it disappear.
I've tried adding the perens to the optional words setting, but that didn't seem to have any effect. I think if I could get Algolia to ignore the perens and dash instead of replacing them with a space, this whole thing wouldn't be a problem. Is there a way to accomplish that? Maybe it's best to find a way to filter the query before it gets sent to Algolia? How should I go about that?
Store
1234567890
in an attribute namedphoneNoFormat
and(123)456-7890
in an attribute namedphoneFormat
. Include both insearchableAttributes
. On the display side, look in the_highlightResult
field to see which attribute matched and render the highlighted result for that attribute. With default typo tolerance each of these queries will match and correctly highlight either one or both of the attributes.Since you're using React InstantSearch, you will need to make your own
Hits
component, where you can change the attribute name used to display the result on a per-hit basis. Thankfully this is not too complicated. Just see the documentation for connectHits.When you are looping through the hits, look at each the
_highlightResult
property of each hit to see which of the two attributes matched. Then, when you create the<Highlight />
component set theattributeName
property to the right attribute. So you have this:Or this: