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.

Fix: Disjunctive Option Value Faceting (#13843)

Damian Legawiec1e59160a965e
diff --git a/CLAUDE.md b/CLAUDE.md
index 2736c04ceb..c96e3f9d6c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -32,6 +32,8 @@ Current plans:
- `5.4-6.0-eu-legal-compliance.md` — GDPR (data export/anonymization, consent timestamps), Omnibus (PriceHistory, lowest-in-30-days), Consumer Rights (withdrawal period). Core primitives + enterprise hooks.
+- `5.4-disjunctive-option-faceting.md` — Per-option-type filter params with disjunctive facet counts (OR within option type, AND across)
+
Completed plans:
- `5.4-store-api-bridges.md` — Bridge 6.0 naming into 5.4 Store API (implemented, PR #13782)
- `spree-starter-and-create-spree-app.md` — Replace monorepo server/ with spree-starter template repo
diff --git a/docs/plans/5.4-disjunctive-option-faceting.md b/docs/plans/5.4-disjunctive-option-faceting.md
new file mode 100644
index 0000000000..744083d8d9
--- /dev/null
+++ b/docs/plans/5.4-disjunctive-option-faceting.md
@@ -0,0 +1,116 @@
+# Disjunctive Option Value Faceting
+
+**Status:** In Progress
+**Target:** Spree 5.4
+**Depends on:** `5.4-search-provider.md` (SearchProvider interface)
+**Author:** Damian
+**Last updated:** 2026-03-26
+
+## Summary
+
+PLP option filters use a flat `with_option_value_ids` array. Selecting "Blue" under Color shows Light Blue count as 1 instead of 18 because facet counts are computed against the already-filtered set. The fix: the backend groups selected values by option type (one query) and computes disjunctive counts per option type. No API, SDK, or storefront changes needed.
+
+## Key Decisions (do not deviate without discussion)
+
+- **No API change** — `with_option_value_ids` stays as a flat array. The backend groups values by option type server-side via a single `OptionValue.where(id:).group_by(&:option_type_id)` query.
+- **N+1 multi-search in Meilisearch** — 1 hit query + 1 facet query per active option type (excluding that type's values). Single HTTP call via `/multi-search`.
+- **Database FiltersAggregator** — receives grouped option values, computes counts per option type against a scope excluding that type's filter.
+
+## Design Details
+
+### Server-Side Grouping
+
+When `with_option_value_ids` arrives, the search provider groups values by option type:
+
+```ruby
+def group_option_values_by_type(prefixed_ids)
+ return {} if prefixed_ids.blank?
+
+ raw_ids = prefixed_ids.filter_map { |id| Spree::OptionValue.decode_prefixed_id(id) }
+ Spree::OptionValue.where(id: raw_ids).group_by(&:option_type_id)
+end
+```
+
+This produces `{ option_type_id_1 => [ov_a, ov_b], option_type_id_2 => [ov_c] }` — enough to build per-type filter conditions and disjunctive facet queries.
+
+### Meilisearch Provider
+
+```ruby
+def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
+ option_value_ids = extract_option_value_ids(filters)
+ grouped = group_option_values_by_type(option_value_ids)
+
+ # Main query: all filters (OR within type, AND across types)
+ all_conditions = build_filters(filters) + build_grouped_option_conditions(grouped)
+
+ queries = [{ indexUid: index_name, q: query.to_s, filter: all_conditions, facets: facet_attributes, ... }]
+
+ # Disjunctive facet query per active option type
+ grouped.each_key do |option_type_id|
+ without_this_type = build_grouped_option_conditions(grouped.except(option_type_id))
+ queries << { indexUid: index_name, q: query.to_s, filter: build_filters(filters) + without_this_type, facets: ['option_value_ids'], limit: 0 }
+ end
+
+ results = client.multi_search(queries)
+ # Merge: option_value_ids facet distribution from disjunctive queries
+end
+```
+
+### Database Provider + FiltersAggregator
+
+The Database provider extracts `with_option_value_ids` before Ransack and applies per-type scoping:
+
+```ruby
+def apply_option_filters(scope, filters)
+ ids = filters.delete('with_option_value_ids') || filters.delete(:with_option_value_ids)
+ return [scope, {}] if ids.blank?
+
+ grouped = group_option_values_by_type(Array(ids))
+ grouped.each_value do |ovs|
+ scope = scope.with_option_value_ids(ovs.map(&:id))
+ end
+
+ [scope, grouped]
+end
+```
+
+FiltersAggregator receives the grouped hash and computes disjunctive counts:
+
+```ruby
+def option_value_data(option_type, option_value)
+ # Use scope excluding THIS option type's selected values
+ scope = disjunctive_scope_for(option_type)
+ scope.joins(:option_value_variants)
+ .where(option_value_variants: { option_value_id: option_value.id })
+ .distinct.count
+end
+```
+
+### What Stays The Same
+
+- API params: `q[with_option_value_ids][]=optval_blue&q[with_option_value_ids][]=optval_small`
+- SDK `ProductListParams.with_option_value_ids`
+- Storefront `ActiveFilters.optionValues: string[]`
+- Filter response shape
+
+## Migration Path
+
+1. Meilisearch provider: intercept `with_option_value_ids`, group by type, N+1 multi-search
+2. Database provider: intercept `with_option_value_ids`, group by type, pass to FiltersAggregator
+3. FiltersAggregator: accept grouped option values, compute disjunctive counts per type
+4. Done — no SDK/storefront/API changes
+
+## Constraints on Current Work
+
+- `with_option_value_ids` Ransack scope must keep working for direct Ransack usage
+- Meilisearch multi-search fallback: if only 1 option type is active, skip multi-search (single query suffices for facet counts of other option types)
+
+## Open Questions
+
+None.
+
+## References
+
+- [Algolia disjunctive faceting](https://www.algolia.com/doc/guides/managing-results/refine-results/faceting) — N+1 multi-search pattern
+- [Meilisearch multi-search](https://www.meilisearch.com/docs/reference/api/multi_search) — batch query endpoint
+- `5.4-search-provider.md` — SearchProvider interface
diff --git a/spree/api/app/services/spree/api/v3/filters_aggregator.rb b/spree/api/app/services/spree/api/v3/filters_aggregator.rb
index 94d426e719..bc7e898a5f 100644
--- a/spree/api/app/services/spree/api/v3/filters_aggregator.rb
+++ b/spree/api/app/services/spree/api/v3/filters_aggregator.rb
@@ -2,13 +2,17 @@ module Spree
module Api
module V3
class FiltersAggregator
- # @param scope [ActiveRecord::Relation] Base product scope (already filtered by store, availability, category, etc.)
+ # @param scope [ActiveRecord::Relation] Base product scope (fully filtered, including option values)
# @param currency [String] Currency for price range
# @param category [Spree::Category, nil] Optional category for default_sort and category filtering context
- def initialize(scope:, currency:, category: nil)
+ # @param option_value_ids [Array<String>] Currently selected option value prefixed IDs (for disjunctive facet counts)
+ # @param scope_before_options [ActiveRecord::Relation] Scope before option value filters (for disjunctive counts)
+ def initialize(scope:, currency:, category: nil, option_value_ids: [], scope_before_options: nil)
@scope = scope
@currency = currency
@category = category
+ @option_value_ids = option_value_ids
+ @scope_before_options = scope_before_options || scope
end
def call
@@ -78,25 +82,26 @@ module Spree
def option_type_filters
Spree::OptionType.filterable.includes(:option_values).order(:position).filter_map do |option_type|
- values = option_type.option_values.for_products(@scope).distinct.order(:position)
+ # Disjunctive: count against scope WITHOUT this option type's filter
+ count_scope = disjunctive_scope_for(option_type)
+ values = option_type.option_values.for_products(count_scope).distinct.order(:position)
next if values.empty?
+ count_ids = count_scope.reorder('').distinct.pluck(:id)
+
{
id: option_type.prefixed_id,
type: 'option',
name: option_type.name,
label: option_type.label,
- options: values.map { |ov| option_value_data(option_type, ov) }
+ options: values.map { |ov| option_value_data(count_ids, ov) }
}
end
end
- def option_value_data(option_type, option_value)
- # Count products in scope that have this option value
- # We use a subquery approach to avoid GROUP BY conflicts when scope includes joins (like in_category)
- # Join directly to option_value_variants for efficiency (skips joining through option_values table)
+ def option_value_data(product_ids, option_value)
count = Spree::Product
- .where(id: base_scope_product_ids)
+ .where(id: product_ids)
.joins(:option_value_variants)
.where(Spree::OptionValueVariant.table_name => { option_value_id: option_value.id })
.distinct
@@ -111,8 +116,38 @@ module Spree
}
end
- def base_scope_product_ids
- @base_scope_product_ids ||= @scope.reorder('').distinct.pluck(:id)
+ # Returns the scope with all option type filters EXCEPT the given one applied.
+ # This gives disjunctive counts: selecting Blue still shows Red's true count.
+ def disjunctive_scope_for(option_type)
+ return @scope_before_options if grouped_selected_options.empty?
+
+ other_groups = grouped_selected_options.except(option_type.id)
+
+ # If this type has selections but no other types do, use scope before any option filters
+ return @scope_before_options if other_groups.empty?
+
+ # Rebuild: start from scope before options, apply only other option types
+ scope = @scope_before_options
+ other_groups.each_value do |ov_ids|
+ matching = Spree::Variant.where(deleted_at: nil)
+ .joins(:option_value_variants)
+ .where(Spree::OptionValueVariant.table_name => { option_value_id: ov_ids })
+ .select(:product_id)
+ scope = scope.where(id: matching)
+ end
+ scope
+ end
+
+ # Group selected option value IDs by option type (cached, single query)
+ def grouped_selected_options
+ @grouped_selected_options ||= begin
+ return {} if @option_value_ids.blank?
+
+ decoded = @option_value_ids.filter_map { |id| Spree::OptionValue.decode_prefixed_id(id) }
+ return {} if decoded.empty?
+
+ Spree::OptionValue.where(id: decoded).group_by(&:option_type_id).transform_values { |ovs| ovs.map(&:id) }
+ end
end
def category_filter
diff --git a/spree/api/spec/services/spree/api/v3/filters_aggregator_spec.rb b/spree/api/spec/services/spree/api/v3/filters_aggregator_spec.rb
index acb8228c54..edfb2f3501 100644
--- a/spree/api/spec/services/spree/api/v3/filters_aggregator_spec.rb
+++ b/spree/api/spec/services/spree/api/v3/filters_aggregator_spec.rb
@@ -115,6 +115,64 @@ RSpec.describe Spree::Api::V3::FiltersAggregator do
end
end
+ describe 'disjunctive option facet counts' do
+ let(:color_type) { create(:option_type, name: 'color', presentation: 'Color', filterable: true) }
+ let(:blue) { create(:option_value, option_type: color_type, name: 'blue', presentation: 'Blue') }
+ let(:red) { create(:option_value, option_type: color_type, name: 'red', presentation: 'Red') }
+
+ let!(:blue_product) do
+ create(:product, stores: [store], status: 'active', taxons: [child_taxon]).tap do |p|
+ p.option_types << color_type << option_type
+ create(:variant, product: p, option_values: [blue, option_value_s])
+ end
+ end
+
+ let!(:red_product) do
+ create(:product, stores: [store], status: 'active', taxons: [child_taxon]).tap do |p|
+ p.option_types << color_type << option_type
+ create(:variant, product: p, option_values: [red, option_value_m])
+ end
+ end
+
+ it 'shows disjunctive counts within the same option type (Color)' do
+ # Filter by Blue — Red's count should reflect products with Red (not Blue AND Red)
+ filtered_scope = scope.with_option_value_ids([blue.prefixed_id])
+ aggregator = described_class.new(
+ scope: filtered_scope,
+ currency: currency,
+ category: nil,
+ option_value_ids: [blue.prefixed_id],
+ scope_before_options: scope
+ )
+ result = aggregator.call
+ color_filter = result[:filters].find { |f| f[:name] == 'color' }
+ red_option = color_filter[:options].find { |o| o[:name] == 'red' }
+
+ # Red count should be 1 (the red_product), not 0
+ expect(red_option[:count]).to eq(1)
+ end
+
+ it 'shows conjunctive counts across different option types (Size counts filtered by Color)' do
+ # Filter by Blue — Size counts should only reflect Blue products
+ filtered_scope = scope.with_option_value_ids([blue.prefixed_id])
+ aggregator = described_class.new(
+ scope: filtered_scope,
+ currency: currency,
+ category: nil,
+ option_value_ids: [blue.prefixed_id],
+ scope_before_options: scope
+ )
+ result = aggregator.call
+ size_filter = result[:filters].find { |f| f[:name] == 'size' }
+ s_option = size_filter[:options].find { |o| o[:name] == 'small' }
+ m_option = size_filter[:options].find { |o| o[:name] == 'medium' }
+
+ # S count = 1 (blue_product has Blue+S), M count should be 0 (only red_product has M)
+ expect(s_option[:count]).to eq(1)
+ expect(m_option).to be_nil # M is not in scope (no Blue+M product)
+ end
+ end
+
describe 'category filter' do
it 'includes child categories when category is provided' do
category_filter = result[:filters].find { |f| f[:type] == 'category' }
diff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rb
index 42935cb09d..b0e930aff7 100644
--- a/spree/core/app/models/concerns/spree/product_scopes.rb
+++ b/spree/core/app/models/concerns/spree/product_scopes.rb
@@ -224,21 +224,31 @@ module Spree
where(Spree::OptionValue.table_name => { name: value, option_type_id: option_type_id })
}
- # Filters products by option value IDs (prefix IDs like 'optval_xxx')
- # Accepts an array of option value IDs
- scope :with_option_value_ids, ->(*ids) {
+ # Filters products by option value IDs (prefix IDs like 'optval_xxx').
+ # Groups values by option type automatically:
+ # - Within the same option type: OR (Blue OR Red)
+ # - Across different option types: AND ((Blue OR Red) AND (S OR M))
+ def self.with_option_value_ids(*ids)
ids = ids.flatten.compact
- next none if ids.empty?
-
- # Handle prefixed IDs (optval_xxx) by decoding to actual IDs
- actual_ids = ids.map do |id|
- id.to_s.include?('_') ? OptionValue.decode_prefixed_id(id) : id
- end.compact
-
- next none if actual_ids.empty?
-
- joins(variants: :option_values).where(Spree::OptionValue.table_name => { id: actual_ids })
- }
+ return none if ids.empty?
+
+ actual_ids = ids.map { |id| id.to_s.include?('_') ? OptionValue.decode_prefixed_id(id) : id }.compact
+ return none if actual_ids.empty?
+
+ grouped = OptionValue.where(id: actual_ids).group_by(&:option_type_id)
+ return none if grouped.empty?
+
+ scope = all
+ grouped.each_value do |option_values|
+ ov_ids = option_values.map(&:id)
+ matching_product_ids = Variant.where(deleted_at: nil)
+ .joins(:option_value_variants)
+ .where(OptionValueVariant.table_name => { option_value_id: ov_ids })
+ .select(:product_id)
+ scope = scope.where(id: matching_product_ids)
+ end
+ scope
+ end
# Deprecated — remove in 6.0. Not used internally.
def self.with(value)
diff --git a/spree/core/app/models/spree/search_provider/database.rb b/spree/core/app/models/spree/search_provider/database.rb
index 14101c7b64..dd0e78f323 100644
--- a/spree/core/app/models/spree/search_provider/database.rb
+++ b/spree/core/app/models/spree/search_provider/database.rb
@@ -14,6 +14,9 @@ module Spree
# 2. Extract internal params before passing to Ransack
category = filters.is_a?(Hash) ? filters.delete('_category') || filters.delete(:_category) : nil
+ # 2b. Extract option value IDs — handled by scope (OR within type, AND across)
+ option_value_ids = filters.is_a?(Hash) ? filters.delete('with_option_value_ids') || filters.delete(:with_option_value_ids) : nil
+
# 3. Structured filtering via Ransack
ransack_filters = sanitize_filters(filters)
if ransack_filters.present?
@@ -21,8 +24,14 @@ module Spree
scope = search.result(distinct: true)
end
+ # Save scope before option filters for disjunctive facet counts
+ scope_before_options = scope
+ if option_value_ids.present?
+ scope = scope.with_option_value_ids(Array(option_value_ids))
+ end
+
# 4. Facets (before sorting to avoid computed column conflicts with count)
- filter_facets = build_facets(scope, category: category)
+ filter_facets = build_facets(scope, category: category, option_value_ids: Array(option_value_ids), scope_before_options: scope_before_options)
# 5. Total count (before sorting to avoid computed column conflicts with count)
total = scope.distinct.count
@@ -49,13 +58,15 @@ module Spree
Pagy::Offset.new(count: count, page: page, limit: limit)
end
- def build_facets(scope, category: nil)
+ def build_facets(scope, category: nil, option_value_ids: [], scope_before_options: nil)
return { filters: [], sort_options: available_sort_options, default_sort: 'manual' } unless defined?(Spree::Api::V3::FiltersAggregator)
Spree::Api::V3::FiltersAggregator.new(
scope: scope,
currency: currency,
- category: category
+ category: category,
+ option_value_ids: option_value_ids,
+ scope_before_options: scope_before_options || scope
).call
end
diff --git a/spree/core/app/models/spree/search_provider/meilisearch.rb b/spree/core/app/models/spree/search_provider/meilisearch.rb
index 8e691acb7f..c4cd370bf5 100644
--- a/spree/core/app/models/spree/search_provider/meilisearch.rb
+++ b/spree/core/app/models/spree/search_provider/meilisearch.rb
@@ -20,9 +20,19 @@ module Spree
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 = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
+ filters = (filters || {}).stringify_keys
+
+ # Extract and group option values by option type for proper OR/AND semantics
+ 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
search_params = {
- filter: build_filters(filters),
+ filter: all_conditions,
facets: facet_attributes,
sort: build_sort(sort),
offset: (page - 1) * limit,
@@ -32,7 +42,55 @@ module Spree
Rails.logger.debug { "[Meilisearch] index=#{index_name} query=#{query.inspect} #{search_params.compact.inspect}" }
begin
- ms_result = client.index(index_name).search(query.to_s, search_params)
+ if grouped_options.any?
+ # N+1 multi-search: 1 hit query + 1 disjunctive facet query per active option type
+ 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'], limit: 0 }
+ end
+
+ results = client.multi_search(queries)
+ ms_result = results['results'][0]
+
+ # Merge disjunctive counts per option type.
+ # Each disjunctive query excluded one option type's filter.
+ # Use that query's full option_value_ids distribution for that option type's values,
+ # and the main query's distribution for everything else.
+ main_ov_dist = ms_result.dig('facetDistribution', 'option_value_ids') || {}
+
+ # Build a set of prefixed IDs per option type (including unselected values)
+ # by looking up which option type each option value belongs to.
+ all_ov_prefixed_ids = Set.new
+ disjunctive_dists = {}
+ results['results'][1..].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
+
+ # Resolve which prefixed IDs belong to which option type
+ 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
+
+ # Start with main query's distribution, overlay disjunctive counts for active option types
+ 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
+
+ facet_distribution = (ms_result['facetDistribution'] || {}).merge('option_value_ids' => merged_ov_dist)
+ else
+ ms_result = client.index(index_name).search(query.to_s, search_params)
+ facet_distribution = ms_result['facetDistribution'] || {}
+ end
rescue ::Meilisearch::ApiError => e
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 })
@@ -46,20 +104,17 @@ module Spree
raw_ids = product_prefixed_ids.filter_map { |pid| Spree::Product.decode_prefixed_id(pid) }
# Intersect with AR scope for security/visibility.
- # Since we filter by store/status/currency/discontinue_on in Meilisearch,
- # the AR scope is a safety net — it should not filter anything out.
products = if raw_ids.any?
scope.where(id: raw_ids).reorder(nil)
else
scope.none
end
- # Build Pagy object from Meilisearch response (passive mode)
pagy = build_pagy(ms_result, page, limit)
SearchResult.new(
products: products,
- filters: build_facet_response(ms_result['facetDistribution'] || {}),
+ filters: build_facet_response(facet_distribution),
sort_options: available_sort_options.map { |id| { id: id } },
default_sort: 'manual',
total_count: ms_result['estimatedTotalHits'] || 0,
@@ -204,8 +259,36 @@ module Spree
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 'with_option_value_ids'
- Array(value).filter_map { |ov| "option_value_ids = '#{sanitize_prefixed_id(ov)}'" if valid_prefixed_id?(ov) }
+ # Handled by grouped option conditions in search_and_filter — skip here
+ nil
+ end
+ 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.
diff --git a/spree/core/spec/models/spree/search_provider/database_spec.rb b/spree/core/spec/models/spree/search_provider/database_spec.rb
index aa247138d8..cd42e01ff0 100644
--- a/spree/core/spec/models/spree/search_provider/database_spec.rb
+++ b/spree/core/spec/models/spree/search_provider/database_spec.rb
@@ -164,6 +164,38 @@ module Spree
expect(result.products).not_to include(product_3)
end
end
+
+ context 'with_option_value_ids disjunctive filtering' do
+ let(:color) { create(:option_type, name: 'color', presentation: 'Color', filterable: true) }
+ let(:size) { create(:option_type, name: 'size', presentation: 'Size', filterable: true) }
+ let(:blue) { create(:option_value, option_type: color, name: 'blue', presentation: 'Blue') }
+ let(:red) { create(:option_value, option_type: color, name: 'red', presentation: 'Red') }
+ let(:small) { create(:option_value, option_type: size, name: 's', presentation: 'S') }
+ let(:large) { create(:option_value, option_type: size, name: 'l', presentation: 'L') }
+
+ before do
+ create(:variant, product: product_1, option_values: [blue, small]) # product_1: Blue + S
+ create(:variant, product: product_2, option_values: [red, small]) # product_2: Red + S
+ create(:variant, product: product_3, option_values: [blue, large]) # product_3: Blue + L
+ end
+
+ it 'ORs within same option type: Blue OR Red returns all 3 products' do
+ result = provider.search_and_filter(scope: scope, filters: { 'with_option_value_ids' => [blue.prefixed_id, red.prefixed_id] })
+ expect(result.products).to include(product_1, product_2, product_3)
+ end
+
+ it 'ANDs across option types: Blue AND S returns only products with both' do
+ result = provider.search_and_filter(scope: scope, filters: { 'with_option_value_ids' => [blue.prefixed_id, small.prefixed_id] })
+ expect(result.products).to include(product_1)
+ expect(result.products).not_to include(product_2, product_3)
+ end
+
+ it 'ANDs across option types: (Blue OR Red) AND S' do
+ result = provider.search_and_filter(scope: scope, filters: { 'with_option_value_ids' => [blue.prefixed_id, red.prefixed_id, small.prefixed_id] })
+ expect(result.products).to include(product_1, product_2)
+ expect(result.products).not_to include(product_3)
+ end
+ end
end
describe '#index' do