Demo, all content is generated
Question

How do I search Firestore by part of a name? like SQL LIKE

Open · 1303 views · asked by wairimu · edited

I have ~3000 products in Firestore. User types "choc" and should see "Dark chocolate bar" and "Hot chocolate". ChatGPT gave me this:

where("name", ">=", term), where("name", "<=", term + "\uf8ff")

but that only matches the beginning and it's case sensitive, so "choc" finds nothing because they start with "Dark" and "Hot".

What I’ve tried

Tried storing name in lowercase. Helps with case, but still prefix only. Loading all 3000 docs and filtering in JS works but feels wrong.

Comment
How many docs and how often does the user search? That decides it. sven_fire · edited

3 answers

sven_fire · edited

Firestore has no substring or full-text search, by design. Options, from simple to proper:

  1. Keywords array. On write, store keywords: ["dark","chocolate","bar","choc","choco",...] (words plus their prefixes, lowercased) and query where("keywords", "array-contains", term). Works fine for short product names.
  2. Search extension. Firebase has official extensions that sync a collection to Algolia, Typesense or Elastic. Real search, typos, ranking. Costs money beyond free tiers.

For 3000 products I'd do 1.

Comment
lena_ops · edited

Honestly at 3000 small docs, loading them once and filtering on the client is not wrong. It's ~3000 reads per full load though, so cache it (persistent cache or just localStorage with a timestamp) instead of refetching per keystroke. That's the part that gets expensive. If the catalogue will grow to 50k, go with the keywords array or an extension.

Comment
Fair, as long as it's cached. The keystroke refetch is how people get the surprise bill. sven_fire · edited
I'll try keywords first because we will add a lot more products. thank you both wairimu · edited
hannah_reyes · edited

Different angle, only if search is central to the product: this is where Postgres shines. pg_trgm with a GIN index gives you fast ilike '%choc%' and fuzzy matching out of the box. Not a reason to migrate on its own, but worth knowing when you pick a database for the next project.

Comment
True. Right tool for the job, Firestore is not a search engine. sven_fire · edited