Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Extract Meilisearch search provider into spree_meilisearch gem (#14428)

Damian Legawiec0218352ddf37
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index f22b1c024f..25234c2d3f 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -56,7 +56,7 @@ jobs:
- name: Install all project dependencies
run: |
- for project in core api emails providers/easypost dashboard; do
+ for project in core api emails providers/easypost providers/meilisearch dashboard; do
echo "--- Installing gems for $project ---"
cd spree/$project
bundle config set --local path ${{ github.workspace }}/vendor/bundle
@@ -101,7 +101,7 @@ jobs:
- name: Install all project dependencies
run: |
- for project in core api emails providers/easypost dashboard; do
+ for project in core api emails providers/easypost providers/meilisearch dashboard; do
echo "--- Installing gems for $project ---"
cd spree/$project
bundle config set --local path ${{ github.workspace }}/vendor/bundle
@@ -129,8 +129,11 @@ jobs:
- { project: api, shard: 1, total_shards: 1, procs: 4 }
# emails: 1 runner × 2 procs (tiny suite)
- { project: emails, shard: 1, total_shards: 1, procs: 2 }
- # easypost: 1 runner × 2 procs (tiny suite — provider gem)
- - { project: easypost, dir: providers/easypost, shard: 1, total_shards: 1, procs: 2 }
+ # providers: 1 runner × 2 procs — every provider gem shares a lane.
+ # The suites are small, so a runner each cost more in queue time than
+ # they saved. This is also the only job with the Meilisearch service,
+ # so spree_meilisearch's integration spec runs here.
+ - { project: providers, dirs: "providers/easypost providers/meilisearch", shard: 1, total_shards: 1, procs: 2 }
# dashboard: 1 runner × 2 procs (tiny suite — SPA host)
- { project: dashboard, shard: 1, total_shards: 1, procs: 2 }
services:
@@ -193,42 +196,54 @@ jobs:
version: 1
- name: Install dependencies
+ env:
+ SUITE_DIRS: ${{ matrix.dirs || matrix.project }}
run: |
cd spree
bundle config set --local path ${{ github.workspace }}/vendor/bundle
bundle install
- cd ${{ matrix.dir || matrix.project }}
- bundle config set --local path ${{ github.workspace }}/vendor/bundle
- bundle install
+ for suite_dir in $SUITE_DIRS; do
+ (cd "$suite_dir" \
+ && bundle config set --local path ${{ github.workspace }}/vendor/bundle \
+ && bundle install)
+ done
- name: Setup test app
- working-directory: spree/${{ matrix.dir || matrix.project }}
+ working-directory: spree
+ env:
+ SUITE_DIRS: ${{ matrix.dirs || matrix.project }}
run: |
- if [[ "${{ matrix.project }}" == "core" || "${{ matrix.project }}" == "api" ]]; then
- bundle exec --gemfile=${{ github.workspace }}/spree/Gemfile rake test_app
- else
- bundle exec rake test_app
- fi
+ for suite_dir in $SUITE_DIRS; do
+ if [[ "${{ matrix.project }}" == "core" || "${{ matrix.project }}" == "api" ]]; then
+ (cd "$suite_dir" && bundle exec --gemfile=${{ github.workspace }}/spree/Gemfile rake test_app)
+ else
+ (cd "$suite_dir" && bundle exec rake test_app)
+ fi
+ done
- name: Setup parallel databases
- working-directory: spree/${{ matrix.dir || matrix.project }}
- run: bundle exec rake parallel_setup[${{ matrix.procs }}]
+ working-directory: spree
+ env:
+ SUITE_DIRS: ${{ matrix.dirs || matrix.project }}
+ run: |
+ for suite_dir in $SUITE_DIRS; do
+ (cd "$suite_dir" && bundle exec rake parallel_setup[${{ matrix.procs }}])
+ done
- name: Run tests
- working-directory: spree/${{ matrix.dir || matrix.project }}
+ working-directory: spree
env:
SHARD: ${{ matrix.shard }}
TOTAL_SHARDS: ${{ matrix.total_shards }}
PROCS: ${{ matrix.procs }}
- RSPEC_OPTS: >-
- --order random
- --format progress
- -r rspec_junit_formatter
- --format RspecJunitFormatter
- -o ${{ github.workspace }}/tmp/test-results/rspec/${{ matrix.project }}-${{ matrix.shard }}-$TEST_ENV_NUMBER.xml
+ SUITE_DIRS: ${{ matrix.dirs || matrix.project }}
run: |
mkdir -p ${{ github.workspace }}/tmp/test-results/rspec
- bundle exec rake parallel_shard
+ for suite_dir in $SUITE_DIRS; do
+ suite_name=$(basename "$suite_dir")
+ RSPEC_OPTS="--order random --format progress -r rspec_junit_formatter --format RspecJunitFormatter -o ${{ github.workspace }}/tmp/test-results/rspec/${suite_name}-${{ matrix.shard }}-\$TEST_ENV_NUMBER.xml" \
+ bash -c "cd '$suite_dir' && bundle exec rake parallel_shard"
+ done
- name: Upload coverage to Codecov
if: always() && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)
@@ -273,8 +288,10 @@ jobs:
- { project: api, shard: 1, total_shards: 1, procs: 4 }
# emails: 1 runner × 2 procs
- { project: emails, shard: 1, total_shards: 1, procs: 2 }
- # easypost: 1 runner × 2 procs (tiny suite — provider gem)
- - { project: easypost, dir: providers/easypost, shard: 1, total_shards: 1, procs: 2 }
+ # providers: 1 runner × 2 procs — every provider gem shares a lane.
+ # No Meilisearch service here, so spree_meilisearch's integration spec
+ # skips itself; its unit specs still run against MySQL.
+ - { project: providers, dirs: "providers/easypost providers/meilisearch", shard: 1, total_shards: 1, procs: 2 }
# dashboard: 1 runner × 2 procs (tiny suite — SPA host)
- { project: dashboard, shard: 1, total_shards: 1, procs: 2 }
services:
@@ -320,42 +337,54 @@ jobs:
version: 1
- name: Install dependencies
+ env:
+ SUITE_DIRS: ${{ matrix.dirs || matrix.project }}
run: |
cd spree
bundle config set --local path ${{ github.workspace }}/vendor/bundle
bundle install
- cd ${{ matrix.dir || matrix.project }}
- bundle config set --local path ${{ github.workspace }}/vendor/bundle
- bundle install
+ for suite_dir in $SUITE_DIRS; do
+ (cd "$suite_dir" \
+ && bundle config set --local path ${{ github.workspace }}/vendor/bundle \
+ && bundle install)
+ done
- name: Setup test app
- working-directory: spree/${{ matrix.dir || matrix.project }}
+ working-directory: spree
+ env:
+ SUITE_DIRS: ${{ matrix.dirs || matrix.project }}
run: |
- if [[ "${{ matrix.project }}" == "core" || "${{ matrix.project }}" == "api" ]]; then
- bundle exec --gemfile=${{ github.workspace }}/spree/Gemfile rake test_app
- else
- bundle exec rake test_app
- fi
+ for suite_dir in $SUITE_DIRS; do
+ if [[ "${{ matrix.project }}" == "core" || "${{ matrix.project }}" == "api" ]]; then
+ (cd "$suite_dir" && bundle exec --gemfile=${{ github.workspace }}/spree/Gemfile rake test_app)
+ else
+ (cd "$suite_dir" && bundle exec rake test_app)
+ fi
+ done
- name: Setup parallel databases
- working-directory: spree/${{ matrix.dir || matrix.project }}
- run: bundle exec rake parallel_setup[${{ matrix.procs }}]
+ working-directory: spree
+ env:
+ SUITE_DIRS: ${{ matrix.dirs || matrix.project }}
+ run: |
+ for suite_dir in $SUITE_DIRS; do
+ (cd "$suite_dir" && bundle exec rake parallel_setup[${{ matrix.procs }}])
+ done
- name: Run tests
- working-directory: spree/${{ matrix.dir || matrix.project }}
+ working-directory: spree
env:
SHARD: ${{ matrix.shard }}
TOTAL_SHARDS: ${{ matrix.total_shards }}
PROCS: ${{ matrix.procs }}
- RSPEC_OPTS: >-
- --order random
- --format progress
- -r rspec_junit_formatter
- --format RspecJunitFormatter
- -o ${{ github.workspace }}/tmp/test-results/rspec/${{ matrix.project }}-${{ matrix.shard }}-$TEST_ENV_NUMBER.xml
+ SUITE_DIRS: ${{ matrix.dirs || matrix.project }}
run: |
mkdir -p ${{ github.workspace }}/tmp/test-results/rspec
- bundle exec rake parallel_shard
+ for suite_dir in $SUITE_DIRS; do
+ suite_name=$(basename "$suite_dir")
+ RSPEC_OPTS="--order random --format progress -r rspec_junit_formatter --format RspecJunitFormatter -o ${{ github.workspace }}/tmp/test-results/rspec/${suite_name}-${{ matrix.shard }}-\$TEST_ENV_NUMBER.xml" \
+ bash -c "cd '$suite_dir' && bundle exec rake parallel_shard"
+ done
- name: Upload test results
if: always()
diff --git a/CLAUDE.md b/CLAUDE.md
index 17e4a820df..0d36fa6aa3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -83,6 +83,7 @@ Shipped plans:
| `spree/api` | Ruby gem — Store & Admin REST APIs (`spree_api`) |
| `spree/emails` | Ruby gem — transactional emails (optional). Rebuilt + modernized in 5.6. The default email stack for installations without a storefront app (e.g. mobile apps); headless storefronts may instead own consumer emails via webhooks. |
| `spree/providers/easypost` | Ruby gem (`spree_easypost`, optional) — reference `DeliveryRateProvider` + `FulfillmentProvider`: live EasyPost rates, label purchase/refund, credentials via `SpreeEasyPost::Integration`. Provider gems live under `spree/providers/` (stripe/adyen/avalara land there too); gem names stay flat. |
+| `spree/providers/meilisearch` | Ruby gem (`spree_meilisearch`, optional) — `SpreeMeilisearch::SearchProvider` + `SpreeMeilisearch::ProductPresenter`: typo-tolerant product search, disjunctive facets and merchant-ordered grouping pages. Extracted from core in 6.0; credentials come from `MEILISEARCH_URL`/`MEILISEARCH_API_KEY` (index is installation-wide infrastructure, not a per-store `Integration`). |
| `spree/dashboard` | Ruby gem (`spree_dashboard`, optional) — hosts a built React Dashboard at `/dashboard` from `Spree::Dashboard.dist_path` / `SPREE_DASHBOARD_DIST_PATH` (single-node topology). Successor slot to `spree_admin` at 6.0. |
| `packages/dashboard` | `@spree/dashboard` — React SPA admin dashboard (Spree 6.0, replaces `spree/admin`). The deployable app shell, routes, schemas, resource hooks, locales. |
| `packages/dashboard-ui` | `@spree/dashboard-ui` — design system. Shadcn primitives + headless composed components + tokens. Source-only; consumer compiles via Vite/Tailwind. **Components are headless: data comes via props, no provider/hook imports.** |
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index eaf8366253..bb9e8553c9 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -438,6 +438,26 @@ Every rename keeps the legacy name working for one release with a deprecation wa
| `.with_metafield_key`, `.with_metafield_key_value` | `.with_custom_field_key`, `.with_custom_field_key_value` |
| `Spree.metafields` | `Spree.custom_fields` |
| `CustomFieldDefinition#name`, `#metafield_type`, `#display_on` | `#label`, `#field_type`, `#storefront_visible` (columns renamed) |
+| `Spree::SearchProvider::Meilisearch` | `SpreeMeilisearch::SearchProvider` (moved to the `spree_meilisearch` gem) |
+| `Spree::SearchProvider::ProductPresenter` | `SpreeMeilisearch::ProductPresenter` (moved to the `spree_meilisearch` gem) |
+
+## Meilisearch moved to its own gem
+
+Meilisearch is no longer part of `spree_core`. Stores using the Database provider (the default) need to do nothing.
+
+If you set `Spree.search_provider` to the Meilisearch provider, add the gem and update the class name:
+
+```ruby
+# Gemfile
+gem 'spree_meilisearch'
+
+# config/initializers/spree.rb
+Spree.search_provider = 'SpreeMeilisearch::SearchProvider'
+```
+
+Your `MEILISEARCH_URL` and `MEILISEARCH_API_KEY` settings are unchanged, and **no reindex is needed** — the documents have the same shape. Applications that subclassed the document presenter should inherit from `SpreeMeilisearch::ProductPresenter` instead.
+
+The old class names keep working for one release, so an application that only names them in an initializer boots with a deprecation warning rather than an error — but the gem must be installed either way, since the classes now live there.
## Staff permissions: roles are data
diff --git a/docs/plans/5.4-search-provider.md b/docs/plans/5.4-search-provider.md
index 378da17794..acdcbc06d4 100644
--- a/docs/plans/5.4-search-provider.md
+++ b/docs/plans/5.4-search-provider.md
@@ -1,6 +1,6 @@
# Search Provider Interface
-**Status:** 5.4 portion shipped (`Spree::SearchProvider::Base/Database/Meilisearch`, PgSearch removed, `add_search_scope` removed); 6.0 metafield faceting pending. 2026-07-19: spree-starter / create-spree-app no longer provision Meilisearch by default — the Database provider is the out-of-the-box default everywhere; Meilisearch is a documented opt-in — installs: uncomment the compose blocks + set `MEILISEARCH_URL`; monorepo dev server: `SPREE_MEILISEARCH=1 pnpm server:dev` (chains `scripts/docker-compose.meilisearch.yml`); either way run `spree:search:reindex` once on first boot. See decisions.md.
+**Status:** 5.4 portion shipped (`Spree::SearchProvider::Base/Database/Meilisearch`, PgSearch removed, `add_search_scope` removed); 6.0 metafield faceting pending. 2026-07-19: spree-starter / create-spree-app no longer provision Meilisearch by default — the Database provider is the out-of-the-box default everywhere; Meilisearch is a documented opt-in — installs: uncomment the compose blocks + set `MEILISEARCH_URL`; monorepo dev server: `SPREE_MEILISEARCH=1 pnpm server:dev` (chains `scripts/docker-compose.meilisearch.yml`); either way run `spree:search:reindex` once on first boot. See decisions.md. **2026-08-12:** the Meilisearch provider left core for its own `spree_meilisearch` gem (`spree/providers/meilisearch`), as this plan always intended — `Spree::SearchProvider::Meilisearch` → `SpreeMeilisearch::SearchProvider` and the document presenter moved with it (`Spree::Dependencies.search_product_presenter` now has NO core default; the gem registers it, and `#search_presentation` raises a directive error without one). Core keeps the interface (`Base`/`Database`/`SearchResult`/`FiltersResult`/`CustomFieldSchema`), the indexing jobs and the reindex task; the `meilisearch` gem is no longer a core dependency. Old constants resolve with a deprecation warning through `Spree::SearchProvider.const_missing` until 6.1.
**Target:** Spree 5.4 (provider + DB provider + PgSearch removal + add_search_scope removal + Meilisearch provider ✓), 6.0 (metafield faceting)
**Depends on:** None for 5.4. ProductType (6.0-product-types.md) for metafield faceting in 6.0.
**Author:** Damian + Claude
@@ -128,7 +128,7 @@ Consistent with existing `products_finder`, `products_sorter` pattern.
- **Remove PgSearch scopes from Product** — `search_by_name` (trigram) removed. ILIKE on name is sufficient for the Database provider.
- **Remove PgSearch scopes from Variant** — `search_by_sku`, `search_by_sku_or_options` replaced by ILIKE equivalents.
- **Remove `pg_search` from gemspec.** Currently an optional dependency. No migration needed — it's a gem removal.
-- **Meilisearch is the recommended upgrade path.** For merchants who want typo tolerance, stemming, and relevance tuning, install `spree_search_meilisearch`. This gives them far more than PgSearch ever did.
+- **Meilisearch is the recommended upgrade path.** For merchants who want typo tolerance, stemming, and relevance tuning, install `spree_meilisearch`. This gives them far more than PgSearch ever did.
### Remove `add_search_scope` macro
@@ -139,7 +139,7 @@ Consistent with existing `products_finder`, `products_sorter` pattern.
### Meilisearch is the recommended external provider
-- **Ship `spree_search_meilisearch` as an official Spree gem.** Uses `meilisearch-ruby` (raw client), NOT `meilisearch-rails` (no model-level overrides).
+- **Ship `spree_meilisearch` as an official Spree gem.** Uses `meilisearch-ruby` (raw client), NOT `meilisearch-rails` (no model-level overrides).
- **Index all products** (all statuses). Store API applies `.active` scope to the base AR scope before passing to the provider. Admin passes all products. The provider searches the full index, AR scope intersects for visibility.
- **Meilisearch handles search + filtering + faceting in one call** — replaces both Ransack filtering and `FiltersAggregator` with Meilisearch's native capabilities. Adjusted facet counts come for free.
- **Docs recommend Meilisearch** as the production search solution. The Database provider is for development and small catalogs.
@@ -293,7 +293,7 @@ module Spree
end
```
-### Meilisearch Provider (`spree_search_meilisearch` gem)
+### Meilisearch Provider (`spree_meilisearch` gem)
Uses `meilisearch-ruby` (raw HTTP client). No model-level overrides.
@@ -627,9 +627,9 @@ type ProductFilter = PriceRangeFilter | AvailabilityFilter | OptionFilter | Cate
- Add `SearchIndexable` concern to Product (no-op for database provider)
- Add `rake spree:search:reindex` task
-### Phase 5: Meilisearch provider (official gem)
+### Phase 5: Meilisearch provider (official gem) ✓ shipped
-- Create `spree_search_meilisearch` gem (official, maintained by Spree team)
+- Create `spree_meilisearch` gem (official, maintained by Spree team) ✓
- Uses `meilisearch-ruby` gem (raw client, no model-level overrides)
- Indexes all products (all statuses) — storefront scopes handle visibility
- Implements: search + filter + faceted aggregation with adjusted counts in one call
diff --git a/spree/Rakefile b/spree/Rakefile
index de097ca558..b767205f85 100644
--- a/spree/Rakefile
+++ b/spree/Rakefile
@@ -9,6 +9,12 @@ end
SPREE_CORE_GEMS = %w(core api).freeze
SPREE_OPTIONAL_GEMS = %w(emails dashboard).freeze
+# Provider gems sit one directory deeper and their gem name doesn't match the
+# directory, so they carry the path explicitly.
+SPREE_PROVIDER_GEMS = {
+ 'spree_easypost' => 'providers/easypost',
+ 'spree_meilisearch' => 'providers/meilisearch'
+}.freeze
task default: :test
@@ -24,6 +30,11 @@ task test: :test_app do
sh 'rspec'
end
end
+ SPREE_PROVIDER_GEMS.each_value do |path|
+ Dir.chdir("#{File.dirname(__FILE__)}/#{path}") do
+ sh 'rspec'
+ end
+ end
end
desc "Generates a dummy app for testing for every Spree engine"
@@ -38,6 +49,11 @@ task :test_app do
sh 'rake test_app'
end
end
+ SPREE_PROVIDER_GEMS.each_value do |path|
+ Dir.chdir("#{File.dirname(__FILE__)}/#{path}") do
+ sh 'rake test_app'
+ end
+ end
end
desc "clean the whole repository by removing all the generated files"
@@ -56,6 +72,11 @@ task :clean do
rm_rf "#{gem_name}/pkg"
rm_rf "#{gem_name}/spec/dummy"
end
+ SPREE_PROVIDER_GEMS.each_value do |path|
+ rm_f "#{path}/Gemfile.lock"
+ rm_rf "#{path}/pkg"
+ rm_rf "#{path}/spec/dummy"
+ end
end
namespace :gem do
@@ -86,6 +107,13 @@ namespace :gem do
mv "spree_#{gem_name}-#{version}.gem", pkgdir
end
end
+
+ SPREE_PROVIDER_GEMS.each do |gem_name, path|
+ Dir.chdir(path) do
+ sh "gem build #{gem_name}.gemspec"
+ mv "#{gem_name}-#{version}.gem", pkgdir
+ end
+ end
end
desc "Install all spree gems"
@@ -103,6 +131,10 @@ namespace :gem do
SPREE_OPTIONAL_GEMS.each do |gem_name|
sh "gem install spree_#{gem_name}-#{version}.gem"
end
+
+ SPREE_PROVIDER_GEMS.each_key do |gem_name|
+ sh "gem install #{gem_name}-#{version}.gem"
+ end
end
end
@@ -119,6 +151,10 @@ namespace :gem do
SPREE_OPTIONAL_GEMS.each do |gem_name|
sh "gem push spree_#{gem_name}-#{version}.gem"
end
+
+ SPREE_PROVIDER_GEMS.each_key do |gem_name|
+ sh "gem push #{gem_name}-#{version}.gem"
+ end
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
index 8b1b2a7813..a042c26253 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
@@ -490,140 +490,5 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
expect(controller.send(:current_currency)).to eq('USD')
end
end
-
- context 'with Meilisearch search provider' do
- let(:mock_client) { instance_double(::Meilisearch::Client) }
- let(:mock_index) { double('Meilisearch::Index') }
-
- before do
- allow(Spree).to receive(:search_provider).and_return('Spree::SearchProvider::Meilisearch')
- allow(::Meilisearch::Client).to receive(:new).and_return(mock_client)
- allow(mock_client).to receive(:index).and_return(mock_index)
- end
-
- after do
- allow(Spree).to receive(:search_provider).and_call_original
- end
-
- it 'searches via Meilisearch when q[search] is present' do
- allow(mock_index).to receive(:search).and_return({
- 'hits' => [{ 'product_id' => product.prefixed_id }],
- 'totalHits' => 1,
- 'facetDistribution' => {}
- })
-
- get :index, params: { q: { search: 'shirt' } }
-
- expect(response).to have_http_status(:ok)
- expect(mock_index).to have_received(:search).with('shirt', hash_including(:page, :hitsPerPage))
-
- ids = json_response['data'].map { |p| p['id'] }
- expect(ids).to include(product.prefixed_id)
- expect(ids).not_to include(product2.prefixed_id)
- end
-
- it 'respects AR scope visibility (does not return draft products from Meilisearch)' do
- allow(mock_index).to receive(:search).and_return({
- 'hits' => [{ 'product_id' => product.prefixed_id }, { 'product_id' => draft_product.prefixed_id }],
- 'totalHits' => 2,
- 'facetDistribution' => {}
- })
-
- get :index, params: { q: { search: 'test' } }
-
- expect(response).to have_http_status(:ok)
- ids = json_response['data'].map { |p| p['id'] }
- expect(ids).to include(product.prefixed_id)
- expect(ids).not_to include(draft_product.prefixed_id)
- end
-
- it 'uses Meilisearch for browsing without search query' do
- allow(mock_index).to receive(:search).and_return({
- 'hits' => [{ 'product_id' => product.prefixed_id }, { 'product_id' => product2.prefixed_id }],
- 'totalHits' => 2,
- 'facetDistribution' => {}
- })
-
- get :index
-
- expect(response).to have_http_status(:ok)
- expect(mock_index).to have_received(:search)
- expect(json_response['data'].size).to eq(2)
- end
-
- it 'filters by current locale in Meilisearch' do
- allow(mock_index).to receive(:search).and_return({
- 'hits' => [{ 'product_id' => product.prefixed_id }],
- 'totalHits' => 1,
- 'facetDistribution' => {}
- })
-
- get :index
-
- expect(response).to have_http_status(:ok)
- expect(mock_index).to have_received(:search).with(anything, hash_including(
- filter: include("locale = '#{store.default_locale}'")
- ))
- end
-
- it 'filters by current currency in Meilisearch' do
- allow(mock_index).to receive(:search).and_return({
- 'hits' => [{ 'product_id' => product.prefixed_id }],
- 'totalHits' => 1,
- 'facetDistribution' => {}
- })
-
- get :index
-
- expect(response).to have_http_status(:ok)
- expect(mock_index).to have_received(:search).with(anything, hash_including(
- filter: include("currency = '#{store.default_currency}'")
- ))
- end
-
- it 'filters by store_id in Meilisearch' do
- allow(mock_index).to receive(:search).and_return({
- 'hits' => [{ 'product_id' => product.prefixed_id }],
- 'totalHits' => 1,
- 'facetDistribution' => {}
- })
-
- get :index
-
- expect(response).to have_http_status(:ok)
- expect(mock_index).to have_received(:search).with(anything, hash_including(
- filter: include("store_ids = '#{store.id}'")
- ))
- end
-
- it 'always filters by active status in Meilisearch' do
- allow(mock_index).to receive(:search).and_return({
- 'hits' => [{ 'product_id' => product.prefixed_id }],
- 'totalHits' => 1,
- 'facetDistribution' => {}
- })
-
- get :index
-
- expect(response).to have_http_status(:ok)
- expect(mock_index).to have_received(:search).with(anything, hash_including(
- filter: include("status = 'active'")
- ))
- end
-
- it 'preserves Meilisearch sort order in the response' do
- allow(mock_index).to receive(:search).and_return({
- 'hits' => [{ 'product_id' => product2.prefixed_id }, { 'product_id' => product.prefixed_id }],
- 'totalHits' => 2,
- 'facetDistribution' => {}
- })
-
- get :index, params: { sort: '-price' }
-
- expect(response).to have_http_status(:ok)
- ids = json_response['data'].map { |p| p['id'] }
- expect(ids).to eq([product2.prefixed_id, product.prefixed_id])
- end
- end
end
end
diff --git a/spree/common_spree_dependencies.rb b/spree/common_spree_dependencies.rb
index d8c7660fab..1913049264 100644
--- a/spree/common_spree_dependencies.rb
+++ b/spree/common_spree_dependencies.rb
@@ -17,8 +17,6 @@ platforms :ruby do
gem 'sqlite3', '>= 2.0'
end
-gem 'meilisearch', '>= 0.28'
-
group :test do
gem 'parallel_tests'
gem 'database_cleaner-active_record'
diff --git a/spree/core/app/models/concerns/spree/search_indexable.rb b/spree/core/app/models/concerns/spree/search_indexable.rb
index dcda015282..b102911022 100644
--- a/spree/core/app/models/concerns/spree/search_indexable.rb
+++ b/spree/core/app/models/concerns/spree/search_indexable.rb
@@ -29,7 +29,10 @@ module Spree
# => { id: 1, name: "Shirt", price_USD: 19.99, ... }
def search_presentation(store = nil)
store ||= Spree::Current.store
- Spree::Dependencies.search_product_presenter_class.new(self, store).call
+ presenter_class = Spree::Dependencies.search_product_presenter_class
+ raise Spree::DependencyError, 'No search product presenter is configured. Install a search provider gem (e.g. spree_meilisearch) or set Spree::Dependencies.search_product_presenter.' if presenter_class.nil?
+
+ presenter_class.new(self, store).call
end
# Remove this record from search index synchronously (inline, no job).
diff --git a/spree/core/app/models/spree/search_provider.rb b/spree/core/app/models/spree/search_provider.rb
new file mode 100644
index 0000000000..5b87a9db3b
--- /dev/null
+++ b/spree/core/app/models/spree/search_provider.rb
@@ -0,0 +1,29 @@
+module Spree
+ module SearchProvider
+ # Meilisearch moved out of core into the spree_meilisearch gem at 6.0, taking
+ # the document presenter with it. Applications configure the provider by
+ # class name, so resolve the old constants to the new ones for one release
+ # rather than failing at boot with a bare NameError.
+ MOVED_TO_SPREE_MEILISEARCH = {
+ Meilisearch: 'SpreeMeilisearch::SearchProvider',
+ ProductPresenter: 'SpreeMeilisearch::ProductPresenter'
+ }.freeze
+
+ def self.const_missing(name)
+ replacement = MOVED_TO_SPREE_MEILISEARCH[name]
+ return super if replacement.nil?
+
+ unless Object.const_defined?(replacement)
+ raise NameError, "Spree::SearchProvider::#{name} moved to #{replacement} in Spree 6.0. " \
+ "Add `gem 'spree_meilisearch'` to your Gemfile."
+ end
+
+ Spree::Deprecation.warn(
+ "Spree::SearchProvider::#{name} is deprecated and will be removed in Spree 6.1. " \
+ "Use #{replacement} instead."
+ ) if defined?(Spree::Deprecation)
+
+ replacement.constantize
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/search_provider/meilisearch.rb b/spree/core/app/models/spree/search_provider/meilisearch.rb
deleted file mode 100644
index 625e02f79f..0000000000
--- a/spree/core/app/models/spree/search_provider/meilisearch.rb
+++ /dev/null
@@ -1,618 +0,0 @@
-require 'pagy/toolbox/paginators/meilisearch'
-
-module Spree
- module SearchProvider
- class Meilisearch < Base
- PREFIXED_ID_PATTERN = /\A[a-z]+_[A-Za-z0-9]+\z/
- ALLOWED_STATUSES = %w[active draft archived paused].freeze
- BUILT_IN_FILTERABLE_ATTRIBUTES = %w[product_id status in_stock preorder store_ids channel_ids locale currency available_on discontinue_on price category_ids collection_ids grouping_id tags option_value_ids].freeze
- CUSTOM_FIELD_RANGE_OPERATORS = { 'gt' => '>', 'gteq' => '>=', 'lt' => '<', 'lteq' => '<=' }.freeze
-
- def self.indexing_required?
- true
- end
-
- def initialize(store)
- super
- require 'meilisearch'
- rescue LoadError
- raise LoadError, "Add `gem 'meilisearch'` to your Gemfile to use the Meilisearch search provider"
- end
-
- def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
- page = [page.to_i, 1].max
- limit = limit.to_i.clamp(1, 100)
-
- filters = normalize_filters(filters)
- sort, filters = resolve_manual_sort(sort, filters)
-
- ms_result, _ = execute_search(query: query, filters: filters, sort: sort, page: page, limit: limit)
- return empty_result(scope, page, limit) unless ms_result
-
- # Hits have composite prefixed_id (prod_abc_en_USD), extract product_id (prod_abc)
- product_prefixed_ids = ms_result['hits'].map { |h| h['product_id'] }.uniq
- raw_ids = product_prefixed_ids.filter_map { |pid| Spree::Product.decode_prefixed_id(pid) }
-
- # Intersect with AR scope for security/visibility, preserving Meilisearch sort order.
- products = if raw_ids.any?
- records = scope.where(id: raw_ids).reorder(nil).index_by(&:id)
- raw_ids.filter_map { |id| records[id] }
- else
- scope.none
- end
-
- pagy = build_pagy(ms_result, page, limit)
-
- SearchResult.new(
- products: products,
- total_count: ms_result['totalHits'] || 0,
- pagy: pagy
- )
- end
-
- def filters(scope:, query: nil, filters: {})
- collection = filters.is_a?(Hash) ? (filters['_collection'] || filters[:_collection]) : nil
- default_sort = collection ? to_api_sort(collection.sort_order) : 'manual'
-
- ms_result, facet_distribution = execute_search(query: query, filters: filters, sort: nil, page: 1, limit: 0, return_facets: true)
-
- unless ms_result
- return FiltersResult.new(
- filters: [],
- sort_options: built_in_and_custom_field_sort_options,
- default_sort: default_sort,
- total_count: 0
- )
- end
-
- FiltersResult.new(
- filters: build_facet_response(facet_distribution),
- sort_options: built_in_and_custom_field_sort_options,
- default_sort: default_sort,
- total_count: ms_result['totalHits'] || 0
- )
- end
-
- def index(product)
- ensure_index_settings_once!
- documents = presenter_class.new(product, store).call
- # Delete first: membership docs use grouping-specific ids, so a product
- # that left a grouping would otherwise leave an orphaned stale doc.
- remove_by_id(product.prefixed_id)
- client.index(index_name).add_documents(documents, 'id')
- end
-
- def remove(product)
- remove_by_id(product.prefixed_id)
- end
-
- def index_batch(documents)
- return if documents.empty?
-
- client.index(index_name).add_documents(documents, 'id')
- end
-
- # Remove all documents for a product by its prefixed_id (e.g. 'prod_abc')
- def remove_by_id(prefixed_id)
- filter = "product_id = '#{sanitize_prefixed_id(prefixed_id)}'"
- client.index(index_name).delete_documents(filter: filter)
- rescue ::Meilisearch::ApiError => e
- raise unless e.http_code == 404
- end
-
- def reindex(scope = nil)
- full_reindex = scope.nil?
- scope ||= store.products
- @custom_field_schema = CustomFieldSchema.new
- ensure_index_settings!
-
- # On a full reindex, clear first so stale docs (e.g. membership docs for
- # removed groupings) don't linger; a scoped reindex keeps upsert semantics.
- client.index(index_name).delete_all_documents if full_reindex
-
- indexed = 0
- scope.reorder(id: :asc)
- .preload_associations_lazily
- .find_in_batches(batch_size: 500) do |batch|
- documents = batch.flat_map { |product| presenter_class.new(product, store).call }
- next if documents.empty?
-
- index_batch(documents)
- indexed += documents.size
-
- Rails.logger.info { "[Meilisearch] Enqueued #{documents.size} documents (#{indexed} total) for #{index_name}" }
- end
-
- Rails.logger.info { "[Meilisearch] Reindex complete: #{indexed} documents enqueued for #{index_name}" }
- indexed
- end
-
- # Configure index settings for filtering, sorting, and faceting.
- # Called automatically by reindex, but can be called separately.
- # Waits for all settings tasks to complete before returning so that
- # subsequent add_documents calls use the correct filterable/sortable attributes.
- def ensure_index_settings!
- index = client.index(index_name)
- tasks = []
- tasks << index.update_filterable_attributes(filterable_attributes)
- tasks << index.update_sortable_attributes(sortable_attributes)
- tasks << index.update_searchable_attributes(searchable_attributes)
- tasks << index.update_distinct_attribute(distinct_attribute)
- tasks.each { |task| task&.await }
- @index_settings_configured = true
- end
-
- # Lightweight guard — configures index settings once per provider instance.
- # Meilisearch settings updates are idempotent, so repeated calls are safe
- # but we avoid the overhead by memoizing.
- def ensure_index_settings_once!
- return if @index_settings_configured
-
- ensure_index_settings!
- end
-
- private
-
- # Normalize incoming filters to a plain, string-keyed Hash.
- def normalize_filters(filters)
- filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
- (filters || {}).stringify_keys
- end
-
- # Manual/position sort. When a single grouping is being viewed (in_collection
- # or in_category) and the effective sort is 'manual' — either requested, or
- # the grouping-page default (blank ⇒ manual) — query the per-grouping
- # membership docs: swap the membership filter for `grouping_id` and sort by
- # the scalar `position`. Without a grouping, 'manual' has nothing to order by,
- # so it falls back to Meilisearch default ranking.
- def resolve_manual_sort(sort, filters)
- grouping_id = filters['in_collection'] || filters['in_category']
- grouping_id = nil unless valid_prefixed_id?(grouping_id)
- sort = 'manual' if sort.blank? && grouping_id
-
- if sort == 'manual' && grouping_id
- filters = filters.except('in_collection', 'in_category').merge('grouping_id' => grouping_id)
- elsif sort == 'manual'
- sort = nil
- end
-
- [sort, filters]
- end
-
- # Execute a Meilisearch query. Returns [ms_result, facet_distribution].
- # facet_distribution is empty when return_facets is false. Returns nil on API error.
- def execute_search(query:, filters:, sort:, page:, limit:, return_facets: false)
- filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
- filters = (filters || {}).stringify_keys
-
- option_value_ids = extract_and_delete(filters, 'with_option_value_ids')
- grouped_options = group_option_values_by_type(Array(option_value_ids))
-
- base_conditions = build_filters(filters)
- option_conditions = build_grouped_option_conditions(grouped_options)
- all_conditions = base_conditions + option_conditions
-
- # Page-based (exhaustive) pagination — REQUIRED so `distinct` collapses
- # totalHits and facetDistribution to per-product counts. The offset/limit
- # ("estimatedTotalHits") mode does NOT apply distinct to the count or
- # facets, which over-counts the duplicated per-grouping membership docs.
- search_params = {
- filter: all_conditions,
- facets: return_facets ? facet_attributes : nil,
- sort: build_sort(sort),
- page: page,
- hitsPerPage: limit
- }.compact
-
- Rails.logger.debug { "[Meilisearch] index=#{index_name} query=#{query.inspect} #{search_params.compact.inspect}" }
-
- settings_refreshed = false
- begin
- if return_facets && grouped_options.any?
- queries = [{ indexUid: index_name, q: query.to_s, **search_params }]
- option_type_ids_ordered = grouped_options.keys
- option_type_ids_ordered.each do |option_type_id|
- without_this = build_grouped_option_conditions(grouped_options.except(option_type_id))
- queries << { indexUid: index_name, q: query.to_s, filter: base_conditions + without_this, facets: ['option_value_ids'], page: 1, hitsPerPage: 0 }
- end
-
- results = client.multi_search(queries)
- ms_result = results['results'][0]
- facet_distribution = merge_disjunctive_facets(ms_result, results['results'][1..], option_type_ids_ordered)
- else
- ms_result = client.index(index_name).search(query.to_s, search_params)
- facet_distribution = ms_result['facetDistribution'] || {}
- end
- rescue ::Meilisearch::ApiError => e
- # Self-heal when a newly added filterable attribute (e.g. `preorder`)
- # is referenced before the index settings were refreshed — otherwise
- # every search on an upgraded store returns empty until a reindex or
- # the next product write.
- if %w[invalid_search_filter invalid_search_sort].include?(e.code) && !settings_refreshed
- settings_refreshed = true
- ensure_index_settings!
- retry
- end
-
- Rails.logger.warn { "[Meilisearch] Search failed: #{e.message}. Run `rake spree:search:reindex` to initialize the index." }
- Rails.error.report(e, handled: true, context: { index: index_name, query: query })
- return nil
- end
-
- Rails.logger.debug { "[Meilisearch] #{ms_result['totalHits']} hits in #{ms_result['processingTimeMs']}ms" }
-
- [ms_result, facet_distribution]
- end
-
- def merge_disjunctive_facets(ms_result, disjunctive_results, option_type_ids_ordered)
- main_ov_dist = ms_result.dig('facetDistribution', 'option_value_ids') || {}
-
- all_ov_prefixed_ids = Set.new
- disjunctive_dists = {}
- disjunctive_results.each_with_index do |r, idx|
- dist = r.dig('facetDistribution', 'option_value_ids') || {}
- disjunctive_dists[option_type_ids_ordered[idx]] = dist
- all_ov_prefixed_ids.merge(dist.keys)
- end
-
- all_raw_ids = all_ov_prefixed_ids.filter_map { |pid| Spree::OptionValue.decode_prefixed_id(pid) }
- ov_to_type = Spree::OptionValue.where(id: all_raw_ids).pluck(:id, :option_type_id).to_h
- prefixed_to_type = all_ov_prefixed_ids.each_with_object({}) do |pid, h|
- raw = Spree::OptionValue.decode_prefixed_id(pid)
- h[pid] = ov_to_type[raw] if raw
- end
-
- merged_ov_dist = main_ov_dist.dup
- disjunctive_dists.each do |option_type_id, dist|
- dist.each do |pid, count|
- merged_ov_dist[pid] = count if prefixed_to_type[pid] == option_type_id
- end
- end
-
- (ms_result['facetDistribution'] || {}).merge('option_value_ids' => merged_ov_dist)
- end
-
- def presenter_class
- Spree::Dependencies.search_product_presenter_class
- end
-
- def client
- @client ||= ::Meilisearch::Client.new(
- ENV.fetch('MEILISEARCH_URL', 'http://localhost:7700'),
- ENV['MEILISEARCH_API_KEY']
- )
- end
-
- def index_name
- "#{store.code}_products"
- end
-
- def searchable_attributes
- %w[name description sku option_values category_names tags] + custom_field_schema.searchable_attribute_keys
- end
-
- def filterable_attributes
- BUILT_IN_FILTERABLE_ATTRIBUTES + custom_field_schema.filterable_attribute_keys
- end
-
- def sortable_attributes
- %w[name price created_at available_on units_sold_count position] + custom_field_schema.sortable_attribute_keys
- end
-
- # Facets stay built-in only — cf_* distributions aren't consumed by
- # +build_facet_response+, so requesting them would be wasted work.
- def facet_attributes
- BUILT_IN_FILTERABLE_ATTRIBUTES
- end
-
- # Collapses the per-grouping membership docs to one row per product on
- # non-grouping queries (shop-all, search, non-manual sorts). Facet counts
- # and totals honor distinct on Meilisearch >= 1.40.
- def distinct_attribute
- 'product_id'
- end
-
- # Sourced from Spree::Collection::SORT_ORDERS (matching FiltersAggregator) so
- # both providers advertise identical options — including 'manual'.
- def available_sort_options
- Spree::Collection::SORT_ORDERS.map { |sort_order| to_api_sort(sort_order) } + custom_field_schema.sort_ids
- end
-
- # Converts internal sort format ('price asc') to API format ('price', '-price').
- def to_api_sort(sort_value)
- return sort_value unless sort_value.to_s.include?(' ')
-
- field, direction = sort_value.split(' ', 2)
- direction == 'desc' ? "-#{field}" : field
- end
-
- def built_in_and_custom_field_sort_options
- Spree::Collection::SORT_ORDERS.map { |sort_order| { id: to_api_sort(sort_order), label: nil } } +
- custom_field_schema.sort_options
- end
-
- # Build Meilisearch filter conditions from API params.
- # Combines system scoping (always applied) with user-facing filters.
- def build_filters(filters)
- conditions = system_filter_conditions
- conditions.concat(user_filter_conditions(filters))
- conditions
- end
-
- # System scoping — always applied. Rarely overridden.
- # Mirrors the AR scope: store.products.active(currency) with locale.
- def system_filter_conditions
- now = Time.current
- conditions = []
- conditions << "store_ids = '#{store.id}'"
- conditions << "channel_ids = '#{Spree::Current.channel.id}'" if Spree::Current.channel
- conditions << "status = 'active'"
- conditions << "locale = '#{locale.to_s.gsub(/[^a-zA-Z_-]/, '')}'"
- conditions << "currency = '#{currency.to_s.gsub(/[^A-Z]/, '')}'"
- # Exclude future-dated products — mirrors
- # +Product.available(Time.current, include_preorderable: true)+. ISO 8601
- # strings sort lexicographically in chronological order, so the string
- # compare is sound; +NOT EXISTS+/+IS NULL+ keep the available_on clause
- # backward-compatible with legacy docs. The trailing +preorder = true+
- # keeps scheduled "coming soon" pre-orders searchable before their
- # publish date. It filters on the new +preorder+ attribute, so a
- # +rake spree:search:reindex+ (or the next product write, which refreshes
- # the index settings) is required after deploy before it takes effect.
- conditions << "(available_on NOT EXISTS OR available_on IS NULL OR available_on <= '#{now.iso8601}' OR preorder = true)"
- conditions << "(discontinue_on = 0 OR discontinue_on > #{now.to_i})"
- conditions
- end
-
- # User-facing filters — override to add custom filter pre/post processing.
- def user_filter_conditions(filters)
- conditions = []
- filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
- return conditions if filters.blank?
-
- filters.each do |key, value|
- next if value.blank?
-
- condition = build_filter_condition(key.to_s, value)
- if condition.is_a?(Array)
- conditions.concat(condition)
- elsif condition
- conditions << condition
- end
- end
-
- conditions
- end
-
- # Translate a single Ransack-style filter param into Meilisearch filter syntax.
- # Override in subclasses to handle custom filter keys — call super for built-in filters.
- def build_filter_condition(key, value)
- case key
- when 'price_gte'
- "price >= #{value.to_f}"
- when 'price_lte'
- "price <= #{value.to_f}"
- when 'in_stock'
- 'in_stock = true' if value.to_s != '0'
- when 'out_of_stock'
- 'in_stock = false' if value.to_s != '0'
- when 'in_category'
- "category_ids = '#{sanitize_prefixed_id(value)}'" if valid_prefixed_id?(value)
- when 'in_categories'
- parts = Array(value).filter_map { |id| "category_ids = '#{sanitize_prefixed_id(id)}'" if valid_prefixed_id?(id) }
- parts.length > 1 ? "(#{parts.join(' OR ')})" : parts.first
- when 'in_collection'
- "collection_ids = '#{sanitize_prefixed_id(value)}'" if valid_prefixed_id?(value)
- when 'grouping_id'
- "grouping_id = '#{sanitize_prefixed_id(value)}'" if valid_prefixed_id?(value)
- when 'with_option_value_ids'
- # Handled by grouped option conditions in search_and_filter — skip here
- nil
- else
- custom_field_filter_condition(key, value)
- end
- end
-
- # Meilisearch has stable filter operators for equality, ranges, and
- # EXISTS — but no string contains/starts/ends (CONTAINS is still
- # experimental), so those predicates are ignored here. The Database
- # provider supports the full predicate set.
- def custom_field_filter_condition(key, value)
- parsed = custom_field_schema.parse_filter(key)
- return nil unless parsed
-
- attribute = parsed[:definition].filter_key
- numeric = parsed[:definition].field_type == 'number'
-
- case parsed[:predicate]
- when 'present'
- "#{attribute} EXISTS"
- when 'blank'
- "#{attribute} NOT EXISTS"
- when 'eq', 'not_eq'
- operator = parsed[:predicate] == 'eq' ? '=' : '!='
- formatted = format_custom_field_filter_value(value, numeric)
- formatted && "#{attribute} #{operator} #{formatted}"
- when *CUSTOM_FIELD_RANGE_OPERATORS.keys
- return nil unless numeric
-
- formatted = format_custom_field_filter_value(value, numeric)
- formatted && "#{attribute} #{CUSTOM_FIELD_RANGE_OPERATORS[parsed[:predicate]]} #{formatted}"
- end
- end
-
- def format_custom_field_filter_value(value, numeric)
- if numeric
- Float(value.to_s, exception: false)&.to_s
- else
- "'#{escape_filter_string(value)}'"
- end
- end
-
- def escape_filter_string(value)
- value.to_s.gsub('\\') { '\\\\' }.gsub("'") { "\\'" }
- end
-
- # Group prefixed option value IDs by option type (single DB query).
- # Returns { option_type_id => ['optval_abc', 'optval_def'], ... }
- def group_option_values_by_type(prefixed_ids)
- prefixed_ids = prefixed_ids.flatten.compact.select { |id| valid_prefixed_id?(id) }
- return {} if prefixed_ids.empty?
-
- raw_ids = prefixed_ids.filter_map { |id| Spree::OptionValue.decode_prefixed_id(id) }
- Spree::OptionValue.where(id: raw_ids).group_by(&:option_type_id).transform_values { |ovs| ovs.map(&:prefixed_id) }
- end
-
- # Build Meilisearch filter conditions from grouped option values.
- # OR within each option type, AND across option types.
- def build_grouped_option_conditions(grouped)
- grouped.map do |_, prefixed_ids|
- parts = prefixed_ids.map { |id| "option_value_ids = '#{sanitize_prefixed_id(id)}'" }
- parts.length > 1 ? "(#{parts.join(' OR ')})" : parts.first
- end
- end
-
- def extract_and_delete(hash, *keys)
- keys.each do |key|
- value = hash.delete(key) || hash.delete(key.to_sym)
- return value if value.present?
- end
- nil
- end
-
- # Sort param to Meilisearch sort syntax.
- # Override in subclasses to handle custom sort keys — call super for built-in sorts.
- def build_sort(sort)
- return nil if sort.blank?
-
- sort_mapping(sort)
- end
-
- # Map a sort param to Meilisearch sort syntax.
- # Override in subclasses to add custom sorts — call super for built-in sorts.
- def sort_mapping(sort)
- case sort
- when 'manual' then ['position:asc']
- when 'price' then ['price:asc']
- when '-price' then ['price:desc']
- when 'name' then ['name:asc']
- when '-name' then ['name:desc']
- when '-available_on' then ['available_on:desc']
- when 'available_on' then ['available_on:asc']
- when 'best_selling' then ['units_sold_count:desc']
- else
- parsed = custom_field_schema.parse_sort(sort)
- parsed && ["#{parsed[:attribute]}:#{parsed[:direction]}"]
- end
- end
-
- # Transform Meilisearch facetDistribution into standard filter response format.
- # Override in subclasses to add custom facets — call super and append.
- def build_facet_response(facet_distribution)
- facets = []
- facets << build_price_facet(facet_distribution['price']) if facet_distribution['price'].present?
- facets << build_availability_facet(facet_distribution['in_stock']) if facet_distribution['in_stock'].present?
- facets.concat(build_option_facets(facet_distribution['option_value_ids'])) if facet_distribution['option_value_ids'].present?
- facets << build_category_facet(facet_distribution['category_ids']) if facet_distribution['category_ids'].present?
- facets.compact
- end
-
- def build_price_facet(distribution)
- amounts = distribution.keys.map(&:to_f)
- {
- id: 'price',
- type: 'price_range',
- min: amounts.min,
- max: amounts.max,
- currency: currency
- }
- end
-
- def build_availability_facet(distribution)
- {
- id: 'availability',
- type: 'availability',
- options: [
- { id: 'in_stock', count: distribution['true'] || 0 },
- { id: 'out_of_stock', count: distribution['false'] || 0 }
- ]
- }
- end
-
- def build_option_facets(distribution)
- prefixed_ids = distribution.keys
- raw_ids = prefixed_ids.filter_map { |pid| Spree::OptionValue.decode_prefixed_id(pid) }
- option_values = Spree::OptionValue.where(id: raw_ids).includes(:option_type).preload_associations_lazily.index_by(&:prefixed_id)
-
- # Group by option type
- by_option_type = {}
- distribution.each do |ov_prefixed_id, count|
- ov = option_values[ov_prefixed_id]
- next unless ov
-
- ot = ov.option_type
- by_option_type[ot] ||= []
- by_option_type[ot] << {
- id: ov.prefixed_id, name: ov.name, label: ov.label, position: ov.position,
- color_code: ov.color_code,
- image_url: ov.image.attached? ? Rails.application.routes.url_helpers.cdn_image_url(ov.image) : nil,
- count: count
- }
- end
-
- by_option_type.map do |option_type, values|
- {
- id: option_type.prefixed_id,
- type: 'option',
- name: option_type.name,
- label: option_type.label,
- kind: option_type.kind,
- options: values.sort_by { |o| o[:position] }
- }
- end
- end
-
- def build_category_facet(distribution)
- prefixed_ids = distribution.keys
- raw_ids = prefixed_ids.filter_map { |pid| Spree::Category.decode_prefixed_id(pid) }
- categories = Spree::Category.where(id: raw_ids).index_by(&:prefixed_id)
-
- {
- id: 'categories',
- type: 'category',
- options: distribution.filter_map do |prefixed_id, count|
- cat = categories[prefixed_id]
- next unless cat
-
- { id: cat.prefixed_id, name: cat.name, permalink: cat.permalink, count: count }
- end
- }
- end
-
- def build_pagy(ms_result, page, limit)
- fake_result = Struct.new(:raw_answer).new({
- 'totalHits' => ms_result['totalHits'] || 0,
- 'hitsPerPage' => limit,
- 'page' => page
- })
-
- Pagy::MeilisearchPaginator.paginate(fake_result, {})
- end
-
- def empty_result(scope, page, limit)
- SearchResult.new(
- products: scope.none,
- total_count: 0,
- pagy: Pagy::Offset.new(count: 0, page: page, limit: limit)
- )
- end
-
- def valid_prefixed_id?(value)
- value.to_s.match?(PREFIXED_ID_PATTERN)
- end
-
- def sanitize_prefixed_id(value)
- value.to_s.gsub(/[^a-zA-Z0-9_]/, '')
- end
- end
- end
-end
diff --git a/spree/core/app/presenters/spree/search_provider/product_presenter.rb b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
deleted file mode 100644
index ae05dd5dcd..0000000000
--- a/spree/core/app/presenters/spree/search_provider/product_presenter.rb
+++ /dev/null
@@ -1,218 +0,0 @@
-module Spree
- module SearchProvider
- class ProductPresenter
- attr_reader :product, :store
-
- def initialize(product, store)
- @product = product
- @store = store
- end
-
- # Returns an array of documents. For each (market × locale) the product is
- # priced in, one BASE document plus one MEMBERSHIP document per grouping the
- # product belongs to (each collection + each category ancestor-or-self),
- # carrying a scalar grouping_id + position so Meilisearch can sort a grouping
- # page by the merchant's hand-set position. Each document has flat name,
- # description, price fields (no dynamic suffixes).
- def call
- documents = []
-
- market_locale_pairs.each do |market, locale|
- # Skip if product has no price in this currency
- next unless lowest_price(market.currency)
-
- Mobility.with_locale(locale) do
- base = build_document(locale, market.currency, default_locale)
- documents << base
- documents.concat(membership_documents(base, locale, market.currency))
- end
- end
-
- # Fallback for stores without markets (legacy/test)
- if documents.empty?
- fallback_currency = store.default_market&.currency || store.supported_currencies_list.first&.iso_code
- if fallback_currency && lowest_price(fallback_currency)
- base = build_document(default_locale, fallback_currency, default_locale)
- documents << base
- documents.concat(membership_documents(base, default_locale, fallback_currency))
- end
- end
-
- documents
- end
-
- private
-
- # Build a document for a given locale and currency
- # @param locale [String] the locale to build the document for
- # @param currency [String] the currency to build the document for
- # @param fallback_locale [String] the fallback locale to use if the product has no translation for the given locale
- # @return [Hash] the document
- def build_document(locale, currency, fallback_locale)
- {
- # Composite ID: product + locale + currency
- id: "#{product.prefixed_id}_#{locale}_#{currency}",
- product_id: product.prefixed_id,
- locale: locale.to_s,
- currency: currency,
- # Translated fields — with fallback to default locale
- name: translated(product, :name, fallback_locale),
- # Indexed as plain text — HTML tag names would otherwise become
- # searchable tokens.
- description: Spree::RichTextHelper.to_plain_text(translated(product, :description, fallback_locale)),
- slug: translated(product, :slug, fallback_locale),
- # Price in this currency
- price: lowest_price(currency)&.to_f,
- compare_at_price: compare_at_price(currency)&.to_f,
- # Non-locale/currency fields
- status: product.status,
- sku: product.sku,
- in_stock: product.in_stock?,
- # True when the product has an active pre-order variant, so a
- # scheduled (future-published) launch still surfaces in search.
- preorder: product.preorder?,
- store_ids: Array(product.store_id).map(&:to_s),
- channel_ids: channel_ids_for_store,
- discontinue_on: product.discontinue_on&.to_i || 0,
- category_ids: category_ids_with_ancestors,
- category_names: product.categories.map { |t| translated(t, :name, fallback_locale) },
- collection_ids: product.collections.map(&:prefixed_id),
- option_type_ids: product.option_types.map(&:prefixed_id),
- option_type_names: product.option_types.map { |ot| translated(ot, :presentation, fallback_locale) },
- option_value_ids: variant_option_value_ids,
- option_values: variant_option_values_data.map { |ov| translated(ov, :presentation, fallback_locale) }.uniq,
- tags: product.tag_list || [],
- units_sold_count: product.units_sold_count || 0,
- available_on: product.available_on&.iso8601,
- created_at: product.created_at&.iso8601,
- updated_at: product.updated_at&.iso8601
- }.merge(custom_field_document_attributes)
- end
-
- # Flat cf_* hash for searchable ∪ sortable custom_fields (Meilisearch docs).
- def custom_field_document_attributes
- @custom_field_document_attributes ||= product.custom_fields.filter_map do |custom_field|
- definition = custom_field.custom_field_definition
- next unless definition&.searchable? || definition&.sortable?
-
- [definition.filter_key, custom_field_index_value(custom_field, definition.field_type)]
- end.to_h
- end
-
- def custom_field_index_value(custom_field, field_type)
- serialized = custom_field.serialize_value
- case field_type
- when 'number'
- serialized.to_f
- else
- serialized.to_s
- end
- end
-
- # Returns all market × locale pairs for this store
- def market_locale_pairs
- @market_locale_pairs ||= store.markets.flat_map do |market|
- market.supported_locales_list.map { |locale| [market, locale] }
- end
- end
-
- def default_locale
- @default_locale ||= store.default_market&.default_locale || I18n.default_locale.to_s
- end
-
- # Read a translated attribute with fallback to default locale.
- def translated(record, attribute, fallback_locale)
- value = record.send(attribute)
- return value if value.present?
-
- record.send(attribute, locale: fallback_locale.to_sym)
- rescue ArgumentError
- value
- end
-
- def lowest_price(currency)
- @prices_cache ||= {}
- @prices_cache[currency] = product.price_in(currency)&.amount unless @prices_cache.key?(currency)
- @prices_cache[currency]
- end
-
- def compare_at_price(currency)
- @compare_at_cache ||= {}
- @compare_at_cache[currency] = product.compare_at_amount_in(currency) unless @compare_at_cache.key?(currency)
- @compare_at_cache[currency]
- end
-
- def channel_ids_for_store
- @channel_ids_for_store ||= product.product_publications
- .joins(:channel)
- .where(spree_channels: { store_id: store.id })
- .pluck(:channel_id)
- .map(&:to_s)
- end
-
- def category_ids_with_ancestors
- @category_ids_with_ancestors ||= product.categories.flat_map { |t|
- t.self_and_ancestors.map(&:prefixed_id)
- }.uniq
- end
-
- # One membership document per grouping (each collection + each category
- # ancestor-or-self) the product belongs to: the full base payload plus a
- # scalar grouping_id and position, with a distinct composite id. A manual-
- # sorted grouping page filters grouping_id and sorts by position.
- def membership_documents(base, locale, currency)
- grouping_positions.map do |grouping_id, position|
- base.merge(
- id: "#{product.prefixed_id}__#{grouping_id}_#{locale}_#{currency}",
- grouping_id: grouping_id,
- position: position
- )
- end
- end
-
- # { grouping_prefixed_id => position }, merged across collections (flat) and
- # categories (subtree-MIN). Prefixes (coll_/ctg_) keep the keys disjoint.
- def grouping_positions
- @grouping_positions ||= collection_positions.merge(category_positions)
- end
-
- # Flat: one entry per collection with the product's ProductCollection.position.
- def collection_positions
- @collection_positions ||= product.product_collections.pluck(:collection_id, :position).each_with_object({}) do |(cid, pos), acc|
- acc[prefixed_id_for(Spree::Collection, cid)] = pos
- end
- end
-
- # Subtree-MIN: a product under a category AND its descendants contributes its
- # position to every ancestor-or-self, folded to the minimum — mirrors the DB
- # provider's MIN(position)/GROUP BY and category_ids_with_ancestors.
- def category_positions
- @category_positions ||= begin
- positions_by_category_id = product.product_categories.pluck(:category_id, :position).to_h
- product.categories.each_with_object({}) do |category, acc|
- position = positions_by_category_id[category.id]
- category.self_and_ancestors.each do |ancestor|
- key = ancestor.prefixed_id
- acc[key] = [acc[key], position].compact.min
- end
- end
- end
- end
-
- # Encode a raw primary key into a model's prefixed id without loading the
- # record (mirrors Spree::PrefixedId#prefixed_id).
- def prefixed_id_for(klass, raw_id)
- "#{klass._prefix_id_prefix}_#{Spree::PrefixedId::SQIDS.encode([raw_id])}"
- end
-
- def variant_option_value_ids
- variant_option_values_data.map(&:prefixed_id).uniq
- end
-
- # Use variants (matches reindex preload) instead of variants.includes
- def variant_option_values_data
- @variant_option_values_data ||= product.variants.flat_map(&:option_values).uniq
- end
- end
- end
-end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 4093b96bfb..40bbdf30b8 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -139,7 +139,7 @@ module Spree
# Search provider class name. Controls product search, filtering, and faceted navigation.
#
- # Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
+ # Spree.search_provider = 'SpreeMeilisearch::SearchProvider'
#
def self.search_provider
@@search_provider ||= 'Spree::SearchProvider::Database'
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 4820c9503e..890784a3f1 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -122,8 +122,9 @@ module Spree
current_store_finder: 'Spree::Stores::FindDefault',
line_item_by_variant_finder: 'Spree::LineItems::FindByVariant',
- # search
- search_product_presenter: 'Spree::SearchProvider::ProductPresenter'
+ # search — the document shape belongs to whichever indexing provider is
+ # installed (spree_meilisearch registers its own), so core ships no default.
+ search_product_presenter: nil
}.freeze
include Spree::DependenciesHelper
diff --git a/spree/core/lib/spree/core/dependencies_helper.rb b/spree/core/lib/spree/core/dependencies_helper.rb
index e73ae717e4..af4b2ec966 100644
--- a/spree/core/lib/spree/core/dependencies_helper.rb
+++ b/spree/core/lib/spree/core/dependencies_helper.rb
@@ -42,6 +42,10 @@ module Spree
when Proc then value.call.then { |v| v.is_a?(String) ? v.constantize : v }
else value
end
+ # An injection point may legitimately have no default — the class is
+ # supplied by an optional gem (search_product_presenter). Leave it
+ # unmemoized so installing the gem later still takes effect.
+ return nil if resolved.nil?
instance_variable_set("@#{point}_resolved", resolved)
resolved
end
diff --git a/spree/core/spec/models/concerns/spree/search_indexable_spec.rb b/spree/core/spec/models/concerns/spree/search_indexable_spec.rb
index 96e4d1e906..2a0663561e 100644
--- a/spree/core/spec/models/concerns/spree/search_indexable_spec.rb
+++ b/spree/core/spec/models/concerns/spree/search_indexable_spec.rb
@@ -6,12 +6,34 @@ RSpec.describe Spree::SearchIndexable, type: :concern do
let(:store) { @default_store }
let(:product) { create(:product) }
+ # Stands in for a provider gem (spree_meilisearch): indexing is required, so
+ # the concern enqueues jobs and calls through synchronously.
+ let(:indexing_provider_class) do
+ Class.new(Spree::SearchProvider::Base) do
+ def self.indexing_required?
+ true
+ end
+
+ def self.name
+ 'SearchIndexableSpec::IndexingProvider'
+ end
+ end
+ end
+
describe '#search_presentation' do
- it 'returns an array of document hashes (one per market × locale)' do
- result = product.search_presentation(store)
- expect(result).to be_an(Array)
- expect(result.first[:product_id]).to eq(product.prefixed_id)
- expect(result.first[:name]).to eq(product.name)
+ it 'raises when no provider gem supplied a presenter' do
+ expect { product.search_presentation(store) }.to raise_error(Spree::DependencyError, /search product presenter/)
+ end
+
+ it 'delegates to the configured presenter' do
+ documents = [{ product_id: product.prefixed_id, name: product.name }]
+ presenter_class = Class.new do
+ def initialize(product, store); end
+ end
+ allow(Spree::Dependencies).to receive(:search_product_presenter_class).and_return(presenter_class)
+ allow_any_instance_of(presenter_class).to receive(:call).and_return(documents)
+
+ expect(product.search_presentation(store)).to eq(documents)
end
end
@@ -45,7 +67,8 @@ RSpec.describe Spree::SearchIndexable, type: :concern do
context 'with external search provider' do
before do
- allow(Spree).to receive(:search_provider).and_return('Spree::SearchProvider::Meilisearch')
+ stub_const(indexing_provider_class.name, indexing_provider_class)
+ allow(Spree).to receive(:search_provider).and_return(indexing_provider_class.name)
end
after do
@@ -82,15 +105,15 @@ RSpec.describe Spree::SearchIndexable, type: :concern do
describe '#add_to_search_index' do
it 'calls provider.index synchronously' do
- provider = instance_double(Spree::SearchProvider::Meilisearch)
- allow(Spree::SearchProvider::Meilisearch).to receive(:new).with(store).and_return(provider)
+ provider = instance_double(indexing_provider_class)
+ allow(indexing_provider_class).to receive(:new).with(store).and_return(provider)
expect(provider).to receive(:index).with(product)
product.add_to_search_index
end
it 'does not enqueue a job' do
- allow_any_instance_of(Spree::SearchProvider::Meilisearch).to receive(:index)
+ allow_any_instance_of(indexing_provider_class).to receive(:index)
product # trigger create jobs
clear_enqueued_jobs
@@ -102,15 +125,15 @@ RSpec.describe Spree::SearchIndexable, type: :concern do
describe '#remove_from_search_index' do
it 'calls provider.remove synchronously' do
- provider = instance_double(Spree::SearchProvider::Meilisearch)
- allow(Spree::SearchProvider::Meilisearch).to receive(:new).with(store).and_return(provider)
+ provider = instance_double(indexing_provider_class)
+ allow(indexing_provider_class).to receive(:new).with(store).and_return(provider)
expect(provider).to receive(:remove).with(product)
product.remove_from_search_index
end
it 'does not enqueue a job' do
- allow_any_instance_of(Spree::SearchProvider::Meilisearch).to receive(:remove)
+ allow_any_instance_of(indexing_provider_class).to receive(:remove)
product # trigger create jobs
clear_enqueued_jobs
diff --git a/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb b/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb
deleted file mode 100644
index 76bd715650..0000000000
--- a/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb
+++ /dev/null
@@ -1,582 +0,0 @@
-require 'spec_helper'
-require 'meilisearch'
-
-module Spree
- RSpec.describe SearchProvider::Meilisearch do
- let(:store) { @default_store }
- let(:provider) { described_class.new(store) }
- let(:mock_client) { instance_double(::Meilisearch::Client) }
- let(:mock_index) { double('MeiliSearch::Index') }
-
- let!(:product_1) { create(:product, name: 'Blue Shirt') }
- let!(:product_2) { create(:product, name: 'Red Pants') }
-
- before do
- allow(::Meilisearch::Client).to receive(:new).and_return(mock_client)
- allow(mock_client).to receive(:index).and_return(mock_index)
- allow(mock_index).to receive(:update_filterable_attributes)
- allow(mock_index).to receive(:update_sortable_attributes)
- allow(mock_index).to receive(:update_searchable_attributes)
- allow(mock_index).to receive(:update_distinct_attribute)
- allow(mock_index).to receive(:delete_documents)
- end
-
- describe '#search_and_filter' do
- let(:ms_response) do
- {
- 'hits' => [
- { 'product_id' => product_1.prefixed_id },
- { 'product_id' => product_2.prefixed_id }
- ],
- 'totalHits' => 2,
- 'facetDistribution' => {
- 'in_stock' => { 'true' => 2 },
- 'price' => { '19.99' => 1, '29.99' => 1 }
- }
- }
- end
-
- before do
- allow(mock_index).to receive(:search).and_return(ms_response)
- end
-
- it 'returns a SearchResult' do
- result = provider.search_and_filter(scope: store.products, query: 'shirt')
- expect(result).to be_a(SearchProvider::SearchResult)
- end
-
- it 'queries Meilisearch with the search term' do
- expect(mock_index).to receive(:search).with('shirt', hash_including(:page, :hitsPerPage))
- provider.search_and_filter(scope: store.products, query: 'shirt')
- end
-
- it 'returns products from the AR scope matching Meilisearch IDs' do
- result = provider.search_and_filter(scope: store.products, query: 'shirt')
- expect(result.products).to include(product_1, product_2)
- end
-
- it 'returns total count from Meilisearch' do
- result = provider.search_and_filter(scope: store.products, query: 'shirt')
- expect(result.total_count).to eq(2)
- end
-
- it 'does not request facets from Meilisearch' do
- expect(mock_index).to receive(:search).with(anything, satisfy { |params| !params.key?(:facets) })
- provider.search_and_filter(scope: store.products, query: 'shirt')
- end
-
- context 'listing all products (no query, no filters)' do
- it 'searches an empty query with only system conditions and no facets' do
- expect(mock_index).to receive(:search).with('', satisfy { |p|
- p[:filter].include?("status = 'active'") && !p.key?(:facets)
- }).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products)
- end
-
- it 'returns the products and total' do
- result = provider.search_and_filter(scope: store.products)
-
- expect(result.products).to include(product_1, product_2)
- expect(result.total_count).to eq(2)
- end
- end
-
- context 'with no results' do
- let(:ms_response) { { 'hits' => [], 'totalHits' => 0, 'facetDistribution' => {} } }
-
- it 'returns empty relation' do
- result = provider.search_and_filter(scope: store.products, query: 'nonexistent')
- expect(result.products).to be_empty
- expect(result.total_count).to eq(0)
- end
- end
-
- context 'with price filter' do
- it 'passes price filter to Meilisearch' do
- expect(mock_index).to receive(:search).with(anything, hash_including(
- filter: include('price >= 10.0')
- )).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, filters: { 'price_gte' => '10' })
- end
- end
-
- context 'with in_stock filter' do
- it 'passes stock filter to Meilisearch' do
- expect(mock_index).to receive(:search).with(anything, hash_including(
- filter: include('in_stock = true')
- )).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, filters: { 'in_stock' => '1' })
- end
- end
-
- context 'with in_collection filter' do
- let(:collection) { create(:collection) }
-
- it 'passes the collection_ids filter to Meilisearch (non-manual sort)' do
- expect(mock_index).to receive(:search).with(anything, hash_including(
- filter: include("collection_ids = '#{collection.prefixed_id}'")
- )).and_return(ms_response)
-
- # A non-manual sort keeps the collection_ids filter; a blank/manual sort
- # instead routes to the grouping_id membership docs (covered below).
- provider.search_and_filter(scope: store.products, sort: 'price', filters: { 'in_collection' => collection.prefixed_id })
- end
-
- it 'ignores a value that is not a prefixed id' do
- expect(mock_index).to receive(:search).with(anything, satisfy { |params|
- params[:filter].none? { |c| c.to_s.include?('collection_ids') }
- }).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, filters: { 'in_collection' => '123' })
- end
- end
-
- context 'with sort' do
- it 'passes price sort to Meilisearch' do
- expect(mock_index).to receive(:search).with(anything, hash_including(
- sort: ['price:asc']
- )).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, sort: 'price')
- end
-
- it 'passes descending price sort' do
- expect(mock_index).to receive(:search).with(anything, hash_including(
- sort: ['price:desc']
- )).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, sort: '-price')
- end
- end
-
- context 'with pagination' do
- it 'passes page and hitsPerPage (exhaustive mode so distinct counts are exact)' do
- expect(mock_index).to receive(:search).with(anything, hash_including(
- page: 2, hitsPerPage: 25
- )).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, page: 2, limit: 25)
- end
- end
-
- context 'pagination result (pagy built from totalHits)' do
- let(:ms_response) do
- { 'hits' => [{ 'product_id' => product_1.prefixed_id }], 'totalHits' => 50, 'facetDistribution' => {} }
- end
-
- it 'builds a pagy spanning all pages with a next page' do
- result = provider.search_and_filter(scope: store.products, page: 1, limit: 25)
-
- expect(result.total_count).to eq(50)
- expect(result.pagy.count).to eq(50)
- expect(result.pagy.pages).to eq(2)
- expect(result.pagy.page).to eq(1)
- expect(result.pagy.next).to eq(2)
- end
- end
-
- context 'with manual (position) sort on a grouping' do
- it 'queries the grouping_id membership docs sorted by position (collection)' do
- expect(mock_index).to receive(:search).with(anything, satisfy { |p|
- p[:filter].include?("grouping_id = 'coll_Manual1'") &&
- p[:filter].none? { |c| c.to_s.include?('collection_ids') } &&
- p[:sort] == ['position:asc']
- }).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, sort: 'manual', filters: { 'in_collection' => 'coll_Manual1' })
- end
-
- it 'defaults a grouping page with no sort param to manual' do
- expect(mock_index).to receive(:search).with(anything, satisfy { |p|
- p[:filter].include?("grouping_id = 'coll_Manual1'") && p[:sort] == ['position:asc']
- }).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, filters: { 'in_collection' => 'coll_Manual1' })
- end
-
- it 'works for a category grouping' do
- expect(mock_index).to receive(:search).with(anything, satisfy { |p|
- p[:filter].include?("grouping_id = 'ctg_Manual1'") && p[:sort] == ['position:asc']
- }).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, sort: 'manual', filters: { 'in_category' => 'ctg_Manual1' })
- end
-
- it 'ignores manual sort without a grouping (falls back to default ranking)' do
- expect(mock_index).to receive(:search).with(anything, satisfy { |p| p[:sort].nil? }).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, sort: 'manual')
- end
- end
-
- context 'with sort order preservation' do
- it 'returns products in the order Meilisearch returned them' do
- reversed_response = {
- 'hits' => [
- { 'product_id' => product_2.prefixed_id },
- { 'product_id' => product_1.prefixed_id }
- ],
- 'totalHits' => 2,
- 'facetDistribution' => {}
- }
- allow(mock_index).to receive(:search).and_return(reversed_response)
-
- result = provider.search_and_filter(scope: store.products, query: 'shirt')
- expect(result.products).to eq([product_2, product_1])
- end
- end
-
- context 'with visibility scope' do
- it 'intersects Meilisearch results with AR scope' do
- restricted_scope = store.products.where(id: product_1.id)
- result = provider.search_and_filter(scope: restricted_scope, query: 'shirt')
- expect(result.products).to include(product_1)
- expect(result.products).not_to include(product_2)
- end
- end
-
- # A newly added filterable or sortable attribute referenced before the
- # index settings were refreshed rejects the whole query on upgraded
- # stores — the provider must push settings and retry instead of serving
- # an empty listing until a reindex.
- context 'when a filter attribute is not yet filterable' do
- before do
- error = ::Meilisearch::ApiError.new(
- 400, 'Bad Request',
- { 'code' => 'invalid_search_filter', 'message' => 'Attribute `preorder` is not filterable.' }
- )
- calls = 0
- allow(mock_index).to receive(:search) do
- calls += 1
- raise error if calls == 1
-
- ms_response
- end
- end
-
- it 'pushes index settings and retries the search once' do
- expect(mock_index).to receive(:update_filterable_attributes)
-
- result = provider.search_and_filter(scope: store.products, query: 'shirt')
- expect(result.products).to include(product_1, product_2)
- end
- end
-
- context 'when a sort attribute is not yet sortable' do
- before do
- error = ::Meilisearch::ApiError.new(
- 400, 'Bad Request',
- { 'code' => 'invalid_search_sort', 'message' => 'Attribute `cf_custom_label` is not sortable.' }
- )
- calls = 0
- allow(mock_index).to receive(:search) do
- calls += 1
- raise error if calls == 1
-
- ms_response
- end
- end
-
- it 'pushes index settings and retries the search once' do
- expect(mock_index).to receive(:update_sortable_attributes)
-
- result = provider.search_and_filter(scope: store.products, query: 'shirt', sort: 'cf_custom_label')
- expect(result.products).to include(product_1, product_2)
- end
- end
- end
-
- describe '#filters' do
- let(:ms_response) do
- {
- 'hits' => [],
- 'totalHits' => 2,
- 'processingTimeMs' => 1,
- 'facetDistribution' => {
- 'in_stock' => { 'true' => 2 },
- 'price' => { '19.99' => 1, '29.99' => 1 }
- }
- }
- end
-
- before do
- allow(mock_index).to receive(:search).and_return(ms_response)
- end
-
- it 'returns a FiltersResult' do
- result = provider.filters(scope: store.products, query: 'shirt')
- expect(result).to be_a(SearchProvider::FiltersResult)
- end
-
- it 'returns facets from Meilisearch' do
- result = provider.filters(scope: store.products, query: 'shirt')
- expect(result.filters).to be_an(Array)
-
- price_filter = result.filters.find { |f| f[:type] == 'price_range' }
- expect(price_filter).to be_present
- expect(price_filter[:min]).to eq(19.99)
- expect(price_filter[:max]).to eq(29.99)
- end
-
- it 'returns sort options as objects' do
- result = provider.filters(scope: store.products, query: 'shirt')
- ids = result.sort_options.map { |o| o[:id] }
- expect(ids).to include('price', '-price')
- end
-
- it 'returns total count' do
- result = provider.filters(scope: store.products, query: 'shirt')
- expect(result.total_count).to eq(2)
- end
-
- it 'requests facets from Meilisearch' do
- expect(mock_index).to receive(:search).with(anything, hash_including(:facets))
- provider.filters(scope: store.products, query: 'shirt')
- end
-
- context 'with option type facets' do
- let(:color_type) { create(:option_type, :color_swatch, filterable: true) }
- let(:red_value) { create(:option_value, option_type: color_type, name: 'red', presentation: 'Red', color_code: '#FF0000') }
- let(:blue_value) { create(:option_value, option_type: color_type, name: 'blue', presentation: 'Blue', color_code: '#0000FF') }
-
- let(:ms_response) do
- {
- 'hits' => [],
- 'totalHits' => 1,
- 'processingTimeMs' => 1,
- 'facetDistribution' => {
- 'option_value_ids' => {
- red_value.prefixed_id => 3,
- blue_value.prefixed_id => 1
- }
- }
- }
- end
-
- it 'includes kind on option type filters' do
- result = provider.filters(scope: store.products, query: '')
- color_filter = result.filters.find { |f| f[:name] == 'color' }
-
- expect(color_filter).to be_present
- expect(color_filter[:kind]).to eq('color_swatch')
- end
-
- it 'includes color_code on option values' do
- result = provider.filters(scope: store.products, query: '')
- color_filter = result.filters.find { |f| f[:name] == 'color' }
- red_option = color_filter[:options].find { |o| o[:name] == 'red' }
-
- expect(red_option[:color_code]).to eq('#FF0000')
- end
-
- it 'includes image_url as nil when no image attached' do
- result = provider.filters(scope: store.products, query: '')
- color_filter = result.filters.find { |f| f[:name] == 'color' }
- red_option = color_filter[:options].find { |o| o[:name] == 'red' }
-
- expect(red_option[:image_url]).to be_nil
- end
- end
-
- context 'when Meilisearch API fails' do
- before do
- error = ::Meilisearch::ApiError.new(500, 'internal error', 'internal')
- allow(mock_index).to receive(:search).and_raise(error)
- end
-
- it 'returns empty FiltersResult' do
- result = provider.filters(scope: store.products, query: 'shirt')
- expect(result.filters).to eq([])
- expect(result.total_count).to eq(0)
- end
- end
-
- # default_sort comes from the collection's sort_order (a collection PLP page),
- # rendered in API format; it falls back to 'manual' with no collection.
- context 'default_sort' do
- it 'defaults to manual when no collection is provided' do
- result = provider.filters(scope: store.products, query: 'shirt')
- expect(result.default_sort).to eq('manual')
- end
-
- it "reflects the collection's sort_order (space format rendered as API format)" do
- collection = create(:collection, sort_order: 'price asc')
-
- result = provider.filters(scope: store.products, filters: { '_collection' => collection })
- expect(result.default_sort).to eq('price')
- end
-
- it 'stays manual for a manual-sorted collection' do
- collection = create(:collection, sort_order: 'manual')
-
- result = provider.filters(scope: store.products, filters: { '_collection' => collection })
- expect(result.default_sort).to eq('manual')
- end
- end
-
- it 'advertises manual in the sort options (sourced from Collection::SORT_ORDERS)' do
- result = provider.filters(scope: store.products, query: '')
- expect(result.sort_options.map { |o| o[:id] }).to include('manual')
- end
- end
-
- describe '#index' do
- it 'adds documents to Meilisearch index with id as primary key' do
- expect(mock_index).to receive(:add_documents).with(
- array_including(hash_including(product_id: product_1.prefixed_id, name: 'Blue Shirt')),
- 'id'
- )
- provider.index(product_1)
- end
-
- it 'uses ProductPresenter to serialize' do
- docs = [{ id: 'prod_abc_en_USD', product_id: 'prod_abc' }]
- presenter = instance_double(SearchProvider::ProductPresenter, call: docs)
- allow(SearchProvider::ProductPresenter).to receive(:new).with(product_1, store).and_return(presenter)
- expect(mock_index).to receive(:add_documents).with(docs, 'id')
- provider.index(product_1)
- end
-
- it 'deletes the product existing docs before adding (purges stale membership docs)' do
- expect(mock_index).to receive(:delete_documents).with(filter: "product_id = '#{product_1.prefixed_id}'").ordered
- expect(mock_index).to receive(:add_documents).ordered
- provider.index(product_1)
- end
- end
-
- describe '#remove' do
- it 'deletes all locale/currency variants by product_id filter' do
- expect(mock_index).to receive(:delete_documents).with(filter: "product_id = '#{product_1.prefixed_id}'")
- provider.remove(product_1)
- end
- end
-
- describe '#remove_by_id' do
- it 'deletes all documents by product_id filter' do
- expect(mock_index).to receive(:delete_documents).with(filter: "product_id = 'prod_abc'")
- provider.remove_by_id('prod_abc')
- end
-
- it 'ignores 404 errors' do
- error = ::Meilisearch::ApiError.new(404, 'not found', 'document_not_found')
- allow(mock_index).to receive(:delete_documents).and_raise(error)
- expect { provider.remove_by_id('prod_abc') }.not_to raise_error
- end
- end
-
- describe '#reindex' do
- it 'configures index settings' do
- expect(mock_index).to receive(:update_filterable_attributes)
- expect(mock_index).to receive(:update_sortable_attributes)
- expect(mock_index).to receive(:update_searchable_attributes)
- allow(mock_index).to receive(:add_documents)
-
- provider.reindex(store.products)
- end
-
- it 'indexes all products in batches' do
- expect(mock_index).to receive(:add_documents).at_least(:once)
- provider.reindex(store.products)
- end
-
- it 'clears the index before a full (unscoped) reindex' do
- expect(mock_index).to receive(:delete_all_documents)
- allow(mock_index).to receive(:add_documents)
- provider.reindex
- end
-
- it 'does not clear the index for a scoped reindex' do
- expect(mock_index).not_to receive(:delete_all_documents)
- allow(mock_index).to receive(:add_documents)
- provider.reindex(store.products)
- end
- end
-
- describe '#ensure_index_settings!' do
- it 'declares grouping_id filterable, position sortable, and product_id distinct' do
- expect(mock_index).to receive(:update_filterable_attributes).with(include('grouping_id'))
- expect(mock_index).to receive(:update_sortable_attributes).with(include('position'))
- expect(mock_index).to receive(:update_distinct_attribute).with('product_id')
- allow(mock_index).to receive(:update_searchable_attributes)
-
- provider.ensure_index_settings!
- end
- end
-
- describe 'custom_field searchable / sortable settings' do
- let!(:definition) do
- create(:custom_field_definition, :short_text_field, :searchable, :sortable,
- namespace: 'custom', key: 'label')
- end
-
- it 'includes cf_* in searchable and sortable attributes' do
- expect(provider.send(:searchable_attributes)).to include('cf_custom_label')
- expect(provider.send(:sortable_attributes)).to include('cf_custom_label')
- end
-
- it 'includes cf_* in filterable attributes but not in requested facets' do
- expect(provider.send(:filterable_attributes)).to include('cf_custom_label')
- expect(provider.send(:facet_attributes)).not_to include('cf_custom_label')
- end
-
- it 'maps cf_* sort params without namespace resolution' do
- expect(provider.send(:sort_mapping, 'cf_custom_label')).to eq(['cf_custom_label:asc'])
- expect(provider.send(:sort_mapping, '-cf_custom_label')).to eq(['cf_custom_label:desc'])
- end
- end
-
- describe 'custom_field filter conditions' do
- let!(:label) do
- create(:custom_field_definition, :short_text_field, :searchable,
- namespace: 'custom', key: 'label')
- end
- let!(:weight) do
- create(:custom_field_definition, :number_field, :sortable,
- namespace: 'custom', key: 'weight')
- end
-
- it 'builds equality conditions for text custom_fields' do
- expect(provider.send(:build_filter_condition, 'cf_custom_label_eq', 'wool')).to eq("cf_custom_label = 'wool'")
- expect(provider.send(:build_filter_condition, 'cf_custom_label_not_eq', 'wool')).to eq("cf_custom_label != 'wool'")
- end
-
- it 'escapes quotes and backslashes in text values' do
- expect(provider.send(:build_filter_condition, 'cf_custom_label_eq', "o'brien\\x")).to eq("cf_custom_label = 'o\\'brien\\\\x'")
- end
-
- it 'builds range conditions for number custom_fields' do
- expect(provider.send(:build_filter_condition, 'cf_custom_weight_gteq', '3.5')).to eq('cf_custom_weight >= 3.5')
- expect(provider.send(:build_filter_condition, 'cf_custom_weight_lt', '10')).to eq('cf_custom_weight < 10.0')
- end
-
- it 'builds EXISTS conditions for present and blank' do
- expect(provider.send(:build_filter_condition, 'cf_custom_label_present', '1')).to eq('cf_custom_label EXISTS')
- expect(provider.send(:build_filter_condition, 'cf_custom_label_blank', '1')).to eq('cf_custom_label NOT EXISTS')
- end
-
- it 'ignores substring predicates Meilisearch cannot filter on' do
- expect(provider.send(:build_filter_condition, 'cf_custom_label_cont', 'wool')).to be_nil
- end
-
- it 'ignores non-numeric values on number predicates' do
- expect(provider.send(:build_filter_condition, 'cf_custom_weight_gteq', 'abc')).to be_nil
- end
-
- it 'ignores unknown cf_ keys' do
- expect(provider.send(:build_filter_condition, 'cf_bogus_field_eq', 'x')).to be_nil
- end
-
- it 'passes custom_field conditions through to the Meilisearch query' do
- ms_response = { 'hits' => [], 'estimatedTotalHits' => 0, 'facetDistribution' => {} }
- expect(mock_index).to receive(:search).with(anything, hash_including(
- filter: include('cf_custom_weight >= 3.5')
- )).and_return(ms_response)
-
- provider.search_and_filter(scope: store.products, filters: { 'cf_custom_weight_gteq' => '3.5' })
- end
- end
- end
-end
diff --git a/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb b/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
deleted file mode 100644
index 7c804246c0..0000000000
--- a/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
+++ /dev/null
@@ -1,312 +0,0 @@
-require 'spec_helper'
-
-module Spree
- RSpec.describe SearchProvider::ProductPresenter do
- let(:store) { @default_store }
- let(:product) { create(:product, name: 'Test Shirt') }
- let(:presenter) { described_class.new(product, store) }
-
- describe '#call' do
- subject(:documents) { presenter.call }
-
- it 'returns an array of documents' do
- expect(documents).to be_an(Array)
- expect(documents).not_to be_empty
- end
-
- context 'document structure' do
- subject(:doc) { documents.first }
-
- it 'includes composite id and product_id' do
- expect(doc[:id]).to start_with(product.prefixed_id)
- expect(doc[:product_id]).to eq(product.prefixed_id)
- end
-
- it 'includes locale and currency' do
- expect(doc[:locale]).to be_present
- expect(doc[:currency]).to be_present
- end
-
- it 'includes flat name and description' do
- expect(doc[:name]).to eq('Test Shirt')
- expect(doc[:slug]).to eq(product.slug)
- end
-
- it 'includes flat price' do
- expect(doc).to have_key(:price)
- end
-
- it 'includes stock status' do
- expect(doc).to have_key(:in_stock)
- end
-
- it 'includes timestamps' do
- expect(doc[:created_at]).to be_present
- expect(doc[:updated_at]).to be_present
- end
-
- it 'includes category data as prefixed IDs' do
- expect(doc[:category_ids]).to be_an(Array)
- end
-
- it 'includes option data as prefixed IDs' do
- expect(doc[:option_type_ids]).to be_an(Array)
- expect(doc[:option_value_ids]).to be_an(Array)
- end
- end
-
- context 'with categories' do
- let(:root_category) { create(:category, store: store, name: 'Apparel') }
- let(:category) { create(:category, store: store, parent: root_category) }
- let(:product) { create(:product, name: 'Test Shirt', categories: [category]) }
-
- it 'indexes category_ids as prefixed IDs including ancestors' do
- doc = documents.first
- expect(doc[:category_ids]).to include(category.prefixed_id)
- expect(doc[:category_ids]).to include(root_category.prefixed_id)
- doc[:category_ids].each { |id| expect(id).to start_with('ctg_') }
- end
- end
-
- context 'with nested categories' do
- let(:root_category) { create(:category, store: store, name: 'Apparel') }
- let(:parent) { create(:category, store: store, parent: root_category, name: 'Men') }
- let(:child) { create(:category, store: store, parent: parent, name: 'Jackets') }
- let(:product) { create(:product, name: 'Test Jacket', channels: [store.default_channel], categories: [child]) }
-
- it 'indexes all ancestor category IDs so parent-level filtering works' do
- doc = documents.first
- expect(doc[:category_ids]).to include(child.prefixed_id)
- expect(doc[:category_ids]).to include(parent.prefixed_id)
- expect(doc[:category_ids]).to include(root_category.prefixed_id)
- end
- end
-
- context 'with collections' do
- let(:collection) { create(:collection, store: store) }
-
- before { Spree::ProductCollection.create!(collection: collection, product: product) }
-
- it 'indexes collection_ids as flat prefixed IDs (no ancestors)' do
- doc = documents.first
- expect(doc[:collection_ids]).to eq([collection.prefixed_id])
- expect(doc[:collection_ids].first).to start_with('coll_')
- end
- end
-
- context 'membership documents (manual sort)' do
- let(:collection) { create(:collection, store: store) }
-
- before { Spree::ProductCollection.create!(collection: collection, product: product, position: 4) }
-
- it 'emits a collection membership doc carrying position + full base payload' do
- member = documents.find { |d| d[:grouping_id] == collection.prefixed_id }
-
- expect(member).to be_present
- expect(member[:position]).to eq(4)
- expect(member[:name]).to eq('Test Shirt') # full base payload copied
- expect(member[:product_id]).to eq(product.prefixed_id)
- expect(member[:id]).to include(collection.prefixed_id)
- end
-
- it 'leaves base docs without a grouping_id/position' do
- base = documents.reject { |d| d[:grouping_id] }
-
- expect(base).not_to be_empty
- base.each { |d| expect(d[:position]).to be_nil }
- end
- end
-
- context 'category membership positions (subtree-MIN)' do
- let(:parent) { create(:category, store: store, name: 'Men') }
- let(:jackets) { create(:category, store: store, parent: parent, name: 'Jackets') }
- let(:coats) { create(:category, store: store, parent: parent, name: 'Coats') }
- let(:product) { create(:product, name: 'Test Jacket', channels: [store.default_channel], categories: [jackets, coats]) }
-
- before do
- Spree::ProductCategory.where(product: product, category: jackets).update_all(position: 5)
- Spree::ProductCategory.where(product: product, category: coats).update_all(position: 2)
- end
-
- it 'emits a membership doc per ancestor-or-self, folding parent to the subtree minimum' do
- jackets_doc = documents.find { |d| d[:grouping_id] == jackets.prefixed_id }
- coats_doc = documents.find { |d| d[:grouping_id] == coats.prefixed_id }
- parent_doc = documents.find { |d| d[:grouping_id] == parent.prefixed_id }
-
- expect(jackets_doc[:position]).to eq(5)
- expect(coats_doc[:position]).to eq(2)
- expect(parent_doc[:position]).to eq(2) # MIN(5, 2) across the subtree
- end
- end
-
- context 'with multiple markets' do
- let!(:us_market) { store.default_market }
- let!(:eu_market) { create(:market, store: store, name: 'EU', currency: 'EUR', default_locale: 'de', supported_locales: 'de,fr') }
-
- # Product with prices in both currencies
- let(:product) do
- p = create(:product, name: 'Test Shirt')
- create(:price, variant: p.default_variant, amount: 29.99, currency: 'EUR')
- p
- end
-
- # Reload store to pick up new markets
- let(:presenter) { described_class.new(product, store.reload) }
-
- it 'creates one document per market × locale where product has a price' do
- locales_currencies = documents.map { |d| [d[:locale], d[:currency]] }
- expect(locales_currencies).to include(['en', 'USD'])
- expect(locales_currencies).to include(['de', 'EUR'])
- expect(locales_currencies).to include(['fr', 'EUR'])
- expect(documents.size).to eq(3)
- end
-
- it 'each document has the correct currency and locale' do
- usd_doc = documents.find { |d| d[:currency] == 'USD' }
- eur_doc = documents.find { |d| d[:currency] == 'EUR' && d[:locale] == 'de' }
-
- expect(usd_doc[:locale]).to eq('en')
- expect(eur_doc[:locale]).to eq('de')
- end
-
- it 'each document has a unique composite id' do
- ids = documents.map { |d| d[:id] }
- expect(ids.uniq.size).to eq(ids.size)
- end
-
- it 'composite id includes product_id, locale, and currency' do
- doc = documents.first
- expect(doc[:id]).to match(/\A#{product.prefixed_id}_\w+_[A-Z]{3}\z/)
- end
-
- it 'includes the price for each currency' do
- usd_doc = documents.find { |d| d[:currency] == 'USD' }
- eur_doc = documents.find { |d| d[:currency] == 'EUR' }
-
- expect(usd_doc[:price]).to be_present
- expect(eur_doc[:price]).to eq(29.99)
- end
-
- it 'all documents share the same product_id' do
- product_ids = documents.map { |d| d[:product_id] }.uniq
- expect(product_ids).to eq([product.prefixed_id])
- end
- end
-
- context 'with market but product has no price in that currency' do
- let!(:us_market) { store.default_market }
- let!(:eu_market) { create(:market, store: store, name: 'EU', currency: 'EUR', default_locale: 'de') }
-
- # Product with USD price only — no EUR price
- let(:product) { create(:product, name: 'USD Only Product') }
- let(:presenter) { described_class.new(product, store.reload) }
-
- it 'skips markets where product has no price' do
- currencies = documents.map { |d| d[:currency] }
- expect(currencies).to include('USD')
- expect(currencies).not_to include('EUR')
- end
-
- it 'only creates documents for markets with matching prices' do
- expect(documents.size).to eq(1)
- expect(documents.first[:currency]).to eq('USD')
- end
- end
-
- context 'translation fallback' do
- let!(:us_market) { create(:market, store: store, name: 'US', currency: 'USD', default_locale: 'en') }
- let!(:eu_market) { create(:market, store: store, name: 'EU', currency: 'EUR', default_locale: 'de') }
-
- let(:product) do
- p = create(:product, name: 'English Name')
- create(:price, variant: p.default_variant, amount: 19.99, currency: 'EUR')
- p
- end
-
- let(:presenter) { described_class.new(product, store.reload) }
-
- it 'falls back to default locale name when translation is missing' do
- de_doc = documents.find { |d| d[:locale] == 'de' }
- expect(de_doc[:name]).to eq('English Name')
- end
- end
-
- context 'with option values' do
- let(:product) { create(:product_with_option_types) }
-
- it 'includes option value prefixed IDs' do
- doc = documents.first
- doc[:option_value_ids].each do |ov_id|
- expect(ov_id).to start_with('optval_')
- end
- end
- end
-
- context 'with searchable / sortable custom_fields' do
- let!(:searchable_def) do
- create(:custom_field_definition, :short_text_field, :searchable,
- namespace: 'custom', key: 'pinyin_name', label: 'Pinyin')
- end
- let!(:sortable_def) do
- create(:custom_field_definition, :number_field, :sortable,
- namespace: 'custom', key: 'priority', label: 'Priority')
- end
- let!(:ignored_def) do
- create(:custom_field_definition, :short_text_field,
- namespace: 'custom', key: 'internal_note', label: 'Note')
- end
-
- before do
- product.set_custom_field(searchable_def, 'mao-tai')
- product.set_custom_field(sortable_def, '10')
- product.set_custom_field(ignored_def, 'secret')
- end
-
- it 'indexes searchable and sortable custom_field values as cf_* attributes' do
- doc = documents.first
- expect(doc['cf_custom_pinyin_name']).to eq('mao-tai')
- expect(doc['cf_custom_priority']).to eq(10.0)
- expect(doc).not_to have_key('cf_custom_internal_note')
- end
-
- it 'uses the same cf_* attributes on every market/locale document' do
- create(:market, store: store, name: 'US', currency: 'USD', default_locale: 'en')
- create(:market, store: store, name: 'EU', currency: 'EUR', default_locale: 'de')
- create(:price, variant: product.master, amount: 9.99, currency: 'EUR')
-
- docs = described_class.new(product.reload, store.reload).call
- expect(docs.size).to be > 1
-
- cf_keys = docs.first.keys.grep(/\Acf_/)
- docs.each do |doc|
- expect(doc.slice(*cf_keys)).to eq(docs.first.slice(*cf_keys))
- end
- end
-
- it 'casts number custom_field values to Float' do
- decimal_def = create(:custom_field_definition, :number_field, :sortable,
- namespace: 'custom', key: 'rating', label: 'Rating')
- product.set_custom_field(decimal_def, '42.5')
-
- doc = described_class.new(product.reload, store).call.first
- expect(doc['cf_custom_rating']).to eq(42.5)
- end
-
- it 'omits registered keys when the product has no value' do
- create(:custom_field_definition, :short_text_field, :searchable,
- namespace: 'custom', key: 'origin', label: 'Origin')
-
- doc = described_class.new(product.reload, store).call.first
- expect(doc).not_to have_key('cf_custom_origin')
- end
-
- it 'includes no cf_* attributes when no definitions are searchable or sortable' do
- Spree::CustomFieldDefinition.destroy_all
-
- doc = described_class.new(product.reload, store).call.first
- expect(doc.keys.grep(/\Acf_/)).to be_empty
- end
- end
- end
- end
-end
diff --git a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
index 6437870efe..bc1da7f9d8 100644
--- a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
+++ b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
@@ -117,8 +117,8 @@ end
# Spree.queues.api_keys = :default
# Spree.queues.search = :default
-# Search provider
-# Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
+# Search provider — requires the spree_meilisearch gem
+# Spree.search_provider = 'SpreeMeilisearch::SearchProvider'
Spree.customer_class = <%= (options[:user_class].blank? ? 'Spree::Customer' : options[:user_class]).inspect %>
Spree.admin_user_class = <%= (options[:admin_user_class].blank? ? (options[:user_class].blank? ? 'Spree::AdminUser' : options[:user_class]) : options[:admin_user_class]).inspect %>
diff --git a/spree/providers/easypost/spree_easypost.gemspec b/spree/providers/easypost/spree_easypost.gemspec
index 4cb44dd3c4..1eac622bd1 100644
--- a/spree/providers/easypost/spree_easypost.gemspec
+++ b/spree/providers/easypost/spree_easypost.gemspec
@@ -26,7 +26,7 @@ Gem::Specification.new do |s|
s.require_path = 'lib'
s.add_dependency 'easypost', '~> 7.0'
- s.add_dependency 'spree_core', ">= #{s.version}"
+ s.add_dependency 'spree_core', s.version
s.add_development_dependency 'vcr'
end
diff --git a/spree/providers/meilisearch/Gemfile b/spree/providers/meilisearch/Gemfile
new file mode 100644
index 0000000000..304a564012
--- /dev/null
+++ b/spree/providers/meilisearch/Gemfile
@@ -0,0 +1,5 @@
+eval_gemfile('../../common_spree_dependencies.rb')
+
+gem 'spree', path: '../../'
+
+gemspec
diff --git a/spree/providers/meilisearch/README.md b/spree/providers/meilisearch/README.md
new file mode 100644
index 0000000000..11769d40fa
--- /dev/null
+++ b/spree/providers/meilisearch/README.md
@@ -0,0 +1,59 @@
+# spree_meilisearch
+
+Instant product search, filtering and faceted navigation for Spree via [Meilisearch](https://www.meilisearch.com) — an implementation of the `Spree::SearchProvider` interface.
+
+## What it does
+
+- **`SpreeMeilisearch::SearchProvider`** answers product search, filtering and faceted navigation from a Meilisearch index instead of the database. One index per store. Search results are always intersected with the caller's ActiveRecord scope, so a stale index can never widen what a customer is allowed to see — it can only ever show less.
+- **`SpreeMeilisearch::ProductPresenter`** builds the documents. Each product is indexed once per locale and currency it is priced in, with the fields flattened for filtering: price, stock, categories, collections, option values, tags, and any custom fields marked searchable or sortable.
+- Facet counts are disjunctive: the counts shown for one option type are computed as if that type's own filters were not applied, so a customer picking "Red" still sees how many blue items are available.
+- Merchant-ordered category and collection pages are supported through extra membership documents carrying the hand-set position.
+
+Without this gem Spree searches the database directly (`Spree::SearchProvider::Database`), which needs no extra infrastructure but has no full-text ranking or typo tolerance.
+
+## Setup
+
+1. Run Meilisearch, and point the application at it:
+
+ ```bash
+ MEILISEARCH_URL=http://localhost:7700
+ MEILISEARCH_API_KEY=your-master-key # optional for a local server
+ ```
+
+ These are environment variables rather than dashboard settings because the index is infrastructure — one server serves every store in the installation, and the reindex task has to reach it outside a request.
+
+2. Add the gem: `bundle add spree_meilisearch`
+
+3. Select the provider in `config/initializers/spree.rb`:
+
+ ```ruby
+ Spree.search_provider = 'SpreeMeilisearch::SearchProvider'
+ ```
+
+4. Build the index: `bin/rails spree:search:reindex`
+
+From then on, product changes are indexed in the background as they happen. Re-run the reindex task after adding a custom field that should be searchable, sortable or filterable.
+
+## Upgrading from Spree 5.x
+
+The provider used to live in `spree_core` as `Spree::SearchProvider::Meilisearch`. Add this gem and update the class name in your initializer:
+
+```ruby
+# before
+Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
+# after
+Spree.search_provider = 'SpreeMeilisearch::SearchProvider'
+```
+
+The old names still resolve with a deprecation warning for one release. Applications that subclassed `Spree::SearchProvider::ProductPresenter` should inherit from `SpreeMeilisearch::ProductPresenter` instead. No reindex is needed — the documents are unchanged.
+
+## Testing
+
+```bash
+cd spree/providers/meilisearch
+bundle install
+bundle exec rake test_app
+bundle exec rspec
+```
+
+The unit specs stub the Meilisearch client and run offline. The integration spec in `spec/requests/` exercises a real server and is skipped unless `MEILISEARCH_URL` is set — locally, `brew install meilisearch && meilisearch`; in CI it runs as a service container.
diff --git a/spree/providers/meilisearch/Rakefile b/spree/providers/meilisearch/Rakefile
new file mode 100644
index 0000000000..d7d9a24577
--- /dev/null
+++ b/spree/providers/meilisearch/Rakefile
@@ -0,0 +1,15 @@
+require 'rubygems'
+require 'rake'
+require 'rake/testtask'
+require 'rspec/core/rake_task'
+require 'spree/testing_support/common_rake'
+
+RSpec::Core::RakeTask.new
+
+task default: :spec
+
+desc "Generates a dummy app for testing"
+task :test_app do
+ ENV['LIB_NAME'] = 'spree_meilisearch'
+ Rake::Task['common:test_app'].invoke
+end
diff --git a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb
new file mode 100644
index 0000000000..0931a6adec
--- /dev/null
+++ b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb
@@ -0,0 +1,613 @@
+module SpreeMeilisearch
+ # Product search, filtering and faceted navigation backed by a Meilisearch
+ # index — one index per store, holding the documents
+ # SpreeMeilisearch::ProductPresenter builds. Results are always intersected
+ # with the caller's ActiveRecord scope, so a stale index can never widen
+ # what a customer is allowed to see.
+ class SearchProvider < Spree::SearchProvider::Base
+ PREFIXED_ID_PATTERN = /\A[a-z]+_[A-Za-z0-9]+\z/
+ ALLOWED_STATUSES = %w[active draft archived paused].freeze
+ BUILT_IN_FILTERABLE_ATTRIBUTES = %w[product_id status in_stock preorder store_ids channel_ids locale currency available_on discontinue_on price category_ids collection_ids grouping_id tags option_value_ids].freeze
+ CUSTOM_FIELD_RANGE_OPERATORS = { 'gt' => '>', 'gteq' => '>=', 'lt' => '<', 'lteq' => '<=' }.freeze
+
+ def self.indexing_required?
+ true
+ end
+
+ def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
+ page = [page.to_i, 1].max
+ limit = limit.to_i.clamp(1, 100)
+
+ filters = normalize_filters(filters)
+ sort, filters = resolve_manual_sort(sort, filters)
+
+ ms_result, _ = execute_search(query: query, filters: filters, sort: sort, page: page, limit: limit)
+ return empty_result(scope, page, limit) unless ms_result
+
+ # Hits have composite prefixed_id (prod_abc_en_USD), extract product_id (prod_abc)
+ product_prefixed_ids = ms_result['hits'].map { |h| h['product_id'] }.uniq
+ raw_ids = product_prefixed_ids.filter_map { |pid| Spree::Product.decode_prefixed_id(pid) }
+
+ # Intersect with AR scope for security/visibility, preserving Meilisearch sort order.
+ products = if raw_ids.any?
+ records = scope.where(id: raw_ids).reorder(nil).index_by(&:id)
+ raw_ids.filter_map { |id| records[id] }
+ else
+ scope.none
+ end
+
+ pagy = build_pagy(ms_result, page, limit)
+
+ Spree::SearchProvider::SearchResult.new(
+ products: products,
+ total_count: ms_result['totalHits'] || 0,
+ pagy: pagy
+ )
+ end
+
+ def filters(scope:, query: nil, filters: {})
+ collection = filters.is_a?(Hash) ? (filters['_collection'] || filters[:_collection]) : nil
+ default_sort = collection ? to_api_sort(collection.sort_order) : 'manual'
+
+ ms_result, facet_distribution = execute_search(query: query, filters: filters, sort: nil, page: 1, limit: 0, return_facets: true)
+
+ unless ms_result
+ return Spree::SearchProvider::FiltersResult.new(
+ filters: [],
+ sort_options: built_in_and_custom_field_sort_options,
+ default_sort: default_sort,
+ total_count: 0
+ )
+ end
+
+ Spree::SearchProvider::FiltersResult.new(
+ filters: build_facet_response(facet_distribution, ms_result['facetStats'] || {}),
+ sort_options: built_in_and_custom_field_sort_options,
+ default_sort: default_sort,
+ total_count: ms_result['totalHits'] || 0
+ )
+ end
+
+ def index(product)
+ ensure_index_settings_once!
+ documents = presenter_class.new(product, store).call
+ # Delete first: membership docs use grouping-specific ids, so a product
+ # that left a grouping would otherwise leave an orphaned stale doc.
+ remove_by_id(product.prefixed_id)
+ client.index(index_name).add_documents(documents, 'id')
+ end
+
+ def remove(product)
+ remove_by_id(product.prefixed_id)
+ end
+
+ def index_batch(documents)
+ return if documents.empty?
+
+ client.index(index_name).add_documents(documents, 'id')
+ end
+
+ # Remove all documents for a product by its prefixed_id (e.g. 'prod_abc')
+ def remove_by_id(prefixed_id)
+ filter = "product_id = '#{sanitize_prefixed_id(prefixed_id)}'"
+ client.index(index_name).delete_documents(filter: filter)
+ rescue ::Meilisearch::ApiError => e
+ raise unless e.http_code == 404
+ end
+
+ def reindex(scope = nil)
+ full_reindex = scope.nil?
+ scope ||= store.products
+ @custom_field_schema = Spree::SearchProvider::CustomFieldSchema.new
+ ensure_index_settings!
+
+ # On a full reindex, clear first so stale docs (e.g. membership docs for
+ # removed groupings) don't linger; a scoped reindex keeps upsert semantics.
+ client.index(index_name).delete_all_documents if full_reindex
+
+ indexed = 0
+ scope.reorder(id: :asc)
+ .preload_associations_lazily
+ .find_in_batches(batch_size: 500) do |batch|
+ documents = batch.flat_map { |product| presenter_class.new(product, store).call }
+ next if documents.empty?
+
+ index_batch(documents)
+ indexed += documents.size
+
+ Rails.logger.info { "[Meilisearch] Enqueued #{documents.size} documents (#{indexed} total) for #{index_name}" }
+ end
+
+ Rails.logger.info { "[Meilisearch] Reindex complete: #{indexed} documents enqueued for #{index_name}" }
+ indexed
+ end
+
+ # Configure index settings for filtering, sorting, and faceting.
+ # Called automatically by reindex, but can be called separately.
+ # Waits for all settings tasks to complete before returning so that
+ # subsequent add_documents calls use the correct filterable/sortable attributes.
+ def ensure_index_settings!
+ index = client.index(index_name)
+ tasks = []
+ tasks << index.update_filterable_attributes(filterable_attributes)
+ tasks << index.update_sortable_attributes(sortable_attributes)
+ tasks << index.update_searchable_attributes(searchable_attributes)
+ tasks << index.update_distinct_attribute(distinct_attribute)
+ tasks.each { |task| task&.await }
+ @index_settings_configured = true
+ end
+
+ # Lightweight guard — configures index settings once per provider instance.
+ # Meilisearch settings updates are idempotent, so repeated calls are safe
+ # but we avoid the overhead by memoizing.
+ def ensure_index_settings_once!
+ return if @index_settings_configured
+
+ ensure_index_settings!
+ end
+
+ private
+
+ # Normalize incoming filters to a plain, string-keyed Hash.
+ def normalize_filters(filters)
+ filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
+ (filters || {}).stringify_keys
+ end
+
+ # Manual/position sort. When a single grouping is being viewed (in_collection
+ # or in_category) and the effective sort is 'manual' — either requested, or
+ # the grouping-page default (blank ⇒ manual) — query the per-grouping
+ # membership docs: swap the membership filter for `grouping_id` and sort by
+ # the scalar `position`. Without a grouping, 'manual' has nothing to order by,
+ # so it falls back to Meilisearch default ranking.
+ def resolve_manual_sort(sort, filters)
+ grouping_id = filters['in_collection'] || filters['in_category']
+ grouping_id = nil unless valid_prefixed_id?(grouping_id)
+ sort = 'manual' if sort.blank? && grouping_id
+
+ if sort == 'manual' && grouping_id
+ filters = filters.except('in_collection', 'in_category').merge('grouping_id' => grouping_id)
+ elsif sort == 'manual'
+ sort = nil
+ end
+
+ [sort, filters]
+ end
+
+ # Execute a Meilisearch query. Returns [ms_result, facet_distribution].
+ # facet_distribution is empty when return_facets is false. Returns nil on API error.
+ def execute_search(query:, filters:, sort:, page:, limit:, return_facets: false)
+ filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
+ filters = (filters || {}).stringify_keys
+
+ option_value_ids = extract_and_delete(filters, 'with_option_value_ids')
+ grouped_options = group_option_values_by_type(Array(option_value_ids))
+
+ base_conditions = build_filters(filters)
+ option_conditions = build_grouped_option_conditions(grouped_options)
+ all_conditions = base_conditions + option_conditions
+
+ # Page-based (exhaustive) pagination — REQUIRED so `distinct` collapses
+ # totalHits and facetDistribution to per-product counts. The offset/limit
+ # ("estimatedTotalHits") mode does NOT apply distinct to the count or
+ # facets, which over-counts the duplicated per-grouping membership docs.
+ search_params = {
+ filter: all_conditions,
+ facets: return_facets ? facet_attributes : nil,
+ sort: build_sort(sort),
+ page: page,
+ hitsPerPage: limit
+ }.compact
+
+ Rails.logger.debug { "[Meilisearch] index=#{index_name} query=#{query.inspect} #{search_params.compact.inspect}" }
+
+ settings_refreshed = false
+ begin
+ if return_facets && grouped_options.any?
+ queries = [{ indexUid: index_name, q: query.to_s, **search_params }]
+ option_type_ids_ordered = grouped_options.keys
+ option_type_ids_ordered.each do |option_type_id|
+ without_this = build_grouped_option_conditions(grouped_options.except(option_type_id))
+ queries << { indexUid: index_name, q: query.to_s, filter: base_conditions + without_this, facets: ['option_value_ids'], page: 1, hitsPerPage: 0 }
+ end
+
+ results = client.multi_search(queries)
+ ms_result = results['results'][0]
+ facet_distribution = merge_disjunctive_facets(ms_result, results['results'][1..], option_type_ids_ordered)
+ else
+ ms_result = client.index(index_name).search(query.to_s, search_params)
+ facet_distribution = ms_result['facetDistribution'] || {}
+ end
+ rescue ::Meilisearch::ApiError => e
+ # Self-heal when a newly added filterable attribute (e.g. `preorder`)
+ # is referenced before the index settings were refreshed — otherwise
+ # every search on an upgraded store returns empty until a reindex or
+ # the next product write.
+ if %w[invalid_search_filter invalid_search_sort].include?(e.code) && !settings_refreshed
+ settings_refreshed = true
+ ensure_index_settings!
+ retry
+ end
+
+ Rails.logger.warn { "[Meilisearch] Search failed: #{e.message}. Run `rake spree:search:reindex` to initialize the index." }
+ Rails.error.report(e, handled: true, context: { index: index_name, query: query })
+ return nil
+ end
+
+ Rails.logger.debug { "[Meilisearch] #{ms_result['totalHits']} hits in #{ms_result['processingTimeMs']}ms" }
+
+ [ms_result, facet_distribution]
+ end
+
+ def merge_disjunctive_facets(ms_result, disjunctive_results, option_type_ids_ordered)
+ main_ov_dist = ms_result.dig('facetDistribution', 'option_value_ids') || {}
+
+ all_ov_prefixed_ids = Set.new
+ disjunctive_dists = {}
+ disjunctive_results.each_with_index do |r, idx|
+ dist = r.dig('facetDistribution', 'option_value_ids') || {}
+ disjunctive_dists[option_type_ids_ordered[idx]] = dist
+ all_ov_prefixed_ids.merge(dist.keys)
+ end
+
+ all_raw_ids = all_ov_prefixed_ids.filter_map { |pid| Spree::OptionValue.decode_prefixed_id(pid) }
+ ov_to_type = Spree::OptionValue.where(id: all_raw_ids).pluck(:id, :option_type_id).to_h
+ prefixed_to_type = all_ov_prefixed_ids.each_with_object({}) do |pid, h|
+ raw = Spree::OptionValue.decode_prefixed_id(pid)
+ h[pid] = ov_to_type[raw] if raw
+ end
+
+ merged_ov_dist = main_ov_dist.dup
+ disjunctive_dists.each do |option_type_id, dist|
+ dist.each do |pid, count|
+ merged_ov_dist[pid] = count if prefixed_to_type[pid] == option_type_id
+ end
+ end
+
+ (ms_result['facetDistribution'] || {}).merge('option_value_ids' => merged_ov_dist)
+ end
+
+ def presenter_class
+ Spree::Dependencies.search_product_presenter_class
+ end
+
+ def client
+ @client ||= SpreeMeilisearch.client
+ end
+
+ def index_name
+ "#{store.code}_products"
+ end
+
+ def searchable_attributes
+ %w[name description sku option_values category_names tags] + custom_field_schema.searchable_attribute_keys
+ end
+
+ def filterable_attributes
+ BUILT_IN_FILTERABLE_ATTRIBUTES + custom_field_schema.filterable_attribute_keys
+ end
+
+ def sortable_attributes
+ %w[name price created_at available_on units_sold_count position] + custom_field_schema.sortable_attribute_keys
+ end
+
+ # Facets stay built-in only — cf_* distributions aren't consumed by
+ # +build_facet_response+, so requesting them would be wasted work.
+ def facet_attributes
+ BUILT_IN_FILTERABLE_ATTRIBUTES
+ end
+
+ # Collapses the per-grouping membership docs to one row per product on
+ # non-grouping queries (shop-all, search, non-manual sorts). Facet counts
+ # and totals honor distinct on Meilisearch >= 1.40.
+ def distinct_attribute
+ 'product_id'
+ end
+
+ # Sourced from Spree::Collection::SORT_ORDERS (matching FiltersAggregator) so
+ # both providers advertise identical options — including 'manual'.
+ def available_sort_options
+ Spree::Collection::SORT_ORDERS.map { |sort_order| to_api_sort(sort_order) } + custom_field_schema.sort_ids
+ end
+
+ # Converts internal sort format ('price asc') to API format ('price', '-price').
+ def to_api_sort(sort_value)
+ return sort_value unless sort_value.to_s.include?(' ')
+
+ field, direction = sort_value.split(' ', 2)
+ direction == 'desc' ? "-#{field}" : field
+ end
+
+ def built_in_and_custom_field_sort_options
+ Spree::Collection::SORT_ORDERS.map { |sort_order| { id: to_api_sort(sort_order), label: nil } } +
+ custom_field_schema.sort_options
+ end
+
+ # Build Meilisearch filter conditions from API params.
+ # Combines system scoping (always applied) with user-facing filters.
+ def build_filters(filters)
+ conditions = system_filter_conditions
+ conditions.concat(user_filter_conditions(filters))
+ conditions
+ end
+
+ # System scoping — always applied. Rarely overridden.
+ # Mirrors the AR scope: store.products.active(currency) with locale.
+ def system_filter_conditions
+ now = Time.current
+ conditions = []
+ conditions << "store_ids = '#{store.id}'"
+ conditions << "channel_ids = '#{Spree::Current.channel.id}'" if Spree::Current.channel
+ conditions << "status = 'active'"
+ conditions << "locale = '#{locale.to_s.gsub(/[^a-zA-Z_-]/, '')}'"
+ conditions << "currency = '#{currency.to_s.gsub(/[^A-Z]/, '')}'"
+ # Exclude future-dated products — mirrors
+ # +Product.available(Time.current, include_preorderable: true)+. ISO 8601
+ # strings sort lexicographically in chronological order, so the string
+ # compare is sound; +NOT EXISTS+/+IS NULL+ keep the available_on clause
+ # backward-compatible with legacy docs. The trailing +preorder = true+
+ # keeps scheduled "coming soon" pre-orders searchable before their
+ # publish date. It filters on the new +preorder+ attribute, so a
+ # +rake spree:search:reindex+ (or the next product write, which refreshes
+ # the index settings) is required after deploy before it takes effect.
+ conditions << "(available_on NOT EXISTS OR available_on IS NULL OR available_on <= '#{now.iso8601}' OR preorder = true)"
+ conditions << "(discontinue_on = 0 OR discontinue_on > #{now.to_i})"
+ conditions
+ end
+
+ # User-facing filters — override to add custom filter pre/post processing.
+ def user_filter_conditions(filters)
+ conditions = []
+ filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
+ return conditions if filters.blank?
+
+ filters.each do |key, value|
+ next if value.blank?
+
+ condition = build_filter_condition(key.to_s, value)
+ if condition.is_a?(Array)
+ conditions.concat(condition)
+ elsif condition
+ conditions << condition
+ end
+ end
+
+ conditions
+ end
+
+ # Translate a single Ransack-style filter param into Meilisearch filter syntax.
+ # Override in subclasses to handle custom filter keys — call super for built-in filters.
+ def build_filter_condition(key, value)
+ case key
+ when 'price_gte'
+ "price >= #{value.to_f}"
+ when 'price_lte'
+ "price <= #{value.to_f}"
+ when 'in_stock'
+ 'in_stock = true' if value.to_s != '0'
+ when 'out_of_stock'
+ 'in_stock = false' if value.to_s != '0'
+ when 'in_category'
+ "category_ids = '#{sanitize_prefixed_id(value)}'" if valid_prefixed_id?(value)
+ when 'in_categories'
+ parts = Array(value).filter_map { |id| "category_ids = '#{sanitize_prefixed_id(id)}'" if valid_prefixed_id?(id) }
+ parts.length > 1 ? "(#{parts.join(' OR ')})" : parts.first
+ when 'in_collection'
+ "collection_ids = '#{sanitize_prefixed_id(value)}'" if valid_prefixed_id?(value)
+ when 'grouping_id'
+ "grouping_id = '#{sanitize_prefixed_id(value)}'" if valid_prefixed_id?(value)
+ when 'with_option_value_ids'
+ # Handled by grouped option conditions in search_and_filter — skip here
+ nil
+ else
+ custom_field_filter_condition(key, value)
+ end
+ end
+
+ # Meilisearch has stable filter operators for equality, ranges, and
+ # EXISTS — but no string contains/starts/ends (CONTAINS is still
+ # experimental), so those predicates are ignored here. The Database
+ # provider supports the full predicate set.
+ def custom_field_filter_condition(key, value)
+ parsed = custom_field_schema.parse_filter(key)
+ return nil unless parsed
+
+ attribute = parsed[:definition].filter_key
+ numeric = parsed[:definition].field_type == 'number'
+
+ case parsed[:predicate]
+ when 'present'
+ "#{attribute} EXISTS"
+ when 'blank'
+ "#{attribute} NOT EXISTS"
+ when 'eq', 'not_eq'
+ operator = parsed[:predicate] == 'eq' ? '=' : '!='
+ formatted = format_custom_field_filter_value(value, numeric)
+ formatted && "#{attribute} #{operator} #{formatted}"
+ when *CUSTOM_FIELD_RANGE_OPERATORS.keys
+ return nil unless numeric
+
+ formatted = format_custom_field_filter_value(value, numeric)
+ formatted && "#{attribute} #{CUSTOM_FIELD_RANGE_OPERATORS[parsed[:predicate]]} #{formatted}"
+ end
+ end
+
+ def format_custom_field_filter_value(value, numeric)
+ if numeric
+ Float(value.to_s, exception: false)&.to_s
+ else
+ "'#{escape_filter_string(value)}'"
+ end
+ end
+
+ def escape_filter_string(value)
+ value.to_s.gsub('\\') { '\\\\' }.gsub("'") { "\\'" }
+ end
+
+ # Group prefixed option value IDs by option type (single DB query).
+ # Returns { option_type_id => ['optval_abc', 'optval_def'], ... }
+ def group_option_values_by_type(prefixed_ids)
+ prefixed_ids = prefixed_ids.flatten.compact.select { |id| valid_prefixed_id?(id) }
+ return {} if prefixed_ids.empty?
+
+ raw_ids = prefixed_ids.filter_map { |id| Spree::OptionValue.decode_prefixed_id(id) }
+ Spree::OptionValue.where(id: raw_ids).group_by(&:option_type_id).transform_values { |ovs| ovs.map(&:prefixed_id) }
+ end
+
+ # Build Meilisearch filter conditions from grouped option values.
+ # OR within each option type, AND across option types.
+ def build_grouped_option_conditions(grouped)
+ grouped.map do |_, prefixed_ids|
+ parts = prefixed_ids.map { |id| "option_value_ids = '#{sanitize_prefixed_id(id)}'" }
+ parts.length > 1 ? "(#{parts.join(' OR ')})" : parts.first
+ end
+ end
+
+ def extract_and_delete(hash, *keys)
+ keys.each do |key|
+ value = hash.delete(key) || hash.delete(key.to_sym)
+ return value if value.present?
+ end
+ nil
+ end
+
+ # Sort param to Meilisearch sort syntax.
+ # Override in subclasses to handle custom sort keys — call super for built-in sorts.
+ def build_sort(sort)
+ return nil if sort.blank?
+
+ sort_mapping(sort)
+ end
+
+ # Map a sort param to Meilisearch sort syntax.
+ # Override in subclasses to add custom sorts — call super for built-in sorts.
+ def sort_mapping(sort)
+ case sort
+ when 'manual' then ['position:asc']
+ when 'price' then ['price:asc']
+ when '-price' then ['price:desc']
+ when 'name' then ['name:asc']
+ when '-name' then ['name:desc']
+ when '-available_on' then ['available_on:desc']
+ when 'available_on' then ['available_on:asc']
+ when 'best_selling' then ['units_sold_count:desc']
+ else
+ parsed = custom_field_schema.parse_sort(sort)
+ parsed && ["#{parsed[:attribute]}:#{parsed[:direction]}"]
+ end
+ end
+
+ # Transform Meilisearch facetDistribution into standard filter response format.
+ # Override in subclasses to add custom facets — call super and append.
+ def build_facet_response(facet_distribution, facet_stats = {})
+ facets = []
+ facets << build_price_facet(facet_distribution['price'], facet_stats['price']) if facet_distribution['price'].present?
+ facets << build_availability_facet(facet_distribution['in_stock']) if facet_distribution['in_stock'].present?
+ facets.concat(build_option_facets(facet_distribution['option_value_ids'])) if facet_distribution['option_value_ids'].present?
+ facets << build_category_facet(facet_distribution['category_ids']) if facet_distribution['category_ids'].present?
+ facets.compact
+ end
+
+ # Bounds come from facetStats, which Meilisearch computes across every
+ # matching document. The distribution is capped at maxValuesPerFacet (100
+ # by default), so deriving min/max from its keys understates the range on
+ # any result set with more distinct prices than that.
+ def build_price_facet(distribution, stats = nil)
+ amounts = distribution.keys.map(&:to_f)
+ {
+ id: 'price',
+ type: 'price_range',
+ min: stats ? stats['min'].to_f : amounts.min,
+ max: stats ? stats['max'].to_f : amounts.max,
+ currency: currency
+ }
+ end
+
+ def build_availability_facet(distribution)
+ {
+ id: 'availability',
+ type: 'availability',
+ options: [
+ { id: 'in_stock', count: distribution['true'] || 0 },
+ { id: 'out_of_stock', count: distribution['false'] || 0 }
+ ]
+ }
+ end
+
+ def build_option_facets(distribution)
+ prefixed_ids = distribution.keys
+ raw_ids = prefixed_ids.filter_map { |pid| Spree::OptionValue.decode_prefixed_id(pid) }
+ option_values = Spree::OptionValue.where(id: raw_ids).includes(:option_type).preload_associations_lazily.index_by(&:prefixed_id)
+
+ # Group by option type
+ by_option_type = {}
+ distribution.each do |ov_prefixed_id, count|
+ ov = option_values[ov_prefixed_id]
+ next unless ov
+
+ ot = ov.option_type
+ by_option_type[ot] ||= []
+ by_option_type[ot] << {
+ id: ov.prefixed_id, name: ov.name, label: ov.label, position: ov.position,
+ color_code: ov.color_code,
+ image_url: ov.image.attached? ? Rails.application.routes.url_helpers.cdn_image_url(ov.image) : nil,
+ count: count
+ }
+ end
+
+ by_option_type.map do |option_type, values|
+ {
+ id: option_type.prefixed_id,
+ type: 'option',
+ name: option_type.name,
+ label: option_type.label,
+ kind: option_type.kind,
+ options: values.sort_by { |o| o[:position] }
+ }
+ end
+ end
+
+ def build_category_facet(distribution)
+ prefixed_ids = distribution.keys
+ raw_ids = prefixed_ids.filter_map { |pid| Spree::Category.decode_prefixed_id(pid) }
+ categories = Spree::Category.where(id: raw_ids).index_by(&:prefixed_id)
+
+ {
+ id: 'categories',
+ type: 'category',
+ options: distribution.filter_map do |prefixed_id, count|
+ cat = categories[prefixed_id]
+ next unless cat
+
+ { id: cat.prefixed_id, name: cat.name, permalink: cat.permalink, count: count }
+ end
+ }
+ end
+
+ def build_pagy(ms_result, page, limit)
+ fake_result = Struct.new(:raw_answer).new({
+ 'totalHits' => ms_result['totalHits'] || 0,
+ 'hitsPerPage' => limit,
+ 'page' => page
+ })
+
+ Pagy::MeilisearchPaginator.paginate(fake_result, {})
+ end
+
+ def empty_result(scope, page, limit)
+ Spree::SearchProvider::SearchResult.new(
+ products: scope.none,
+ total_count: 0,
+ pagy: Pagy::Offset.new(count: 0, page: page, limit: limit)
+ )
+ end
+
+ def valid_prefixed_id?(value)
+ value.to_s.match?(PREFIXED_ID_PATTERN)
+ end
+
+ def sanitize_prefixed_id(value)
+ value.to_s.gsub(/[^a-zA-Z0-9_]/, '')
+ end
+ end
+end
diff --git a/spree/providers/meilisearch/app/presenters/spree_meilisearch/product_presenter.rb b/spree/providers/meilisearch/app/presenters/spree_meilisearch/product_presenter.rb
new file mode 100644
index 0000000000..72828c8146
--- /dev/null
+++ b/spree/providers/meilisearch/app/presenters/spree_meilisearch/product_presenter.rb
@@ -0,0 +1,219 @@
+module SpreeMeilisearch
+ # Builds the Meilisearch documents for a product. The shape is Meilisearch's
+ # own: flat, denormalized, one document per (locale × currency) the product is
+ # priced in, plus the membership documents a manual sort depends on.
+ class ProductPresenter
+ attr_reader :product, :store
+
+ def initialize(product, store)
+ @product = product
+ @store = store
+ end
+
+ # Returns an array of documents. For each (market × locale) the product is
+ # priced in, one BASE document plus one MEMBERSHIP document per grouping the
+ # product belongs to (each collection + each category ancestor-or-self),
+ # carrying a scalar grouping_id + position so Meilisearch can sort a grouping
+ # page by the merchant's hand-set position. Each document has flat name,
+ # description, price fields (no dynamic suffixes).
+ def call
+ documents = []
+
+ market_locale_pairs.each do |market, locale|
+ # Skip if product has no price in this currency
+ next unless lowest_price(market.currency)
+
+ Mobility.with_locale(locale) do
+ base = build_document(locale, market.currency, default_locale)
+ documents << base
+ documents.concat(membership_documents(base, locale, market.currency))
+ end
+ end
+
+ # Fallback for stores without markets (legacy/test)
+ if documents.empty?
+ fallback_currency = store.default_market&.currency || store.supported_currencies_list.first&.iso_code
+ if fallback_currency && lowest_price(fallback_currency)
+ base = build_document(default_locale, fallback_currency, default_locale)
+ documents << base
+ documents.concat(membership_documents(base, default_locale, fallback_currency))
+ end
+ end
+
+ documents
+ end
+
+ private
+
+ # Build a document for a given locale and currency
+ # @param locale [String] the locale to build the document for
+ # @param currency [String] the currency to build the document for
+ # @param fallback_locale [String] the fallback locale to use if the product has no translation for the given locale
+ # @return [Hash] the document
+ def build_document(locale, currency, fallback_locale)
+ {
+ # Composite ID: product + locale + currency
+ id: "#{product.prefixed_id}_#{locale}_#{currency}",
+ product_id: product.prefixed_id,
+ locale: locale.to_s,
+ currency: currency,
+ # Translated fields — with fallback to default locale
+ name: translated(product, :name, fallback_locale),
+ # Indexed as plain text — HTML tag names would otherwise become
+ # searchable tokens.
+ description: Spree::RichTextHelper.to_plain_text(translated(product, :description, fallback_locale)),
+ slug: translated(product, :slug, fallback_locale),
+ # Price in this currency
+ price: lowest_price(currency)&.to_f,
+ compare_at_price: compare_at_price(currency)&.to_f,
+ # Non-locale/currency fields
+ status: product.status,
+ sku: product.sku,
+ in_stock: product.in_stock?,
+ # True when the product has an active pre-order variant, so a
+ # scheduled (future-published) launch still surfaces in search.
+ preorder: product.preorder?,
+ store_ids: Array(product.store_id).map(&:to_s),
+ channel_ids: channel_ids_for_store,
+ discontinue_on: product.discontinue_on&.to_i || 0,
+ category_ids: category_ids_with_ancestors,
+ category_names: product.categories.map { |t| translated(t, :name, fallback_locale) },
+ collection_ids: product.collections.map(&:prefixed_id),
+ option_type_ids: product.option_types.map(&:prefixed_id),
+ option_type_names: product.option_types.map { |ot| translated(ot, :presentation, fallback_locale) },
+ option_value_ids: variant_option_value_ids,
+ option_values: variant_option_values_data.map { |ov| translated(ov, :presentation, fallback_locale) }.uniq,
+ tags: product.tag_list || [],
+ units_sold_count: product.units_sold_count || 0,
+ available_on: product.available_on&.iso8601,
+ created_at: product.created_at&.iso8601,
+ updated_at: product.updated_at&.iso8601
+ }.merge(custom_field_document_attributes)
+ end
+
+ # Flat cf_* hash for searchable ∪ sortable custom_fields (Meilisearch docs).
+ def custom_field_document_attributes
+ @custom_field_document_attributes ||= product.custom_fields.filter_map do |custom_field|
+ definition = custom_field.custom_field_definition
+ next unless definition&.searchable? || definition&.sortable?
+
+ [definition.filter_key, custom_field_index_value(custom_field, definition.field_type)]
+ end.to_h
+ end
+
+ def custom_field_index_value(custom_field, field_type)
+ serialized = custom_field.serialize_value
+ case field_type
+ when 'number'
+ serialized.to_f
+ else
+ serialized.to_s
+ end
+ end
+
+ # Returns all market × locale pairs for this store
+ def market_locale_pairs
+ @market_locale_pairs ||= store.markets.flat_map do |market|
+ market.supported_locales_list.map { |locale| [market, locale] }
+ end
+ end
+
+ def default_locale
+ @default_locale ||= store.default_market&.default_locale || I18n.default_locale.to_s
+ end
+
+ # Read a translated attribute with fallback to default locale.
+ def translated(record, attribute, fallback_locale)
+ value = record.send(attribute)
+ return value if value.present?
+
+ record.send(attribute, locale: fallback_locale.to_sym)
+ rescue ArgumentError
+ value
+ end
+
+ def lowest_price(currency)
+ @prices_cache ||= {}
+ @prices_cache[currency] = product.price_in(currency)&.amount unless @prices_cache.key?(currency)
+ @prices_cache[currency]
+ end
+
+ def compare_at_price(currency)
+ @compare_at_cache ||= {}
+ @compare_at_cache[currency] = product.compare_at_amount_in(currency) unless @compare_at_cache.key?(currency)
+ @compare_at_cache[currency]
+ end
+
+ def channel_ids_for_store
+ @channel_ids_for_store ||= product.product_publications
+ .joins(:channel)
+ .where(spree_channels: { store_id: store.id })
+ .pluck(:channel_id)
+ .map(&:to_s)
+ end
+
+ def category_ids_with_ancestors
+ @category_ids_with_ancestors ||= product.categories.flat_map { |t|
+ t.self_and_ancestors.map(&:prefixed_id)
+ }.uniq
+ end
+
+ # One membership document per grouping (each collection + each category
+ # ancestor-or-self) the product belongs to: the full base payload plus a
+ # scalar grouping_id and position, with a distinct composite id. A manual-
+ # sorted grouping page filters grouping_id and sorts by position.
+ def membership_documents(base, locale, currency)
+ grouping_positions.map do |grouping_id, position|
+ base.merge(
+ id: "#{product.prefixed_id}__#{grouping_id}_#{locale}_#{currency}",
+ grouping_id: grouping_id,
+ position: position
+ )
+ end
+ end
+
+ # { grouping_prefixed_id => position }, merged across collections (flat) and
+ # categories (subtree-MIN). Prefixes (coll_/ctg_) keep the keys disjoint.
+ def grouping_positions
+ @grouping_positions ||= collection_positions.merge(category_positions)
+ end
+
+ # Flat: one entry per collection with the product's ProductCollection.position.
+ def collection_positions
+ @collection_positions ||= product.product_collections.pluck(:collection_id, :position).each_with_object({}) do |(cid, pos), acc|
+ acc[prefixed_id_for(Spree::Collection, cid)] = pos
+ end
+ end
+
+ # Subtree-MIN: a product under a category AND its descendants contributes its
+ # position to every ancestor-or-self, folded to the minimum — mirrors the DB
+ # provider's MIN(position)/GROUP BY and category_ids_with_ancestors.
+ def category_positions
+ @category_positions ||= begin
+ positions_by_category_id = product.product_categories.pluck(:category_id, :position).to_h
+ product.categories.each_with_object({}) do |category, acc|
+ position = positions_by_category_id[category.id]
+ category.self_and_ancestors.each do |ancestor|
+ key = ancestor.prefixed_id
+ acc[key] = [acc[key], position].compact.min
+ end
+ end
+ end
+ end
+
+ # Encode a raw primary key into a model's prefixed id without loading the
+ # record (mirrors Spree::PrefixedId#prefixed_id).
+ def prefixed_id_for(klass, raw_id)
+ "#{klass._prefix_id_prefix}_#{Spree::PrefixedId::SQIDS.encode([raw_id])}"
+ end
+
+ def variant_option_value_ids
+ variant_option_values_data.map(&:prefixed_id).uniq
+ end
+
+ # Use variants (matches reindex preload) instead of variants.includes
+ def variant_option_values_data
+ @variant_option_values_data ||= product.variants.flat_map(&:option_values).uniq
+ end
+ end
+end
diff --git a/spree/providers/meilisearch/lib/spree_meilisearch.rb b/spree/providers/meilisearch/lib/spree_meilisearch.rb
new file mode 100644
index 0000000000..276e6c71e3
--- /dev/null
+++ b/spree/providers/meilisearch/lib/spree_meilisearch.rb
@@ -0,0 +1,17 @@
+require 'meilisearch'
+require 'pagy/toolbox/paginators/meilisearch'
+require 'spree_core'
+require 'spree_meilisearch/engine'
+
+module SpreeMeilisearch
+ # Meilisearch server the store's index lives on. Credentials are read from the
+ # environment rather than a Spree::Integration record because the index is
+ # infrastructure — one server serves every store in the installation, and the
+ # rake reindex task has to reach it outside a request.
+ def self.client
+ ::Meilisearch::Client.new(
+ ENV.fetch('MEILISEARCH_URL', 'http://localhost:7700'),
+ ENV['MEILISEARCH_API_KEY']
+ )
+ end
+end
diff --git a/spree/providers/meilisearch/lib/spree_meilisearch/engine.rb b/spree/providers/meilisearch/lib/spree_meilisearch/engine.rb
new file mode 100644
index 0000000000..533a8adf2c
--- /dev/null
+++ b/spree/providers/meilisearch/lib/spree_meilisearch/engine.rb
@@ -0,0 +1,25 @@
+require 'rails/engine'
+
+module SpreeMeilisearch
+ class Engine < Rails::Engine
+ engine_name 'spree_meilisearch'
+
+ # Gem name and module disagree on word boundaries (spree_meilisearch →
+ # SpreeMeilisearch), so Zeitwerk needs telling once.
+ initializer 'spree_meilisearch.inflections', before: :set_autoload_paths do
+ Rails.autoloaders.each do |autoloader|
+ autoloader.inflector.inflect('spree_meilisearch' => 'SpreeMeilisearch')
+ end
+ end
+
+ config.after_initialize do
+ # The document shape is Meilisearch's own — one document per locale and
+ # currency, plus per-grouping membership documents carrying the position a
+ # manual sort orders by. Installing the gem therefore also supplies the
+ # presenter that builds it, unless the application named its own subclass.
+ unless Spree::Dependencies.overridden?(:search_product_presenter)
+ Spree::Dependencies.search_product_presenter = 'SpreeMeilisearch::ProductPresenter'
+ end
+ end
+ end
+end
diff --git a/spree/providers/meilisearch/spec/controllers/spree_meilisearch/products_controller_spec.rb b/spree/providers/meilisearch/spec/controllers/spree_meilisearch/products_controller_spec.rb
new file mode 100644
index 0000000000..c2fe676ef0
--- /dev/null
+++ b/spree/providers/meilisearch/spec/controllers/spree_meilisearch/products_controller_spec.rb
@@ -0,0 +1,161 @@
+require 'spec_helper'
+
+# The Store API products controller delegating to the Meilisearch provider —
+# the wiring that only holds when this gem is installed. Provider-agnostic
+# controller behaviour is covered by spree_api's own products controller spec.
+RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
+ # The dummy app mounts only spree_core's routes, so drive the real controller
+ # through an anonymous subclass rather than the named route.
+ controller(Spree::Api::V3::Store::ProductsController) {}
+
+ render_views
+
+ include_context 'API v3 Store'
+
+ let!(:product) { create(:product, status: 'active') }
+ let!(:product2) { create(:product, status: 'active') }
+ let!(:draft_product) { create(:product, status: 'draft') }
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ after do
+ I18n.locale = store.default_locale
+ end
+
+ describe 'GET #index' do
+ let(:mock_client) { instance_double(::Meilisearch::Client) }
+ let(:mock_index) { double('Meilisearch::Index') }
+
+ before do
+ allow(Spree).to receive(:search_provider).and_return('SpreeMeilisearch::SearchProvider')
+ allow(::Meilisearch::Client).to receive(:new).and_return(mock_client)
+ allow(mock_client).to receive(:index).and_return(mock_index)
+ end
+
+ after do
+ allow(Spree).to receive(:search_provider).and_call_original
+ end
+
+ it 'searches via Meilisearch when q[search] is present' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'product_id' => product.prefixed_id }],
+ 'totalHits' => 1,
+ 'facetDistribution' => {}
+ })
+
+ get :index, params: { q: { search: 'shirt' } }
+
+ expect(response).to have_http_status(:ok)
+ expect(mock_index).to have_received(:search).with('shirt', hash_including(:page, :hitsPerPage))
+
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(product.prefixed_id)
+ expect(ids).not_to include(product2.prefixed_id)
+ end
+
+ it 'respects AR scope visibility (does not return draft products from Meilisearch)' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'product_id' => product.prefixed_id }, { 'product_id' => draft_product.prefixed_id }],
+ 'totalHits' => 2,
+ 'facetDistribution' => {}
+ })
+
+ get :index, params: { q: { search: 'test' } }
+
+ expect(response).to have_http_status(:ok)
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(product.prefixed_id)
+ expect(ids).not_to include(draft_product.prefixed_id)
+ end
+
+ it 'uses Meilisearch for browsing without search query' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'product_id' => product.prefixed_id }, { 'product_id' => product2.prefixed_id }],
+ 'totalHits' => 2,
+ 'facetDistribution' => {}
+ })
+
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(mock_index).to have_received(:search)
+ expect(json_response['data'].size).to eq(2)
+ end
+
+ it 'filters by current locale in Meilisearch' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'product_id' => product.prefixed_id }],
+ 'totalHits' => 1,
+ 'facetDistribution' => {}
+ })
+
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(mock_index).to have_received(:search).with(anything, hash_including(
+ filter: include("locale = '#{store.default_locale}'")
+ ))
+ end
+
+ it 'filters by current currency in Meilisearch' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'product_id' => product.prefixed_id }],
+ 'totalHits' => 1,
+ 'facetDistribution' => {}
+ })
+
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(mock_index).to have_received(:search).with(anything, hash_including(
+ filter: include("currency = '#{store.default_currency}'")
+ ))
+ end
+
+ it 'filters by store_id in Meilisearch' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'product_id' => product.prefixed_id }],
+ 'totalHits' => 1,
+ 'facetDistribution' => {}
+ })
+
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(mock_index).to have_received(:search).with(anything, hash_including(
+ filter: include("store_ids = '#{store.id}'")
+ ))
+ end
+
+ it 'always filters by active status in Meilisearch' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'product_id' => product.prefixed_id }],
+ 'totalHits' => 1,
+ 'facetDistribution' => {}
+ })
+
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(mock_index).to have_received(:search).with(anything, hash_including(
+ filter: include("status = 'active'")
+ ))
+ end
+
+ it 'preserves Meilisearch sort order in the response' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'product_id' => product2.prefixed_id }, { 'product_id' => product.prefixed_id }],
+ 'totalHits' => 2,
+ 'facetDistribution' => {}
+ })
+
+ get :index, params: { sort: '-price' }
+
+ expect(response).to have_http_status(:ok)
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to eq([product2.prefixed_id, product.prefixed_id])
+ end
+ end
+end
diff --git a/spree/providers/meilisearch/spec/models/spree_meilisearch/deprecated_constants_spec.rb b/spree/providers/meilisearch/spec/models/spree_meilisearch/deprecated_constants_spec.rb
new file mode 100644
index 0000000000..7ac404009a
--- /dev/null
+++ b/spree/providers/meilisearch/spec/models/spree_meilisearch/deprecated_constants_spec.rb
@@ -0,0 +1,25 @@
+require 'spec_helper'
+
+# The provider moved out of spree_core at 6.0. Applications name it as a string
+# in an initializer, so the old constants keep resolving for one release.
+RSpec.describe 'deprecated Spree::SearchProvider constants' do
+ it 'resolves the old provider constant to the gem class' do
+ expect(Spree::Deprecation).to receive(:warn).with(/SpreeMeilisearch::SearchProvider/)
+
+ expect(Spree::SearchProvider::Meilisearch).to eq(SpreeMeilisearch::SearchProvider)
+ end
+
+ it 'resolves the old presenter constant to the gem class' do
+ expect(Spree::Deprecation).to receive(:warn).with(/SpreeMeilisearch::ProductPresenter/)
+
+ expect(Spree::SearchProvider::ProductPresenter).to eq(SpreeMeilisearch::ProductPresenter)
+ end
+
+ it 'still raises for genuinely unknown constants' do
+ expect { Spree::SearchProvider::Nonsense }.to raise_error(NameError)
+ end
+
+ it 'registers the gem presenter as the default document builder' do
+ expect(Spree::Dependencies.search_product_presenter).to eq('SpreeMeilisearch::ProductPresenter')
+ end
+end
diff --git a/spree/providers/meilisearch/spec/models/spree_meilisearch/search_provider_spec.rb b/spree/providers/meilisearch/spec/models/spree_meilisearch/search_provider_spec.rb
new file mode 100644
index 0000000000..dd5eae4884
--- /dev/null
+++ b/spree/providers/meilisearch/spec/models/spree_meilisearch/search_provider_spec.rb
@@ -0,0 +1,596 @@
+require 'spec_helper'
+require 'meilisearch'
+
+RSpec.describe SpreeMeilisearch::SearchProvider do
+ let(:store) { @default_store }
+ let(:provider) { described_class.new(store) }
+ let(:mock_client) { instance_double(::Meilisearch::Client) }
+ let(:mock_index) { double('MeiliSearch::Index') }
+
+ let!(:product_1) { create(:product, name: 'Blue Shirt') }
+ let!(:product_2) { create(:product, name: 'Red Pants') }
+
+ before do
+ allow(::Meilisearch::Client).to receive(:new).and_return(mock_client)
+ allow(mock_client).to receive(:index).and_return(mock_index)
+ allow(mock_index).to receive(:update_filterable_attributes)
+ allow(mock_index).to receive(:update_sortable_attributes)
+ allow(mock_index).to receive(:update_searchable_attributes)
+ allow(mock_index).to receive(:update_distinct_attribute)
+ allow(mock_index).to receive(:delete_documents)
+ end
+
+ describe '#search_and_filter' do
+ let(:ms_response) do
+ {
+ 'hits' => [
+ { 'product_id' => product_1.prefixed_id },
+ { 'product_id' => product_2.prefixed_id }
+ ],
+ 'totalHits' => 2,
+ 'facetDistribution' => {
+ 'in_stock' => { 'true' => 2 },
+ 'price' => { '19.99' => 1, '29.99' => 1 }
+ }
+ }
+ end
+
+ before do
+ allow(mock_index).to receive(:search).and_return(ms_response)
+ end
+
+ it 'returns a SearchResult' do
+ result = provider.search_and_filter(scope: store.products, query: 'shirt')
+ expect(result).to be_a(Spree::SearchProvider::SearchResult)
+ end
+
+ it 'queries Meilisearch with the search term' do
+ expect(mock_index).to receive(:search).with('shirt', hash_including(:page, :hitsPerPage))
+ provider.search_and_filter(scope: store.products, query: 'shirt')
+ end
+
+ it 'returns products from the AR scope matching Meilisearch IDs' do
+ result = provider.search_and_filter(scope: store.products, query: 'shirt')
+ expect(result.products).to include(product_1, product_2)
+ end
+
+ it 'returns total count from Meilisearch' do
+ result = provider.search_and_filter(scope: store.products, query: 'shirt')
+ expect(result.total_count).to eq(2)
+ end
+
+ it 'does not request facets from Meilisearch' do
+ expect(mock_index).to receive(:search).with(anything, satisfy { |params| !params.key?(:facets) })
+ provider.search_and_filter(scope: store.products, query: 'shirt')
+ end
+
+ context 'listing all products (no query, no filters)' do
+ it 'searches an empty query with only system conditions and no facets' do
+ expect(mock_index).to receive(:search).with('', satisfy { |p|
+ p[:filter].include?("status = 'active'") && !p.key?(:facets)
+ }).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products)
+ end
+
+ it 'returns the products and total' do
+ result = provider.search_and_filter(scope: store.products)
+
+ expect(result.products).to include(product_1, product_2)
+ expect(result.total_count).to eq(2)
+ end
+ end
+
+ context 'with no results' do
+ let(:ms_response) { { 'hits' => [], 'totalHits' => 0, 'facetDistribution' => {} } }
+
+ it 'returns empty relation' do
+ result = provider.search_and_filter(scope: store.products, query: 'nonexistent')
+ expect(result.products).to be_empty
+ expect(result.total_count).to eq(0)
+ end
+ end
+
+ context 'with price filter' do
+ it 'passes price filter to Meilisearch' do
+ expect(mock_index).to receive(:search).with(anything, hash_including(
+ filter: include('price >= 10.0')
+ )).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, filters: { 'price_gte' => '10' })
+ end
+ end
+
+ context 'with in_stock filter' do
+ it 'passes stock filter to Meilisearch' do
+ expect(mock_index).to receive(:search).with(anything, hash_including(
+ filter: include('in_stock = true')
+ )).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, filters: { 'in_stock' => '1' })
+ end
+ end
+
+ context 'with in_collection filter' do
+ let(:collection) { create(:collection) }
+
+ it 'passes the collection_ids filter to Meilisearch (non-manual sort)' do
+ expect(mock_index).to receive(:search).with(anything, hash_including(
+ filter: include("collection_ids = '#{collection.prefixed_id}'")
+ )).and_return(ms_response)
+
+ # A non-manual sort keeps the collection_ids filter; a blank/manual sort
+ # instead routes to the grouping_id membership docs (covered below).
+ provider.search_and_filter(scope: store.products, sort: 'price', filters: { 'in_collection' => collection.prefixed_id })
+ end
+
+ it 'ignores a value that is not a prefixed id' do
+ expect(mock_index).to receive(:search).with(anything, satisfy { |params|
+ params[:filter].none? { |c| c.to_s.include?('collection_ids') }
+ }).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, filters: { 'in_collection' => '123' })
+ end
+ end
+
+ context 'with sort' do
+ it 'passes price sort to Meilisearch' do
+ expect(mock_index).to receive(:search).with(anything, hash_including(
+ sort: ['price:asc']
+ )).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, sort: 'price')
+ end
+
+ it 'passes descending price sort' do
+ expect(mock_index).to receive(:search).with(anything, hash_including(
+ sort: ['price:desc']
+ )).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, sort: '-price')
+ end
+ end
+
+ context 'with pagination' do
+ it 'passes page and hitsPerPage (exhaustive mode so distinct counts are exact)' do
+ expect(mock_index).to receive(:search).with(anything, hash_including(
+ page: 2, hitsPerPage: 25
+ )).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, page: 2, limit: 25)
+ end
+ end
+
+ context 'pagination result (pagy built from totalHits)' do
+ let(:ms_response) do
+ { 'hits' => [{ 'product_id' => product_1.prefixed_id }], 'totalHits' => 50, 'facetDistribution' => {} }
+ end
+
+ it 'builds a pagy spanning all pages with a next page' do
+ result = provider.search_and_filter(scope: store.products, page: 1, limit: 25)
+
+ expect(result.total_count).to eq(50)
+ expect(result.pagy.count).to eq(50)
+ expect(result.pagy.pages).to eq(2)
+ expect(result.pagy.page).to eq(1)
+ expect(result.pagy.next).to eq(2)
+ end
+ end
+
+ context 'with manual (position) sort on a grouping' do
+ it 'queries the grouping_id membership docs sorted by position (collection)' do
+ expect(mock_index).to receive(:search).with(anything, satisfy { |p|
+ p[:filter].include?("grouping_id = 'coll_Manual1'") &&
+ p[:filter].none? { |c| c.to_s.include?('collection_ids') } &&
+ p[:sort] == ['position:asc']
+ }).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, sort: 'manual', filters: { 'in_collection' => 'coll_Manual1' })
+ end
+
+ it 'defaults a grouping page with no sort param to manual' do
+ expect(mock_index).to receive(:search).with(anything, satisfy { |p|
+ p[:filter].include?("grouping_id = 'coll_Manual1'") && p[:sort] == ['position:asc']
+ }).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, filters: { 'in_collection' => 'coll_Manual1' })
+ end
+
+ it 'works for a category grouping' do
+ expect(mock_index).to receive(:search).with(anything, satisfy { |p|
+ p[:filter].include?("grouping_id = 'ctg_Manual1'") && p[:sort] == ['position:asc']
+ }).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, sort: 'manual', filters: { 'in_category' => 'ctg_Manual1' })
+ end
+
+ it 'ignores manual sort without a grouping (falls back to default ranking)' do
+ expect(mock_index).to receive(:search).with(anything, satisfy { |p| p[:sort].nil? }).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, sort: 'manual')
+ end
+ end
+
+ context 'with sort order preservation' do
+ it 'returns products in the order Meilisearch returned them' do
+ reversed_response = {
+ 'hits' => [
+ { 'product_id' => product_2.prefixed_id },
+ { 'product_id' => product_1.prefixed_id }
+ ],
+ 'totalHits' => 2,
+ 'facetDistribution' => {}
+ }
+ allow(mock_index).to receive(:search).and_return(reversed_response)
+
+ result = provider.search_and_filter(scope: store.products, query: 'shirt')
+ expect(result.products).to eq([product_2, product_1])
+ end
+ end
+
+ context 'with visibility scope' do
+ it 'intersects Meilisearch results with AR scope' do
+ restricted_scope = store.products.where(id: product_1.id)
+ result = provider.search_and_filter(scope: restricted_scope, query: 'shirt')
+ expect(result.products).to include(product_1)
+ expect(result.products).not_to include(product_2)
+ end
+ end
+
+ # A newly added filterable or sortable attribute referenced before the
+ # index settings were refreshed rejects the whole query on upgraded
+ # stores — the provider must push settings and retry instead of serving
+ # an empty listing until a reindex.
+ context 'when a filter attribute is not yet filterable' do
+ before do
+ error = ::Meilisearch::ApiError.new(
+ 400, 'Bad Request',
+ { 'code' => 'invalid_search_filter', 'message' => 'Attribute `preorder` is not filterable.' }
+ )
+ calls = 0
+ allow(mock_index).to receive(:search) do
+ calls += 1
+ raise error if calls == 1
+
+ ms_response
+ end
+ end
+
+ it 'pushes index settings and retries the search once' do
+ expect(mock_index).to receive(:update_filterable_attributes)
+
+ result = provider.search_and_filter(scope: store.products, query: 'shirt')
+ expect(result.products).to include(product_1, product_2)
+ end
+ end
+
+ context 'when a sort attribute is not yet sortable' do
+ before do
+ error = ::Meilisearch::ApiError.new(
+ 400, 'Bad Request',
+ { 'code' => 'invalid_search_sort', 'message' => 'Attribute `cf_custom_label` is not sortable.' }
+ )
+ calls = 0
+ allow(mock_index).to receive(:search) do
+ calls += 1
+ raise error if calls == 1
+
+ ms_response
+ end
+ end
+
+ it 'pushes index settings and retries the search once' do
+ expect(mock_index).to receive(:update_sortable_attributes)
+
+ result = provider.search_and_filter(scope: store.products, query: 'shirt', sort: 'cf_custom_label')
+ expect(result.products).to include(product_1, product_2)
+ end
+ end
+ end
+
+ describe '#filters' do
+ let(:ms_response) do
+ {
+ 'hits' => [],
+ 'totalHits' => 2,
+ 'processingTimeMs' => 1,
+ 'facetDistribution' => {
+ 'in_stock' => { 'true' => 2 },
+ 'price' => { '19.99' => 1, '29.99' => 1 }
+ }
+ }
+ end
+
+ before do
+ allow(mock_index).to receive(:search).and_return(ms_response)
+ end
+
+ it 'returns a FiltersResult' do
+ result = provider.filters(scope: store.products, query: 'shirt')
+ expect(result).to be_a(Spree::SearchProvider::FiltersResult)
+ end
+
+ it 'returns facets from Meilisearch' do
+ result = provider.filters(scope: store.products, query: 'shirt')
+ expect(result.filters).to be_an(Array)
+
+ price_filter = result.filters.find { |f| f[:type] == 'price_range' }
+ expect(price_filter).to be_present
+ expect(price_filter[:min]).to eq(19.99)
+ expect(price_filter[:max]).to eq(29.99)
+ end
+
+ context 'when Meilisearch reports facet stats' do
+ # facetDistribution is capped at maxValuesPerFacet, so on a large result
+ # set its keys are a truncated sample. facetStats covers every match.
+ let(:ms_response) do
+ super().merge('facetStats' => { 'price' => { 'min' => 4.99, 'max' => 199.0 } })
+ end
+
+ it 'takes the price range from the stats rather than the truncated distribution' do
+ result = provider.filters(scope: store.products, query: 'shirt')
+
+ price_filter = result.filters.find { |f| f[:type] == 'price_range' }
+ expect(price_filter[:min]).to eq(4.99)
+ expect(price_filter[:max]).to eq(199.0)
+ end
+ end
+
+ it 'returns sort options as objects' do
+ result = provider.filters(scope: store.products, query: 'shirt')
+ ids = result.sort_options.map { |o| o[:id] }
+ expect(ids).to include('price', '-price')
+ end
+
+ it 'returns total count' do
+ result = provider.filters(scope: store.products, query: 'shirt')
+ expect(result.total_count).to eq(2)
+ end
+
+ it 'requests facets from Meilisearch' do
+ expect(mock_index).to receive(:search).with(anything, hash_including(:facets))
+ provider.filters(scope: store.products, query: 'shirt')
+ end
+
+ context 'with option type facets' do
+ let(:color_type) { create(:option_type, :color_swatch, filterable: true) }
+ let(:red_value) { create(:option_value, option_type: color_type, name: 'red', presentation: 'Red', color_code: '#FF0000') }
+ let(:blue_value) { create(:option_value, option_type: color_type, name: 'blue', presentation: 'Blue', color_code: '#0000FF') }
+
+ let(:ms_response) do
+ {
+ 'hits' => [],
+ 'totalHits' => 1,
+ 'processingTimeMs' => 1,
+ 'facetDistribution' => {
+ 'option_value_ids' => {
+ red_value.prefixed_id => 3,
+ blue_value.prefixed_id => 1
+ }
+ }
+ }
+ end
+
+ it 'includes kind on option type filters' do
+ result = provider.filters(scope: store.products, query: '')
+ color_filter = result.filters.find { |f| f[:name] == 'color' }
+
+ expect(color_filter).to be_present
+ expect(color_filter[:kind]).to eq('color_swatch')
+ end
+
+ it 'includes color_code on option values' do
+ result = provider.filters(scope: store.products, query: '')
+ color_filter = result.filters.find { |f| f[:name] == 'color' }
+ red_option = color_filter[:options].find { |o| o[:name] == 'red' }
+
+ expect(red_option[:color_code]).to eq('#FF0000')
+ end
+
+ it 'includes image_url as nil when no image attached' do
+ result = provider.filters(scope: store.products, query: '')
+ color_filter = result.filters.find { |f| f[:name] == 'color' }
+ red_option = color_filter[:options].find { |o| o[:name] == 'red' }
+
+ expect(red_option[:image_url]).to be_nil
+ end
+ end
+
+ context 'when Meilisearch API fails' do
+ before do
+ error = ::Meilisearch::ApiError.new(500, 'internal error', 'internal')
+ allow(mock_index).to receive(:search).and_raise(error)
+ end
+
+ it 'returns empty FiltersResult' do
+ result = provider.filters(scope: store.products, query: 'shirt')
+ expect(result.filters).to eq([])
+ expect(result.total_count).to eq(0)
+ end
+ end
+
+ # default_sort comes from the collection's sort_order (a collection PLP page),
+ # rendered in API format; it falls back to 'manual' with no collection.
+ context 'default_sort' do
+ it 'defaults to manual when no collection is provided' do
+ result = provider.filters(scope: store.products, query: 'shirt')
+ expect(result.default_sort).to eq('manual')
+ end
+
+ it "reflects the collection's sort_order (space format rendered as API format)" do
+ collection = create(:collection, sort_order: 'price asc')
+
+ result = provider.filters(scope: store.products, filters: { '_collection' => collection })
+ expect(result.default_sort).to eq('price')
+ end
+
+ it 'stays manual for a manual-sorted collection' do
+ collection = create(:collection, sort_order: 'manual')
+
+ result = provider.filters(scope: store.products, filters: { '_collection' => collection })
+ expect(result.default_sort).to eq('manual')
+ end
+ end
+
+ it 'advertises manual in the sort options (sourced from Collection::SORT_ORDERS)' do
+ result = provider.filters(scope: store.products, query: '')
+ expect(result.sort_options.map { |o| o[:id] }).to include('manual')
+ end
+ end
+
+ describe '#index' do
+ it 'adds documents to Meilisearch index with id as primary key' do
+ expect(mock_index).to receive(:add_documents).with(
+ array_including(hash_including(product_id: product_1.prefixed_id, name: 'Blue Shirt')),
+ 'id'
+ )
+ provider.index(product_1)
+ end
+
+ it 'uses ProductPresenter to serialize' do
+ docs = [{ id: 'prod_abc_en_USD', product_id: 'prod_abc' }]
+ presenter = instance_double(SpreeMeilisearch::ProductPresenter, call: docs)
+ allow(SpreeMeilisearch::ProductPresenter).to receive(:new).with(product_1, store).and_return(presenter)
+ expect(mock_index).to receive(:add_documents).with(docs, 'id')
+ provider.index(product_1)
+ end
+
+ it 'deletes the product existing docs before adding (purges stale membership docs)' do
+ expect(mock_index).to receive(:delete_documents).with(filter: "product_id = '#{product_1.prefixed_id}'").ordered
+ expect(mock_index).to receive(:add_documents).ordered
+ provider.index(product_1)
+ end
+ end
+
+ describe '#remove' do
+ it 'deletes all locale/currency variants by product_id filter' do
+ expect(mock_index).to receive(:delete_documents).with(filter: "product_id = '#{product_1.prefixed_id}'")
+ provider.remove(product_1)
+ end
+ end
+
+ describe '#remove_by_id' do
+ it 'deletes all documents by product_id filter' do
+ expect(mock_index).to receive(:delete_documents).with(filter: "product_id = 'prod_abc'")
+ provider.remove_by_id('prod_abc')
+ end
+
+ it 'ignores 404 errors' do
+ error = ::Meilisearch::ApiError.new(404, 'not found', 'document_not_found')
+ allow(mock_index).to receive(:delete_documents).and_raise(error)
+ expect { provider.remove_by_id('prod_abc') }.not_to raise_error
+ end
+ end
+
+ describe '#reindex' do
+ it 'configures index settings' do
+ expect(mock_index).to receive(:update_filterable_attributes)
+ expect(mock_index).to receive(:update_sortable_attributes)
+ expect(mock_index).to receive(:update_searchable_attributes)
+ allow(mock_index).to receive(:add_documents)
+
+ provider.reindex(store.products)
+ end
+
+ it 'indexes all products in batches' do
+ expect(mock_index).to receive(:add_documents).at_least(:once)
+ provider.reindex(store.products)
+ end
+
+ it 'clears the index before a full (unscoped) reindex' do
+ expect(mock_index).to receive(:delete_all_documents)
+ allow(mock_index).to receive(:add_documents)
+ provider.reindex
+ end
+
+ it 'does not clear the index for a scoped reindex' do
+ expect(mock_index).not_to receive(:delete_all_documents)
+ allow(mock_index).to receive(:add_documents)
+ provider.reindex(store.products)
+ end
+ end
+
+ describe '#ensure_index_settings!' do
+ it 'declares grouping_id filterable, position sortable, and product_id distinct' do
+ expect(mock_index).to receive(:update_filterable_attributes).with(include('grouping_id'))
+ expect(mock_index).to receive(:update_sortable_attributes).with(include('position'))
+ expect(mock_index).to receive(:update_distinct_attribute).with('product_id')
+ allow(mock_index).to receive(:update_searchable_attributes)
+
+ provider.ensure_index_settings!
+ end
+ end
+
+ describe 'custom_field searchable / sortable settings' do
+ let!(:definition) do
+ create(:custom_field_definition, :short_text_field, :searchable, :sortable,
+ namespace: 'custom', key: 'label')
+ end
+
+ it 'includes cf_* in searchable and sortable attributes' do
+ expect(provider.send(:searchable_attributes)).to include('cf_custom_label')
+ expect(provider.send(:sortable_attributes)).to include('cf_custom_label')
+ end
+
+ it 'includes cf_* in filterable attributes but not in requested facets' do
+ expect(provider.send(:filterable_attributes)).to include('cf_custom_label')
+ expect(provider.send(:facet_attributes)).not_to include('cf_custom_label')
+ end
+
+ it 'maps cf_* sort params without namespace resolution' do
+ expect(provider.send(:sort_mapping, 'cf_custom_label')).to eq(['cf_custom_label:asc'])
+ expect(provider.send(:sort_mapping, '-cf_custom_label')).to eq(['cf_custom_label:desc'])
+ end
+ end
+
+ describe 'custom_field filter conditions' do
+ let!(:label) do
+ create(:custom_field_definition, :short_text_field, :searchable,
+ namespace: 'custom', key: 'label')
+ end
+ let!(:weight) do
+ create(:custom_field_definition, :number_field, :sortable,
+ namespace: 'custom', key: 'weight')
+ end
+
+ it 'builds equality conditions for text custom_fields' do
+ expect(provider.send(:build_filter_condition, 'cf_custom_label_eq', 'wool')).to eq("cf_custom_label = 'wool'")
+ expect(provider.send(:build_filter_condition, 'cf_custom_label_not_eq', 'wool')).to eq("cf_custom_label != 'wool'")
+ end
+
+ it 'escapes quotes and backslashes in text values' do
+ expect(provider.send(:build_filter_condition, 'cf_custom_label_eq', "o'brien\\x")).to eq("cf_custom_label = 'o\\'brien\\\\x'")
+ end
+
+ it 'builds range conditions for number custom_fields' do
+ expect(provider.send(:build_filter_condition, 'cf_custom_weight_gteq', '3.5')).to eq('cf_custom_weight >= 3.5')
+ expect(provider.send(:build_filter_condition, 'cf_custom_weight_lt', '10')).to eq('cf_custom_weight < 10.0')
+ end
+
+ it 'builds EXISTS conditions for present and blank' do
+ expect(provider.send(:build_filter_condition, 'cf_custom_label_present', '1')).to eq('cf_custom_label EXISTS')
+ expect(provider.send(:build_filter_condition, 'cf_custom_label_blank', '1')).to eq('cf_custom_label NOT EXISTS')
+ end
+
+ it 'ignores substring predicates Meilisearch cannot filter on' do
+ expect(provider.send(:build_filter_condition, 'cf_custom_label_cont', 'wool')).to be_nil
+ end
+
+ it 'ignores non-numeric values on number predicates' do
+ expect(provider.send(:build_filter_condition, 'cf_custom_weight_gteq', 'abc')).to be_nil
+ end
+
+ it 'ignores unknown cf_ keys' do
+ expect(provider.send(:build_filter_condition, 'cf_bogus_field_eq', 'x')).to be_nil
+ end
+
+ it 'passes custom_field conditions through to the Meilisearch query' do
+ ms_response = { 'hits' => [], 'totalHits' => 0, 'facetDistribution' => {} }
+ expect(mock_index).to receive(:search).with(anything, hash_including(
+ filter: include('cf_custom_weight >= 3.5')
+ )).and_return(ms_response)
+
+ provider.search_and_filter(scope: store.products, filters: { 'cf_custom_weight_gteq' => '3.5' })
+ end
+ end
+end
diff --git a/spree/providers/meilisearch/spec/presenters/spree_meilisearch/product_presenter_spec.rb b/spree/providers/meilisearch/spec/presenters/spree_meilisearch/product_presenter_spec.rb
new file mode 100644
index 0000000000..c867c4ae87
--- /dev/null
+++ b/spree/providers/meilisearch/spec/presenters/spree_meilisearch/product_presenter_spec.rb
@@ -0,0 +1,310 @@
+require 'spec_helper'
+
+RSpec.describe SpreeMeilisearch::ProductPresenter do
+ let(:store) { @default_store }
+ let(:product) { create(:product, name: 'Test Shirt') }
+ let(:presenter) { described_class.new(product, store) }
+
+ describe '#call' do
+ subject(:documents) { presenter.call }
+
+ it 'returns an array of documents' do
+ expect(documents).to be_an(Array)
+ expect(documents).not_to be_empty
+ end
+
+ context 'document structure' do
+ subject(:doc) { documents.first }
+
+ it 'includes composite id and product_id' do
+ expect(doc[:id]).to start_with(product.prefixed_id)
+ expect(doc[:product_id]).to eq(product.prefixed_id)
+ end
+
+ it 'includes locale and currency' do
+ expect(doc[:locale]).to be_present
+ expect(doc[:currency]).to be_present
+ end
+
+ it 'includes flat name and description' do
+ expect(doc[:name]).to eq('Test Shirt')
+ expect(doc[:slug]).to eq(product.slug)
+ end
+
+ it 'includes flat price' do
+ expect(doc).to have_key(:price)
+ end
+
+ it 'includes stock status' do
+ expect(doc).to have_key(:in_stock)
+ end
+
+ it 'includes timestamps' do
+ expect(doc[:created_at]).to be_present
+ expect(doc[:updated_at]).to be_present
+ end
+
+ it 'includes category data as prefixed IDs' do
+ expect(doc[:category_ids]).to be_an(Array)
+ end
+
+ it 'includes option data as prefixed IDs' do
+ expect(doc[:option_type_ids]).to be_an(Array)
+ expect(doc[:option_value_ids]).to be_an(Array)
+ end
+ end
+
+ context 'with categories' do
+ let(:root_category) { create(:category, store: store, name: 'Apparel') }
+ let(:category) { create(:category, store: store, parent: root_category) }
+ let(:product) { create(:product, name: 'Test Shirt', categories: [category]) }
+
+ it 'indexes category_ids as prefixed IDs including ancestors' do
+ doc = documents.first
+ expect(doc[:category_ids]).to include(category.prefixed_id)
+ expect(doc[:category_ids]).to include(root_category.prefixed_id)
+ doc[:category_ids].each { |id| expect(id).to start_with('ctg_') }
+ end
+ end
+
+ context 'with nested categories' do
+ let(:root_category) { create(:category, store: store, name: 'Apparel') }
+ let(:parent) { create(:category, store: store, parent: root_category, name: 'Men') }
+ let(:child) { create(:category, store: store, parent: parent, name: 'Jackets') }
+ let(:product) { create(:product, name: 'Test Jacket', channels: [store.default_channel], categories: [child]) }
+
+ it 'indexes all ancestor category IDs so parent-level filtering works' do
+ doc = documents.first
+ expect(doc[:category_ids]).to include(child.prefixed_id)
+ expect(doc[:category_ids]).to include(parent.prefixed_id)
+ expect(doc[:category_ids]).to include(root_category.prefixed_id)
+ end
+ end
+
+ context 'with collections' do
+ let(:collection) { create(:collection, store: store) }
+
+ before { create(:product_collection, collection: collection, product: product) }
+
+ it 'indexes collection_ids as flat prefixed IDs (no ancestors)' do
+ doc = documents.first
+ expect(doc[:collection_ids]).to eq([collection.prefixed_id])
+ expect(doc[:collection_ids].first).to start_with('coll_')
+ end
+ end
+
+ context 'membership documents (manual sort)' do
+ let(:collection) { create(:collection, store: store) }
+
+ before { create(:product_collection, collection: collection, product: product, position: 4) }
+
+ it 'emits a collection membership doc carrying position + full base payload' do
+ member = documents.find { |d| d[:grouping_id] == collection.prefixed_id }
+
+ expect(member).to be_present
+ expect(member[:position]).to eq(4)
+ expect(member[:name]).to eq('Test Shirt') # full base payload copied
+ expect(member[:product_id]).to eq(product.prefixed_id)
+ expect(member[:id]).to include(collection.prefixed_id)
+ end
+
+ it 'leaves base docs without a grouping_id/position' do
+ base = documents.reject { |d| d[:grouping_id] }
+
+ expect(base).not_to be_empty
+ base.each { |d| expect(d[:position]).to be_nil }
+ end
+ end
+
+ context 'category membership positions (subtree-MIN)' do
+ let(:parent) { create(:category, store: store, name: 'Men') }
+ let(:jackets) { create(:category, store: store, parent: parent, name: 'Jackets') }
+ let(:coats) { create(:category, store: store, parent: parent, name: 'Coats') }
+ let(:product) { create(:product, name: 'Test Jacket', channels: [store.default_channel], categories: [jackets, coats]) }
+
+ before do
+ Spree::ProductCategory.where(product: product, category: jackets).update_all(position: 5)
+ Spree::ProductCategory.where(product: product, category: coats).update_all(position: 2)
+ end
+
+ it 'emits a membership doc per ancestor-or-self, folding parent to the subtree minimum' do
+ jackets_doc = documents.find { |d| d[:grouping_id] == jackets.prefixed_id }
+ coats_doc = documents.find { |d| d[:grouping_id] == coats.prefixed_id }
+ parent_doc = documents.find { |d| d[:grouping_id] == parent.prefixed_id }
+
+ expect(jackets_doc[:position]).to eq(5)
+ expect(coats_doc[:position]).to eq(2)
+ expect(parent_doc[:position]).to eq(2) # MIN(5, 2) across the subtree
+ end
+ end
+
+ context 'with multiple markets' do
+ let!(:us_market) { store.default_market }
+ let!(:eu_market) { create(:market, store: store, name: 'EU', currency: 'EUR', default_locale: 'de', supported_locales: 'de,fr') }
+
+ # Product with prices in both currencies
+ let(:product) do
+ p = create(:product, name: 'Test Shirt')
+ create(:price, variant: p.default_variant, amount: 29.99, currency: 'EUR')
+ p
+ end
+
+ # Reload store to pick up new markets
+ let(:presenter) { described_class.new(product, store.reload) }
+
+ it 'creates one document per market × locale where product has a price' do
+ locales_currencies = documents.map { |d| [d[:locale], d[:currency]] }
+ expect(locales_currencies).to include(['en', 'USD'])
+ expect(locales_currencies).to include(['de', 'EUR'])
+ expect(locales_currencies).to include(['fr', 'EUR'])
+ expect(documents.size).to eq(3)
+ end
+
+ it 'each document has the correct currency and locale' do
+ usd_doc = documents.find { |d| d[:currency] == 'USD' }
+ eur_doc = documents.find { |d| d[:currency] == 'EUR' && d[:locale] == 'de' }
+
+ expect(usd_doc[:locale]).to eq('en')
+ expect(eur_doc[:locale]).to eq('de')
+ end
+
+ it 'each document has a unique composite id' do
+ ids = documents.map { |d| d[:id] }
+ expect(ids.uniq.size).to eq(ids.size)
+ end
+
+ it 'composite id includes product_id, locale, and currency' do
+ doc = documents.first
+ expect(doc[:id]).to match(/\A#{product.prefixed_id}_\w+_[A-Z]{3}\z/)
+ end
+
+ it 'includes the price for each currency' do
+ usd_doc = documents.find { |d| d[:currency] == 'USD' }
+ eur_doc = documents.find { |d| d[:currency] == 'EUR' }
+
+ expect(usd_doc[:price]).to be_present
+ expect(eur_doc[:price]).to eq(29.99)
+ end
+
+ it 'all documents share the same product_id' do
+ product_ids = documents.map { |d| d[:product_id] }.uniq
+ expect(product_ids).to eq([product.prefixed_id])
+ end
+ end
+
+ context 'with market but product has no price in that currency' do
+ let!(:us_market) { store.default_market }
+ let!(:eu_market) { create(:market, store: store, name: 'EU', currency: 'EUR', default_locale: 'de') }
+
+ # Product with USD price only — no EUR price
+ let(:product) { create(:product, name: 'USD Only Product') }
+ let(:presenter) { described_class.new(product, store.reload) }
+
+ it 'skips markets where product has no price' do
+ currencies = documents.map { |d| d[:currency] }
+ expect(currencies).to include('USD')
+ expect(currencies).not_to include('EUR')
+ end
+
+ it 'only creates documents for markets with matching prices' do
+ expect(documents.size).to eq(1)
+ expect(documents.first[:currency]).to eq('USD')
+ end
+ end
+
+ context 'translation fallback' do
+ let!(:us_market) { create(:market, store: store, name: 'US', currency: 'USD', default_locale: 'en') }
+ let!(:eu_market) { create(:market, store: store, name: 'EU', currency: 'EUR', default_locale: 'de') }
+
+ let(:product) do
+ p = create(:product, name: 'English Name')
+ create(:price, variant: p.default_variant, amount: 19.99, currency: 'EUR')
+ p
+ end
+
+ let(:presenter) { described_class.new(product, store.reload) }
+
+ it 'falls back to default locale name when translation is missing' do
+ de_doc = documents.find { |d| d[:locale] == 'de' }
+ expect(de_doc[:name]).to eq('English Name')
+ end
+ end
+
+ context 'with option values' do
+ let(:product) { create(:product_with_option_types) }
+
+ it 'includes option value prefixed IDs' do
+ doc = documents.first
+ doc[:option_value_ids].each do |ov_id|
+ expect(ov_id).to start_with('optval_')
+ end
+ end
+ end
+
+ context 'with searchable / sortable custom_fields' do
+ let!(:searchable_def) do
+ create(:custom_field_definition, :short_text_field, :searchable,
+ namespace: 'custom', key: 'pinyin_name', label: 'Pinyin')
+ end
+ let!(:sortable_def) do
+ create(:custom_field_definition, :number_field, :sortable,
+ namespace: 'custom', key: 'priority', label: 'Priority')
+ end
+ let!(:ignored_def) do
+ create(:custom_field_definition, :short_text_field,
+ namespace: 'custom', key: 'internal_note', label: 'Note')
+ end
+
+ before do
+ product.set_custom_field(searchable_def, 'mao-tai')
+ product.set_custom_field(sortable_def, '10')
+ product.set_custom_field(ignored_def, 'secret')
+ end
+
+ it 'indexes searchable and sortable custom_field values as cf_* attributes' do
+ doc = documents.first
+ expect(doc['cf_custom_pinyin_name']).to eq('mao-tai')
+ expect(doc['cf_custom_priority']).to eq(10.0)
+ expect(doc).not_to have_key('cf_custom_internal_note')
+ end
+
+ it 'uses the same cf_* attributes on every market/locale document' do
+ create(:market, store: store, name: 'US', currency: 'USD', default_locale: 'en')
+ create(:market, store: store, name: 'EU', currency: 'EUR', default_locale: 'de')
+ create(:price, variant: product.master, amount: 9.99, currency: 'EUR')
+
+ docs = described_class.new(product.reload, store.reload).call
+ expect(docs.size).to be > 1
+
+ cf_keys = docs.first.keys.grep(/\Acf_/)
+ docs.each do |doc|
+ expect(doc.slice(*cf_keys)).to eq(docs.first.slice(*cf_keys))
+ end
+ end
+
+ it 'casts number custom_field values to Float' do
+ decimal_def = create(:custom_field_definition, :number_field, :sortable,
+ namespace: 'custom', key: 'rating', label: 'Rating')
+ product.set_custom_field(decimal_def, '42.5')
+
+ doc = described_class.new(product.reload, store).call.first
+ expect(doc['cf_custom_rating']).to eq(42.5)
+ end
+
+ it 'omits registered keys when the product has no value' do
+ create(:custom_field_definition, :short_text_field, :searchable,
+ namespace: 'custom', key: 'origin', label: 'Origin')
+
+ doc = described_class.new(product.reload, store).call.first
+ expect(doc).not_to have_key('cf_custom_origin')
+ end
+
+ it 'includes no cf_* attributes when no definitions are searchable or sortable' do
+ Spree::CustomFieldDefinition.destroy_all
+
+ doc = described_class.new(product.reload, store).call.first
+ expect(doc.keys.grep(/\Acf_/)).to be_empty
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb b/spree/providers/meilisearch/spec/requests/spree_meilisearch/search_integration_spec.rb
similarity index 98%
rename from spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
rename to spree/providers/meilisearch/spec/requests/spree_meilisearch/search_integration_spec.rb
index 6dcd3a43d1..b3290833ab 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
+++ b/spree/providers/meilisearch/spec/requests/spree_meilisearch/search_integration_spec.rb
@@ -6,7 +6,7 @@ require 'meilisearch'
# In CI, Meilisearch runs as a service container.
# Locally: `brew install meilisearch && meilisearch`
#
-# Run with: bundle exec rspec spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
+# Run with: bundle exec rspec spec/requests/spree_meilisearch/search_integration_spec.rb
RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARCH_URL'].present? do
controller(Spree::Api::V3::Store::ProductsController) {}
@@ -15,7 +15,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
before(:all) { WebMock.allow_net_connect!(allow_localhost: true) }
after(:all) { WebMock.disable_net_connect! }
- let(:provider) { Spree::SearchProvider::Meilisearch.new(store) }
+ let(:provider) { SpreeMeilisearch::SearchProvider.new(store) }
let(:index_name) { "#{store.code}_products" }
# Categories
@@ -82,7 +82,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
before do
request.headers['X-Spree-Api-Key'] = api_key.token
- allow(Spree).to receive(:search_provider).and_return('Spree::SearchProvider::Meilisearch')
+ allow(Spree).to receive(:search_provider).and_return('SpreeMeilisearch::SearchProvider')
provider.reindex(store.products)
wait_for_meilisearch_indexing!
diff --git a/spree/providers/meilisearch/spec/spec_helper.rb b/spree/providers/meilisearch/spec/spec_helper.rb
new file mode 100644
index 0000000000..ad012293fc
--- /dev/null
+++ b/spree/providers/meilisearch/spec/spec_helper.rb
@@ -0,0 +1,85 @@
+if ENV['COVERAGE']
+ require 'simplecov'
+ require 'simplecov-cobertura'
+ SimpleCov.root(ENV.fetch('GITHUB_WORKSPACE', File.expand_path('../../..', __dir__)))
+ SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter
+ SimpleCov.start 'rails' do
+ add_group 'Models', 'app/models'
+ add_group 'Presenters', 'app/presenters'
+ add_filter '/spec/'
+
+ suffix = [ENV.fetch('CI_SHARD', '1'), ENV['TEST_ENV_NUMBER']].compact.reject(&:empty?).join('_')
+ coverage_dir "#{ENV['COVERAGE_DIR']}/meilisearch_#{suffix}" if ENV['COVERAGE_DIR']
+ command_name "meilisearch_shard_#{suffix}"
+ end
+end
+
+ENV['RAILS_ENV'] ||= 'test'
+
+# The dummy app requires only this gem, so pull in spree_api for the Store API
+# controller specs below.
+require 'spree_api'
+
+begin
+ require File.expand_path('../dummy/config/environment', __FILE__)
+rescue LoadError
+ puts 'Could not load dummy application. Please ensure you have run `bundle exec rake test_app`'
+end
+
+require 'rspec/rails'
+require 'database_cleaner/active_record'
+require 'ffaker'
+require 'webmock/rspec'
+
+Dir['./spec/support/**/*.rb'].sort.each { |f| require f }
+
+require 'spree/testing_support/factories'
+require 'spree/testing_support/jobs'
+require 'spree/testing_support/store'
+require 'spree/testing_support/preferences'
+require 'spree/testing_support/rspec_retry_config'
+
+# The Store API controller specs here exercise the provider through a real
+# request, so they need the API's shared contexts and factories.
+require 'spree/api/testing_support/v3/base'
+require 'spree/api/testing_support/factories'
+
+def json_response
+ case body = JSON.parse(response.body)
+ when Hash
+ body.with_indifferent_access
+ when Array
+ body
+ end
+end
+
+RSpec.configure do |config|
+ config.color = true
+ config.default_formatter = 'progress'
+ config.infer_spec_type_from_file_location!
+ config.mock_with :rspec
+ config.raise_errors_for_deprecations!
+ config.use_transactional_fixtures = true
+
+ config.include FactoryBot::Syntax::Methods
+ config.include Spree::TestingSupport::Preferences
+
+ config.before(:suite) do
+ Spree::Events.disable!
+ end
+
+ # Same as core's spec_helper: Spree::Current must not leak between examples.
+ #
+ # @default_store is one shared instance created outside the per-example
+ # transaction: an update! inside an example rolls back in the database but
+ # stays mutated in memory, and the next example's save re-persists the stale
+ # preferences. Reload drops the leak.
+ config.before do
+ Spree::Current.reset
+ I18n.locale = :en
+ @default_store.reload if defined?(@default_store) && @default_store&.persisted?
+ end
+
+ config.order = :random
+ Kernel.srand config.seed
+end
diff --git a/spree/providers/meilisearch/spree_meilisearch.gemspec b/spree/providers/meilisearch/spree_meilisearch.gemspec
new file mode 100644
index 0000000000..df39333850
--- /dev/null
+++ b/spree/providers/meilisearch/spree_meilisearch.gemspec
@@ -0,0 +1,30 @@
+# encoding: UTF-8
+
+require_relative '../../core/lib/spree/core/version.rb'
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'spree_meilisearch'
+ s.version = Spree.version
+ s.authors = ['Spark Solutions Sp. z o.o.', 'Vendo Connect Inc.']
+ s.email = '[email protected]'
+ s.summary = 'Meilisearch product search for Spree eCommerce platform'
+ s.description = 'Instant product search, filtering and faceted navigation for Spree via Meilisearch'
+ s.homepage = 'https://spreecommerce.org'
+ s.license = 'BSD-3-Clause'
+
+ s.metadata = {
+ "bug_tracker_uri" => "https://github.com/spree/spree/issues",
+ "changelog_uri" => "https://github.com/spree/spree/releases/tag/v#{s.version}",
+ "documentation_uri" => "https://docs.spreecommerce.org/",
+ "source_code_uri" => "https://github.com/spree/spree/tree/v#{s.version}",
+ }
+
+ s.required_ruby_version = '>= 3.2'
+
+ s.files = Dir["{app,config,db,lib,vendor}/**/*", "Rakefile", "README.md"].reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }
+ s.require_path = 'lib'
+
+ s.add_dependency 'meilisearch', '>= 0.28'
+ s.add_dependency 'spree_core', s.version
+end