Search by

akawaka / sylius-open-search-plugin

akawaka

OpenSearch product search for Sylius: autocomplete, fuzzy matching and synonyms.

Package info

github.com/akawaka/SyliusOpenSearchPlugin

Type:sylius-plugin

pkg:composer/akawaka/sylius-open-search-plugin

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

This package is not auto-updated.

Last update: 2026-12-04 08:32:45 UTC


README

AKAWAKA

AKAWAKA is a software development company specializing in e-commerce platforms and custom web applications. We help businesses evolve or rebuild their platforms with a pragmatic approach: improving existing solutions or starting from scratch, notably with Sylius. Our team also handles data migration, SEO preservation, and business continuity. With strong expertise in PHP and Symfony, AKAWAKA builds web solutions tailored to our clients’ business needs.

Sylius OpenSearch Plugin

Product search for Sylius 2 powered by OpenSearch: autocomplete, typo tolerance and synonyms.

  • Search page with relevance ranking, sorting, taxon / price / stock filters and pagination
  • Autocomplete in the shop header (Stimulus, ARIA combobox), tolerant to typos and accents
  • Synonyms managed in the Sylius administration, applied without reindexing
  • Always up to date: products, prices, stock and taxons are re-indexed when they change (optionally through Messenger)
  • Zero downtime full reindexation, one index per channel and locale
  • English and French (analysis and translations)

Installation

Requirements: PHP 8.2+, Sylius 2.2+, an OpenSearch 2.x server.

  1. Add the Akawaka Flex recipes endpoint to your project, then require the plugin:

    composer config --json extra.symfony.endpoint '["https://api.github.com/repos/akawaka/symfony-recipes/contents/index.json?ref=flex/main","flex://defaults"]'
    composer require akawaka/sylius-open-search-plugin

    Symfony Flex registers the bundle, creates config/packages/akawaka_sylius_open_search.yaml and config/routes/akawaka_sylius_open_search.yaml, and adds OPENSEARCH_URL to your .env (see Manual installation for their content).

  2. Point the plugin to OpenSearch (OPENSEARCH_URL in .env, http://localhost:9200 by default) and create the tables of the synonyms and of the facet blocks:

    bin/console doctrine:migrations:migrate
  3. Build the indices (see OpenSearch indexing):

    bin/console akawaka:opensearch:reindex
  4. Add the frontend entrypoint to your shop bundle (see Frontend assets).

For development, docker compose up -d opensearch starts a single-node OpenSearch with security disabled. Do not use that setup in production: enable the security plugin and set connection.username, connection.password and connection.ssl_verification.

Manual installation (without Flex)

Replace the first step above with:

  1. Require the plugin and register the bundle:

    composer require akawaka/sylius-open-search-plugin
    // config/bundles.php
    AKAWAKA\SyliusOpenSearchPlugin\AKAWAKASyliusOpenSearchPlugin::class => ['all' => true],
  2. Import the configuration and the routes:

    # config/packages/akawaka_sylius_open_search.yaml
    imports:
        - { resource: "@AKAWAKASyliusOpenSearchPlugin/config/config.yaml" }
    # config/routes/akawaka_sylius_open_search.yaml
    akawaka_sylius_open_search_shop:
        resource: "@AKAWAKASyliusOpenSearchPlugin/config/routes/shop.yaml"
        prefix: /{_locale}
        requirements:
            _locale: ^[A-Za-z]{2,4}(_([A-Za-z]{4}|[0-9]{3}))?(_([A-Za-z]{2}|[0-9]{3}))?$
    
    akawaka_sylius_open_search_admin:
        resource: "@AKAWAKASyliusOpenSearchPlugin/config/routes/admin.yaml"
        prefix: '/%sylius_admin.path_name%'
  3. Set OPENSEARCH_URL in your .env (the default is http://localhost:9200).

Configuration reference

akawaka_sylius_open_search:
    connection:
        hosts: ['%env(OPENSEARCH_URL)%']
        username: ~
        password: ~
        ssl_verification: true
    index_prefix: sylius_product       # alias: {prefix}_{channel}_{locale}
    indexing:
        batch_size: 500
        number_of_shards: 1
        number_of_replicas: 0
        incremental:
            enabled: true              # false: disable the catalog listener
            transport: ~               # Messenger transport, e.g. "main"
    synonyms:
        sync_on_change: true           # false: disable the synonym listener
    search:
        fields: {}                     # extra boosts, e.g. { brand: 3.0 }; built-in: name 5, sku 4, short_description 2, description 1 (0 removes a field)
        fuzziness: AUTO                # "AUTO", "AUTO:3,6", 0, 1 or 2
        fuzzy_prefix_length: 1
        fuzzy_max_expansions: 50
        per_page: 12
        per_page_options: [12, 24, 48]   # choices of the "Show" menu
    facets:
        taxon_page: true               # serve the category pages with OpenSearch
    autocomplete:
        min_length: 2                  # letters typed before suggesting (browser and server)
        inline_completion: true        # false: no completion inside the input, the dropdown stays
        product_suggestions: 5
        term_suggestions: 5

Console commands

Command Purpose
akawaka:opensearch:reindex [--channel=] [--locale=] Rebuild the indices without interruption
akawaka:opensearch:synonyms:sync [--channel=] [--locale=] [--force] Apply the synonyms to the live indices

Troubleshooting

Symptom Cause and fix
The search page answers 503 OpenSearch is unreachable: check OPENSEARCH_URL, credentials and ssl_verification.
The search finds nothing The index does not exist yet: run akawaka:opensearch:reindex (see Search → Index status).
A product change is not visible Check that indexing.incremental.enabled is true, and with a transport that a worker is running. Errors are logged as "Could not update the OpenSearch index". Run reindex to repair any drift.
A synonym has no effect Index status shows "To apply": run akawaka:opensearch:synonyms:sync. Check that the synonym is enabled and scoped to the right channel / locale.
index_closed_exception in another client Synonyms are applied by closing the index for about half a second; the plugin retries its own searches transparently.
Autocomplete box does not show up The frontend entrypoint is not imported, or the header hook was disabled.
Images missing with php -S The built-in server does not serve some static URLs: use the Symfony CLI, nginx or Apache.

OpenSearch indexing

Start OpenSearch (and Dashboards on http://localhost:5601) for development:

docker compose up -d opensearch
export OPENSEARCH_URL=http://localhost:9200

Rebuild the product indices — one per channel and locale, exposed through the alias {index_prefix}_{channel}_{locale} (e.g. sylius_product_fashion_web_en_us):

bin/console akawaka:opensearch:reindex                       # everything
bin/console akawaka:opensearch:reindex --channel=FASHION_WEB --locale=en_US

A new timestamped index is filled next to the live one, then the alias is switched atomically and the previous index is removed: searches are never interrupted, and a failure leaves the live index untouched.

To index your own fields, write a contributor class tagged with #[AsDocumentFieldContributor]: see the tutorial Index and search a custom field.

Analyzers are provided for English and French (stemming, stop words, elision, accent folding); other locales use a plain lowercase/ascii-folding chain.

Integration tests run against a real OpenSearch (OPENSEARCH_URL, default http://localhost:9200) and are skipped when it is unreachable.

Search page

GET /{_locale}/search lists the matching products (route imported during the installation).

Query parameter Meaning
q Search text. Typos are tolerated and partially typed words match. Every word must match.
sort relevance (default), newest, name_asc, name_desc, price_asc, price_desc, plus your own sorts (taxon pages: position by default)
taxon[] Taxon codes (a product matches if it belongs to any of them)
price_min, price_max In the channel currency; applied to the price shown on the product card (the first enabled variant)
in_stock 1 to hide out-of-stock products
limit Page size, one of search.per_page_options (default search.per_page)
page Page number

OpenSearch finds and ranks the products; the entities are then loaded from the database, so product cards, prices and promotions are rendered by Sylius exactly as in the catalog. Products disabled since the last indexation are dropped silently. If OpenSearch is down the page answers 503 with a friendly message.

Tuning (fields and boosts, fuzziness, page size) is done under akawaka_sylius_open_search.search. The page reuses the markup and classes of the Sylius product listing (breadcrumbs, search field, "Show" and "Sort" menus, product grid, pagination) so it matches the rest of the catalog. Override @AKAWAKASyliusOpenSearchPlugin/shop/search/index.html.twig to change it.

Each sort is a PHP class tagged with #[AsSort]: to add your own (best rated, best sellers...), see Add a sort.

Browser test: BASE_URL=http://127.0.0.1:8080 node tests/E2E/search_page.mjs.

Note: the price filter, the price sort and the bounds of the price block use the price shown on the product card, i.e. the one of the first enabled variant (indexed in the price field). The cheapest and the most expensive variants stay indexed in price_min and price_max. Run akawaka:opensearch:reindex after upgrading.

Facets (filters of the category and search pages)

The left column of the category pages (/taxons/...) and of the search page shows blocks of filters with counters, configured in the administration under Search > Facets:

Block Filters on
Category list sub-categories of the current category, its siblings, or whichever exists (on the search page: the categories of the results, as a filter)
Price range min / max price, the placeholders show the bounds of the results
In stock products with a variant in stock
Product option one option (e.g. size), values and counts come from the index
Product attribute one attribute (select attributes show their translated choices)

Blocks can be added, removed, disabled and reordered (drag and drop, or the arrows). The configuration is either the default one, or one per category: a category with its own blocks replaces the default ones for itself and its sub-categories (the closest ancestor with blocks wins). Without any configuration, the pages show categories, price and stock.

The type of a block is a PHP class: to add your own (a brand, a rating...), tag a class with #[AsFacetType], see Add a type of facet block.

Selecting several values of one block widens the results (OR), several blocks narrow them (AND), and a block keeps listing the values that are still reachable from its own selection. Selections are in the query string: option[CODE][], attribute[CODE][], taxon[], price_min, price_max, in_stock.

The category pages are served by OpenSearch (listener on the sylius_shop_product_index route), sorted by their position in the category by default; if OpenSearch is unavailable, the native Sylius listing takes over. Set akawaka_sylius_open_search.facets.taxon_page: false to keep the native listing (the facets then only apply to the search page).

The position of the products in their categories is a new indexed field (taxon_positions): run bin/console akawaka:opensearch:reindex after upgrading. Facet changes themselves never need a reindexation. Run the Doctrine migrations too (new akawaka_search_facet_block table).

Autocomplete

A search box with autocomplete is added to the shop header (Twig hook sylius_shop.base.header.content, priority 250). While typing it suggests completed search terms and the best matching products (image and price rendered by Sylius), tolerates typos and ignores accents. It is an ARIA combobox: arrow keys, Enter, Escape, screen reader announcements, and the form still works without JavaScript.

The input is also completed in place, like a browser address bar: typing t-sh shows t-shirt with irt selected. → or Tab accepts it, Backspace or Escape drops it, and Enter searches for the completed text. Set inline_completion: false to turn this off and keep only the dropdown.

GET /{_locale}/search/suggest?q=… returns the list items as an HTML fragment (204 when there is nothing to suggest, 503 when OpenSearch is down). Override @AKAWAKASyliusOpenSearchPlugin/shop/search/suggest.html.twig to change the markup.

Options, under akawaka_sylius_open_search.autocomplete: min_length (the number of letters before anything is suggested, used by the browser and the server), inline_completion, product_suggestions, term_suggestions.

Frontend assets

The plugin ships a Stimulus controller and a stylesheet in assets/shop/entrypoint.js. It starts its own Stimulus application, so it does not depend on how the shop registers its controllers. Include the entrypoint in your shop bundle (the Sylius test application already does), which needs @hotwired/stimulus:

import '../../vendor/akawaka/sylius-open-search-plugin/assets/shop/entrypoint';

To hide the header box, disable the hook:

sylius_twig_hooks:
    hooks:
        'sylius_shop.base.header.content':
            akawaka_search:
                enabled: false

Browser test

BASE_URL=http://127.0.0.1:8080 node tests/E2E/autocomplete.mjs

Drives a headless Chromium through the DevTools protocol (typing, debounce, keyboard, mouse, ARIA attributes, navigation, mobile layout, JavaScript errors) and saves screenshots.

Synonyms

Synonyms are managed in the Sylius administration, under Search → Synonyms.

Kind Terms Also search for Effect
Interchangeable sweater, pullover, jumper (empty) each word finds the products of the others
One-way tee t-shirt searching tee also finds t-shirts, not the reverse
  • A synonym can be limited to one channel and/or one locale (empty = all).
  • Multi-word terms are supported (hoodie → hooded sweatshirt).
  • Synonyms are applied at search time only: the index analyzer is untouched, so changing a synonym never requires reindexing the products.
  • Saving, disabling or deleting a synonym updates the live indices immediately. If OpenSearch is unreachable the change is saved and logged; apply it later with:
bin/console akawaka:opensearch:synonyms:sync            # only the outdated indices
bin/console akawaka:opensearch:synonyms:sync --force    # all of them
bin/console akawaka:opensearch:synonyms:sync --channel=WEB --locale=fr_FR
  • A full akawaka:opensearch:reindex builds the new index with the current synonyms.

Known limit: OpenSearch only reloads synonyms by closing the index briefly (about 0.5 s). Searches made through the plugin retry transparently during that window (measured: 0 failed searches on 20 000 documents), but other clients querying the alias directly may get an index_closed_exception.

Incremental indexing

Once an index exists (akawaka:opensearch:reindex), it follows the catalog on its own: a Doctrine listener notices the changes of products, translations, variants, prices, stock, attributes, images, product taxons and taxons, then asks for the matching documents to be updated. One message is sent per flush, whatever the number of entities that changed.

Change Effect on the index
product created / modified document indexed or updated
product disabled, removed from a channel, or deleted document removed
price, stock, option, attribute, image document updated
taxon renamed or deleted documents of its products (and of its sub-taxons) updated
# config/packages/akawaka_sylius_open_search.yaml
akawaka_sylius_open_search:
    indexing:
        incremental:
            enabled: true      # false: no listener, only akawaka:opensearch:reindex updates the indices
            transport: ~       # e.g. "main": updates are handled by a Messenger worker
    synonyms:
        sync_on_change: true   # false: no listener, use akawaka:opensearch:synonyms:sync
  • Without transport the update is made right after the flush, in the same request. If OpenSearch is unreachable, the error is logged and the catalog change is still saved.
  • With transport the messages (SyncProducts, SyncTaxonProducts) are routed to that Messenger transport; start a worker with bin/console messenger:consume main. Failed messages follow the retry and failure strategy of the transport.
  • The messages travel on a dedicated bus, akawaka_sylius_open_search.bus.
  • Messages already queued are still handled when the listener is disabled.

Known limits

  • Nothing is updated when an index does not exist yet, or while it is being rebuilt by a full reindex: run akawaka:opensearch:reindex again after a long outage or a bulk import made with raw SQL.
  • Catalog promotions applied by Sylius' own workers update prices through Doctrine, so they are followed too, but each batch generates its own messages: prefer an asynchronous transport on busy shops.
  • With a transport that is not on the database connection (AMQP, Redis...), a very fast worker may read a product before the transaction that changed it is committed.

Search index administration

Search → Index status shows, for every channel and locale, whether the index exists, how many documents it holds and whether the synonyms of the administration are applied to it. Buttons rebuild one index, rebuild everything, or apply the synonyms.

  • Without indexing.incremental.transport a rebuild runs during the request (fine for small catalogs; it can exceed the PHP time limit on large ones).
  • With a transport the request only schedules the rebuild, and a worker runs it: bin/console messenger:consume main.
  • When OpenSearch is unreachable the page says so instead of failing.

Browser test: BASE_URL=http://127.0.0.1:8080 node tests/E2E/search_index.mjs.

Development environment

Run composer create-project sylius/plugin-skeleton ProjectName.

Traditional

  1. From the plugin skeleton root directory, run the following commands:

    (cd vendor/sylius/test-application && yarn install)
    (cd vendor/sylius/test-application && yarn build)
    vendor/bin/console assets:install
    
    vendor/bin/console doctrine:database:create
    vendor/bin/console doctrine:migrations:migrate -n
    # Optionally load data fixtures
    vendor/bin/console sylius:fixtures:load -n

To be able to set up a plugin's database, remember to configure your database credentials in tests/TestApplication/.env and tests/TestApplication/.env.test.

  1. Run your local server:

    symfony server:ca:install
    symfony server:start -d
  2. Open your browser and navigate to https://localhost:8000.

Docker

  1. Execute make init to initialize the container and install the dependencies.

  2. Execute make database-init to create the database and run migrations.

  3. (Optional) Execute make load-fixtures to load the fixtures.

  4. Your app is available at http://localhost.

Usage

Running plugin tests

  • PHPUnit

    vendor/bin/phpunit
  • Behat (non-JS scenarios)

    vendor/bin/behat --strict --tags="~@javascript&&~@mink:chromedriver"
  • Behat (JS scenarios)

    1. Install Symfony CLI command.

    2. Start Headless Chrome:

    google-chrome-stable --enable-automation --disable-background-networking --no-default-browser-check --no-first-run --disable-popup-blocking --disable-default-apps --allow-insecure-localhost --disable-translate --disable-extensions --no-sandbox --enable-features=Metal --headless --remote-debugging-port=9222 --window-size=2880,1800 --proxy-server='direct://' --proxy-bypass-list='*' http://127.0.0.1
    1. Install SSL certificates (only once needed) and run test application's webserver on 127.0.0.1:8080:
    symfony server:ca:install
    APP_ENV=test symfony server:start --port=8080 --daemon
    1. Run Behat:
    vendor/bin/behat --strict --tags="@javascript,@mink:chromedriver"
  • Static Analysis

    • PHPStan

      vendor/bin/phpstan analyse -c phpstan.neon -l max src/  
  • Coding Standard

    vendor/bin/ecs check

Opening Sylius with your plugin

  • Using test environment:

    APP_ENV=test vendor/bin/console sylius:fixtures:load -n
    APP_ENV=test symfony server:start -d
  • Using dev environment:

    vendor/bin/console sylius:fixtures:load -n
    symfony server:start -d