perf: reuse cached search engine instead of rebuilding on every query

search_products() and find_product_substitutes() were ignoring the
already-built self._search_engine and creating a brand new ProductSearch
instance on every call — serialising every product to dict and
re-initialising the fuzzy engine each time.

They now use self._search_engine directly. The engine is already kept
up-to-date by add_product / update_product / delete_product, so no
correctness change is needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
thekiwismarthome
2026-08-11 17:45:43 +12:00
parent c55e90d74f
commit 91cbc6018c
@@ -518,20 +518,15 @@ class ShoppingListStorage:
if not self._search_engine: if not self._search_engine:
_LOGGER.warning("Search engine not initialized") _LOGGER.warning("Search engine not initialized")
return [] return []
# Convert products dict to format search engine expects results = self._search_engine.search(
products_dict = {pid: p.to_dict() for pid, p in self._products.items()}
search_engine = ProductSearch(products_dict)
results = search_engine.search(
query=query, query=query,
limit=limit, limit=limit,
exclude_allergens=exclude_allergens, exclude_allergens=exclude_allergens,
include_tags=include_tags, include_tags=include_tags,
substitution_group=substitution_group, substitution_group=substitution_group,
) )
# Convert back to Product objects
return [self._products[r["id"]] for r in results if r["id"] in self._products] return [self._products[r["id"]] for r in results if r["id"] in self._products]
def find_product_substitutes(self, product_id: str, limit: int = 5) -> List[Product]: def find_product_substitutes(self, product_id: str, limit: int = 5) -> List[Product]:
@@ -546,11 +541,8 @@ class ShoppingListStorage:
""" """
if not self._search_engine: if not self._search_engine:
return [] return []
products_dict = {pid: p.to_dict() for pid, p in self._products.items()} results = self._search_engine.find_substitutes(product_id, limit)
search_engine = ProductSearch(products_dict)
results = search_engine.find_substitutes(product_id, limit)
return [self._products[r["id"]] for r in results if r["id"] in self._products] return [self._products[r["id"]] for r in results if r["id"] in self._products]
def get_product_suggestions(self, limit: int = 20) -> List[Product]: def get_product_suggestions(self, limit: int = 20) -> List[Product]: