Writing a product search driver (external search engine)

🌐 Language: 🇻🇳 Tiếng Việt · 🇬🇧 English (current) · 🇯🇵 日本語

Writing a product search driver (external search engine)

Introduction

Every place where gp247/shop searches products (storefront, admin product list, REST API, MCP) goes through one shared service, GP247\Shop\Search\ProductSearch. The default database driver is a keyword index in the database. This page is for plugin developers: how to plug in an external search engine (Meilisearch, Typesense, OpenSearch, Algolia…) with a driver — without changing the core. By the end you have a working driver skeleton and know what the core already handles and what the plugin must do itself.

💡 Working with an AI agent? Use the gp247-plugin-create skill from the gp247-skills repo to scaffold the plugin (settings screen, encrypted API key, update-safe install), then add the driver following this page.

At a glance

flowchart LR
    S["Storefront · admin<br/>REST API · MCP"] --> P["ProductSearch<br/>(core)"]
    P -->|"driver synced"| D["Plugin driver<br/>search()"]
    P -->|"error · slow · not synced"| DB["database index"]
    D --> F["Core re-filters in the DB<br/>store · status · stock"]
    DB --> F
    W["Save / delete a product<br/>Rebuild index"] -->|"sync() · remove()"| D
  • The driver only proposes ids — the core always re-filters by store, status, hidden sold-out products and language before showing them.
  • On an error or a slow answer the core uses the database index — the store never loses search.
  • The data sent out is built by the core (SearchDocument) — public fields only: no cost price, no customer data, no custom fields.
  • A newly chosen driver answers only after one full rebuild — an empty engine does not make the store "lose" its results.
  • A real reference: the free Meilisearch plugin (open source).

ℹ️ Available since: gp247/shop 3.17.0

On this page


1. Contract

namespace GP247\Shop\Search;

interface ProductSearchDriver
{
    public function search(ProductSearchQuery $query): ProductSearchResult; // ids by relevance, at most $query->limit
    public function sync(array $documents): void;                          // SearchDocument[] — save / edit / rebuild
    public function remove(array $productIds): void;                       // deleted products
}
Public class Use
ProductSearchQuery keyword (as typed), terms (normalised: lower case, Latin accents removed, CJK bigrams), lang (null = every language), storeId (hint), context (storefront · admin · api · mcp), limit (1,000 by default)
ProductSearchResult::ids($ids, $total, $key) The driver's answer: product_ids by relevance
SearchDocument toArray(): id, store_id, status, sku, alias, texts[lang][name, keyword, description], brand, categories[lang][], price, price_promotion, sellable
ProductSearch::touch($ids) / forget($ids) Tell the core to update the index after the plugin writes product tables directly (not through the model)
RebuildAwareSearchDriver (optional) Extra interface for a driver that wants to know when a full rebuild starts and finishes: rebuildStarted(), rebuildFinished() — see section 4

These classes stay compatible within a major version. Do not import other internal classes of the shop.

2. Register the driver

In the plugin's Provider.php, register while the plugin is enabled and the shop has the search service:

if (gp247_extension_check_active($config['configGroup'], $config['configKey'])
    && interface_exists(\GP247\Shop\Search\ProductSearchDriver::class)) {
    config(['gp247-config.shop.search_drivers' => array_merge(
        (array) config('gp247-config.shop.search_drivers', []),
        [['key' => 'acme', 'label' => 'Acme Search', 'class' => \App\GP247\Plugins\AcmeSearch\AcmeDriver::class]],
    )]);
}
  • interface_exists keeps the plugin installable on an older shop (without the search service) — it then registers nothing.
  • An administrator of the root store chooses the driver in Configuration → Search. When the plugin is disabled / removed, the driver leaves the list and the core uses database again.
  • A newly chosen driver does not answer searches until it has received every product through one full rebuild (the Rebuild index button on the tab, or gp247:shop-search-index without --store). Meanwhile the database index answers and the tab reminds the site owner to rebuild. Switching to another driver needs another rebuild.

3. A driver skeleton

The example uses an imaginary "Acme" engine with an HTTP API, called with Laravel's HTTP client (no SDK needed):

namespace App\GP247\Plugins\AcmeSearch;

use GP247\Shop\Search\ProductSearchDriver;
use GP247\Shop\Search\ProductSearchQuery;
use GP247\Shop\Search\ProductSearchResult;
use GP247\Shop\Search\SearchDocument;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

class AcmeDriver implements ProductSearchDriver
{
    public function search(ProductSearchQuery $query): ProductSearchResult
    {
        // Shorter than the core's limit (2 seconds by default), so the core can still switch to the database index.
        $answer = $this->http(1.5)->post('/search', [
            'q' => $query->keyword, 'lang' => $query->lang, 'limit' => $query->limit,
        ])->throw()->json();

        return ProductSearchResult::ids(array_column($answer['hits'] ?? [], 'id'), $answer['total'] ?? null, 'acme');
    }

    public function sync(array $documents): void
    {
        $rows = array_map(fn (SearchDocument $d) => $d->toArray(), $documents);
        $this->http(10)->put('/documents', $rows)->throw();
    }

    public function remove(array $productIds): void
    {
        $this->http(10)->post('/documents/delete', ['ids' => $productIds])->throw();
    }

    private function http(float $seconds): PendingRequest
    {
        // Address and API key come from the plugin's settings; the key is stored encrypted (a setting with the security flag).
        return Http::baseUrl($this->host())->withToken($this->apiKey())
            ->connectTimeout(1)->timeout($seconds)->acceptJson();
    }

    private function host(): string { /* … */ }

    private function apiKey(): string { /* … */ }
}
  • search() must be fast: an answer past the time limit is dropped and the database index answers.
  • No need to filter store / status / stock yourself — the core re-filters. Filtering in the engine (by storeId, sellable) only keeps pages full.
  • Results are cut at limit (1,000 ids by default): enough for people searching, not for exporting data.
  • For a complete driver (settings screen, connection check, one document per product × language, cleaning old documents), read the code of the Meilisearch plugin.

4. Synchronisation

  • Saving / duplicating / deleting a product: the core calls sync() / remove() of the chosen driver after the database index is updated, after the page has answered. A driver failure is only reported; it never fails the save.
  • Products re-indexed after a brand / category is renamed (a little after each search) are sent with sync() too.
  • Full rebuild — the Rebuild index button on the tab (runs slice by slice in the browser, no CLI needed) or php artisan gp247:shop-search-index: each slice builds the database index, then sends the products of that slice to the chosen driver with sync() in batches of 200. When every batch went through, the driver is "synced" and starts answering searches. On failure the database index stays ready and the command exits non-zero. --store=<id> sends only the products of that store and leaves the sync state as it is.
  • When sync() / remove() throws (service down, flaky network) the core records a drift mark; the Search tab and the system alerts say "out of sync since … — rebuild". Searches still go to the driver (the core re-filters); the next successful full rebuild clears the mark.
  • A rebuild only overwrites documents: products deleted while the service was down stay in the engine. To clean them up, also implement the optional RebuildAwareSearchDriver interface — the core calls rebuildStarted() before the first batch and rebuildFinished() after the last one of a full rebuild (a rebuild that was interrupted and resumed does not call rebuildStarted() again). For example: number a generation in rebuildStarted(), stamp it on every document in sync(), then delete the documents of older generations in rebuildFinished(). An exception from rebuildFinished() counts as a failed sync().
  • The database index is always kept, even with an external driver chosen — it is the fallback path.
sequenceDiagram
    participant T as Search tab / command
    participant C as Core (ProductSearch)
    participant D as Driver
    T->>C: Rebuild index
    C->>D: rebuildStarted() (if implemented)
    loop each slice of products
        C->>C: build the database index
        C->>D: sync(batches of 200)
    end
    C->>D: rebuildFinished() (if implemented)
    C->>C: mark the driver "synced"

5. The plugin README

State in the README what is sent to the external service (the SearchDocument fields, and anything the plugin reads from the database itself), where the service runs, and how to delete the data there when the plugin is removed.


Conditions & Rules (know before you act)

When registering

  • Register only while the plugin is enabled and ProductSearchDriver exists — a disabled plugin must not answer searches, and an older shop has no such interface.
  • Keys are unique: a key already registered makes the later registration ignored; database is the core's key — so two plugins never fight over one choice.

When answering a search

  • Return ProductSearchResult::ids() — any other kind of result counts as an error, because the core only takes ids to re-filter them.
  • Past gp247-config.shop.search_driver_timeout (2 seconds by default), or an exception ⇒ that search uses the database index, the driver is paused for 60 seconds, and the error is reported through gp247_report at most once per 10 minutes per driver — so a flaky engine does not make every search wait.
  • Empty ids or ids longer than 64 characters are dropped; the list is cut at limit — so odd answers never reach the core's query.

When synchronising

  • A newly chosen driver answers only after one successful full rebuild — an empty engine would answer "no results" without that counting as an error.
  • The driver cannot be changed during a rebuild — so half of the products do not sit in the old engine and half in the new one.
  • Use only the public classes of section 1 — other internal classes of the shop may change between minor versions.

Q&A

Q1: Can a plugin override ShopProduct::buildQuery() instead?

→ Better not: each plugin would rewrite the store / stock / price filters, and the admin / API / MCP would not be covered. Use a driver.

Q2: What if a plugin writes shop_product / shop_product_description directly?

→ Call \GP247\Shop\Search\ProductSearch::touch($ids) after writing (wrapped in class_exists for older shops); on delete, forget($ids).

Q3: Does a processMoreQuery() filter on description columns still work while searching?

→ When the database index answers and the shopper has not sorted by name, the storefront does not join the description table into the search query (names and descriptions are loaded after paging) — a condition on description columns fails in that case. Filter on product table columns, or use whereExists.

Q4: How do I try a driver without a real engine?

→ In automated tests, fake the API with Http::fake() and call the driver's search() / sync() directly; to try it by hand, run the engine in Docker on your development machine.

Q5: Is there a complete driver to read?

→ Yes: the free Meilisearch plugin — driver registration, settings screen with the key, connection check, RebuildAwareSearchDriver to clean old documents.


📅 Last updated: 2026-12-02 · ✍️ Author: GP247