Search
Product search goes through SyncShop\Modules\Catalog\Contracts\ProductSearch. Two drivers ship: PostgreSQL, the only
engine a small shop needs and the fallback for every shop, and Typesense. A Meilisearch driver can come behind the same
contract.
$result = resolve(ProductSearch::class)->search(new SearchQuery('cafea macinata', categoryId: $id, brandIds: [3], page: 1));
$result->productIds; // best match first
$result->total;
$result->exact; // the first hit matched a SKU or barcode exactly
The storefront sees products on sale only (activeOnly: true, the default). Prices, stock and visibility for a buyer
are applied to the hit list afterwards, so the index doesn't grow with every price list.
How the PostgreSQL driver matches
- Exact codes first. A query that is a product's SKU, barcode or manufacturer part number, whatever its case, puts that product first.
- Full text. The
romanianstemmer over unaccented text: diacritics fold, comma-below and cedilla forms alike (ș/ş, ț/ţ), somacinatafinds măcinată andceascafinds ceașca. Names weigh most, then the brand and codes, then the short description, then the description. - Typos. When full text finds nothing,
pg_trgmword similarity compares the query with the closest run of words in the name, sozacusastill finds Zacuscă, and so doescafeaua, which the stemmer reduces differently from cafea.
Filters: a category includes everything below it (the product's category paths are ltree), and brands.
Keeping the index in step
- Outbox. Saving or deleting a product or a variant, renaming a brand, moving a category and changing a product's
categories each write a
search_outboxrow in the same transaction as the change. A queued job sends the rows once the change commits. When the engine fails, the row stays with the error and a growing delay, so no update is lost.search:process-outboxruns every minute as a safety net. - Reconciliation.
search:reconcileruns at 03:30 and compares every product with its index entry by checksum. Drifted entries go back through the outbox, and the run is marked failed so the scheduler shows that the index had fallen behind. - Rebuild.
php artisan search:rebuildrebuilds the whole index inside one transaction, so searches keep using the old index until the new one is complete.
Typesense
Typesense is set up on Settings → Search (Catalog\Settings\SearchSettings, group search, API key encrypted),
not in .env. SEARCH_DRIVER and TYPESENSE_NODES / TYPESENSE_API_KEY / TYPESENSE_COLLECTION /
TYPESENSE_TIMEOUT only seed the settings when their migration first runs, so an automated install (the demo) can
start on Typesense; after that the admin screen is the source.
- Choosing the engine.
SearchEngines::current()backs theProductSearchbinding. It returns PostgreSQL unless Typesense is chosen and its index is built for the connection now set up:built_forholds theTypesenseConnection::fingerprint()(nodes and alias, not the key) of the last complete build. Saving a new cluster or alias queuesRebuildSearch;RebuildSearchIndexfills the new collection, setsbuilt_foronly if the settings did not change meanwhile, and sends products whose entry drifted during the build through the outbox. Switching to PostgreSQL clearsbuilt_for, so going back rebuilds from scratch. Before the settings exist (fresh install), PostgreSQL answers. - Connection test.
TestSearchConnectionchecks/healthon each node on its own (a node down while others answer is a warning), then the key, creating a collection, indexing, searching and an alias, and always removes its<alias>_check_<random>collection. The result is aPlatform\Data\CheckReport, rendered by<x-check-report>like the storage test. Node addresses are usually on a private network, so they are not restricted to public addresses; instead the server's own answers are never shown (SearchErrorsmaps failures to fixed messages), the client never follows redirects, the test route is throttled (10 a minute), and the saved API key is reused only when the typed nodes are the saved ones, so it cannot be sent to a new address. - Failover.
FailoverProductSearchwraps Typesense and PostgreSQL. Every change is indexed in PostgreSQL first, so the fallback is never stale. A query that Typesense fails is answered by PostgreSQL; after three failures within a minute the circuit breaker (in the shared cache) sends every query to PostgreSQL for 30 seconds, then tries Typesense again. While it is open, outbox rows wait and retry instead of timing out one by one. Timeouts are short (2 s by default, set on the screen) so a slow engine never holds up a page. - Zero-downtime rebuild. Searches go through an alias.
search:rebuild(or the screen's button) fills a new collection (<alias>_<timestamp>_<random>), swaps the alias to it when complete, then deletes the old collections. A rebuild that fails deletes its half-built collection and leaves the alias alone. - Matching. The same order as PostgreSQL: an exact SKU, barcode or part number first (a
codesfilter), then Typesense's ranking with typo tolerance and prefixes over the name, its folded form (ș/ş→s), the brand, the codes and the descriptions. Category filters match the category and everything below it, because each document carries its categories' paths and the paths above them. - Reconciliation.
search:reconcilecompares both indexes with the products by checksum (ProductDocumentbuilds the document and the checksum for both engines).
Tests play the Typesense server with a Guzzle handler (Tests\Fixtures\FakeTypesense, passed to SearchEngines as its
HTTP client), so they run without one. To try it against a real server locally: brew install typesense/tap/typesense-server, start it with an API key, and fill in Settings → Search with http://127.0.0.1:8108.
Semantic search
Contracts\AssistedSearch(Search\AiAssistedSearch):understand(text)returns aData\SearchIntent: text, min/max price in bani, brand ids, vector,understood. It never throws.- Understanding runs through
AiFeature::SearchIntent(a structured answer with keywords, min_price, max_price and brand, validated; the brand matched byTaxonomy::brandNamed()). Only forreadsLikeASentence()searches, afterscreen()removes e-mails and long digit runs. - The vector runs through
AiFeature::SearchEmbeddings(Assistant::embed(), primary route only), only when the current engine is Typesense. - Only the screened text is sent or cached; the search runs on the original unless the model understood it.
- Both are cached a day per screened search and model; a partial failure is not cached.
AiFeature::isPublic()features need a daily budget to be switched on. Calls made for a shopper's request passforShopper: true: they skip the budget lock (never waiting on another call) and count against a shop-wide cap ofGatedAssistant::SHOPPER_CALLS_PER_MINUTEper feature. Batch work (search:embed) keeps the locked path.
Data\SearchQuerytakesminPrice,maxPriceandvector.ProductDocumentcarriesminPrice(the lowest active variant price) inproduct_search.min_priceand Typesense'smin_price, plusembeddingText/embeddingChecksum().Search\ProductVectorshandles theproduct_embeddingstable (product, model, dimensions, checksum, vector jsonb), for the modelAssistant::embeddingModel()names. Storing one model's vector drops the others.Search\EmbedProducts(search:embed, every 15 min) embeds active products whoseembeddingChecksum()differs, 64 per call, then pushes them to the outbox. It does nothing unless the feature is available and Typesense is current.- Typesense:
- The schema gets
embedding(float[],num_dimfrom the stored vectors) when known.ensureVectorField()adds or replaces it on the live collection (PATCH) when a document brings a vector of another length. - A query with a vector of the right length adds
vector_query: embedding:([...], k: 200, alpha: 0.3)and dropssort_by, so Typesense fuses the text and vector rankings.
- The schema gets
- Storefront:
SearchControllerasksunderstand()unlessexact=1or the visitor'ssearch-ai:<ip>limit (10 a minute) is spent, shows the understood chips with a link to the exact search, and repeats the search as typed when the understood one finds nothing.
Tests: tests/Feature/Catalog/SemanticSearchTest.php.
Related products
-
product_relations(product, kind, related product, position, score) holds, per product, the similar products (RelationKind::Similar, up to 8) and those bought together (RelationKind::Together, up to 6), replaced every night byRelated\RelateProducts(catalog:relate, 03:50). -
Similar: when the current engine is a
Search\FindsSimilar(Typesense, throughFailoverProductSearchwhile it is healthy) and the product has a vector for the current model,similar()asks Typesense for its nearest neighbours by its own stored vector (vector_query: embedding:([], id: <id>, k: n+1), active and public only, itself excluded): no AI call. Otherwise, or when the engine fails or finds nothing, the rules: products sharing most categories (category_product), the same brand first, then the closestmin_price. -
Bought together:
Orders\Contracts\CoPurchases::pairs()counts, for each ordered pair of products in the same order in the last 365 days, the distinct buyers (lower-cased e-mail), leaving out gift lines and cancelled or returned orders; only pairs with at least two buyers come back. -
Reading:
Catalog\Contracts\RelatedProducts(of(),forBasket()) returns only products that are active and public (product_search).Storefront\Support\Suggestionsturns them into cards: bought together in stock only, similar in stock first, four each on the product page (and its Markdown version), four for the cart. The MCP server'sget_productlists them as names and links. -
Picks:
product_relation_picks(product, kindtogether/similar/hidden, related product, position), saved byRelated\RelationPicksfrom the SKUs typed on the product's Produse asociate tab (ProductRelationsController,catalog.manage).DatabaseRelatedProductsreads them live: picks first in their order, then the computed relations without the picks and without the pairs the product hides;forBasket()the same, picks of the basket's products first. -
Best sellers:
Related\CountBestSellers(catalog:bestsellers, 03:55) replacesproduct_sales(product, units, distinct buyers) fromSalesFigures::products()over the last 90 days (gifts, cancelled and returned orders left out).ProductSort::BestSelling(vandute) orders listings by those units, then the newest;RelatedProducts::bestSelling()gives the home page's best sellers (two buyers or more). -
Recently viewed:
Storefront\Support\RecentlyViewedkeeps up to 12 product ids, newest first, in the session (recently_viewed); the product page adds to it (not its Markdown version) and shows the four before it, the home page the last four.
Tests: tests/Feature/Catalog/RelatedProductsTest.php, tests/Feature/Storefront/RecentAndBestSellersTest.php.