faceted_search 3.6.4 → 4.0.0.beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 684d3943a7c0b0cf5e1c806098df9e6d54b4758f6cd7699b46ebbe22713568ea
4
- data.tar.gz: 0ce9164385fd5c3168a44ef94b54890cffe62407452dcc81d15484158a36af1a
3
+ metadata.gz: ecae24335def2fe0a7246f68975022ddbfaa54ec894a5a159f78150937ea49e7
4
+ data.tar.gz: '09650474feb511a86c4c95a1f51f853db85bda550a76d92102a76cc6e3ac8970'
5
5
  SHA512:
6
- metadata.gz: 71aecd633e58916554cbff73410564d19832c220e5ed3423b8e0055cf8e4e3cba8c6ef3284267b186e3de42f700ed7325e64c5157ec823de616b485d377d11ad
7
- data.tar.gz: 1cb07ff37da61c96df8c4959327ef49548506bdb3b4215691149f25ac10620edd8aeb8f5af98bf00a74bc2c4ffb25d4bab7386e986d0c8415050853d23d47a05
6
+ metadata.gz: 101d6c2253540fee9b420ea1923790dd2e377190a67a69c0f3532261145eae9dfa58b781a60645e82ce476720f4e65a6798000af5091578b1d17558db5335560
7
+ data.tar.gz: e585d9aa6de7ca3058174566754e5256140e38c01c8b81bf74c1b5934890199d02575c8a985cbf15417b3991d23fd6a171effca2be7ac800c561cb6b3970574d
data/CHANGELOG.md ADDED
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ ## 4.0.0
4
+
5
+ Facets are much cheaper for the database: no more `JOIN` + `DISTINCT`, only semi-joins (`WHERE id IN (subquery)`).
6
+
7
+ ### Breaking changes
8
+
9
+ See [UPGRADING.md](UPGRADING.md) for the migration from 3.x.
10
+
11
+ - `FacetedSearch::Facets#results` (and `results_except`) no longer add a `DISTINCT`.
12
+ The facets of the gem do not multiply rows anymore, but a custom facet whose `add_scope` adds a `JOIN` would now return duplicates.
13
+ Rewrite it with a semi-join (see the README), or get the previous behavior back with `FacetedSearch::Facets.distinct_results = true` (globally) or `MyModel::Facets.distinct_results = true` (for one facets class).
14
+ - habtm facets (`habtm: true`) filter with `WHERE items.id IN (SELECT items.id FROM items INNER JOIN ... WHERE kinds.id IN (...))` instead of joining the association on the results.
15
+ Code relying on the joined table being present in `results` (for instance ordering by a column of the association) must add its own join.
16
+ - The values of list facets (`list`, `checkboxes`, `full_tree`) are computed with a semi-join, without `DISTINCT`. Their order is now the order of the `source` (it was undefined before, because of the `DISTINCT`): add an `order` to the source if needed.
17
+ - Selected values are found with `find_by` instead of `id`. With a facet like `find_by: :title`, a selected value without results is now listed (and can be unselected); it disappeared before.
18
+
19
+ ### Improvements
20
+
21
+ - belongs_to facets compute their values without any join (`WHERE styles.id IN (SELECT items.style_id FROM items WHERE ...)`).
22
+ - Several habtm facets on the same association can be combined (AND between facets, OR between the values of a facet), without table aliases.
23
+ - The model given to the facets can be ordered: orderings are removed from the subqueries.
24
+ - `primitive_list` and `date` facets pluck distinct values of their column only.
25
+ - The values of list and tree facets are a loaded and memoized relation: `any?`, `each` and `length` in the partials do not run other queries (they ran one query each). `Tree#selected_object` is memoized too.
26
+ - README: all facets and options, custom facets, performance, robots (`noindex, follow`, `robots.txt`, throttling), upgrading, development.
27
+
28
+ ### Development
29
+
30
+ - The test suite runs with Rails 8.0 and Ruby 4.0, without warnings (Minitest < 6, `fixture_paths`, Bundler 4, `tsort`).
31
+ - The dummy app runs again in development (Sprockets and Dart Sass), with Rails 8.0 defaults.
32
+ - New tests: semi-joins, values of the facets, custom facets, options, paths, trees.
data/README.md CHANGED
@@ -20,15 +20,24 @@ Or install it yourself as:
20
20
  $ gem install faceted_search
21
21
  ```
22
22
 
23
+ Requirements:
24
+
25
+ - Rails 5.2 or newer (the test suite runs with Rails 8.0 and Ruby 4.0)
26
+ - PostgreSQL (text facets use `ILIKE`, date facets use `EXTRACT`)
27
+
23
28
  ## Getting started
24
29
 
25
- Add Bootstrap and Font Awesome to your `app/assets/stylesheets/application.sass`
30
+ The partials use [Bootstrap](https://getbootstrap.com) classes and [Font Awesome](https://fontawesome.com) icons.
31
+
32
+ With Sprockets and Sass (`sassc-rails` or `dartsass-sprockets`), add them to your `app/assets/stylesheets/application.sass`:
26
33
  ```
27
34
  @import 'bootstrap'
28
35
  @import 'font-awesome-sprockets'
29
36
  @import 'font-awesome'
30
37
  ```
31
38
 
39
+ With `cssbundling-rails` or `importmap-rails`, install them the usual way (`bootstrap` and `@fortawesome/fontawesome-free` packages, or their CDN): the gem only needs the CSS.
40
+
32
41
  Create a model defining your facets:
33
42
 
34
43
  class Item::Facets < FacetedSearch::Facets
@@ -46,29 +55,28 @@ Create a model defining your facets:
46
55
  filter_with_list :style, {
47
56
  habtm: false
48
57
  }
58
+ filter_with_boolean :active
59
+
60
+ # Categories, one level at a time
49
61
  filter_with_tree :categories, {
50
62
  habtm: true,
51
63
  children_scope: Proc.new { |children|
52
64
  children.order(:title)
53
65
  }
54
66
  }
55
- filter_with_boolean :active
56
- # Other tree option, shows all values
67
+ # Or the whole tree of categories:
68
+ # filter_with_full_tree :categories, {
69
+ # habtm: true
70
+ # }
71
+ # Or the whole tree, with searchable (SEO) category pages:
57
72
  # filter_with_full_tree :categories, {
58
73
  # habtm: true,
59
- # children_scope: Proc.new { |children|
60
- # children.order(:title)
74
+ # searchable: true,
75
+ # path_pattern: Proc.new { |category_id|
76
+ # Rails.application.routes.url_helpers.category_path(category_id)
61
77
  # }
62
78
  # }
63
-
64
- # Other option, with searchable (SEO) categories
65
- filter_with_full_tree :categories, {
66
- habtm: true,
67
- searchable: true,
68
- path_pattern: Proc.new { |category_id|
69
- Rails.application.routes.url_helpers.category_path(category_id)
70
- }
71
- }
79
+ # Use only one of them, or give them different param_name.
72
80
 
73
81
  # Filter with range input
74
82
  filter_with_range :distance, {
@@ -81,7 +89,7 @@ Create a model defining your facets:
81
89
  end
82
90
  end
83
91
 
84
- Warning: do not provide model with order, as it messes with the distinct used in the facet computations.
92
+ The model can be ordered: the ordering is removed from the subqueries used to compute the facets.
85
93
 
86
94
  In your controller, use it:
87
95
 
@@ -113,6 +121,130 @@ If you need, you can add an anchor to the links:
113
121
 
114
122
  <%= render 'faceted_search/facets', facets: @facets, anchor: "#identifier" %>
115
123
 
124
+ The parameters look like `?facets[kinds]=1,2&facets[style]=3`.
125
+ Inside a facet, the values are combined with an OR; between facets, with an AND.
126
+
127
+ ## Facets
128
+
129
+ | Method | Filters | Values listed |
130
+ |---|---|---|
131
+ | `filter_with_text` | `ILIKE '%term%'` on a column (with `unaccent` if the extension is enabled) | A search field |
132
+ | `filter_with_boolean` | `column = true` when checked | A checkbox |
133
+ | `filter_with_list` | An association (`belongs_to`, or `has_and_belongs_to_many` / `has_many :through` with `habtm: true`) | Values of the source having results, as links |
134
+ | `filter_with_checkboxes` | Same as `filter_with_list` | Same, as checkboxes |
135
+ | `filter_with_tree` | Same as `filter_with_list` | Root values, then the children of the selected value |
136
+ | `filter_with_full_tree` | Same as `filter_with_list` | The whole tree of values having results |
137
+ | `filter_with_primitive_list` | A column (`field IN (...)`) | Distinct values of the column in the results |
138
+ | `filter_with_date` | The year of a date column | Years present in the results |
139
+ | `filter_with_range` | `column = value` | A range input |
140
+
141
+ ### Options for all facets
142
+
143
+ | Option | Default | Description |
144
+ |---|---|---|
145
+ | `title` | Humanized name | Title displayed above the facet |
146
+ | `param_name` | The name | Name of the parameter, needed to filter twice on the same association |
147
+ | `ignore_scope` | `false` | The facet is displayed but does not filter the results |
148
+ | `hide_in_selected` | `false` | Do not show the selected values above the facets |
149
+ | `searchable` | `false` | Links without `rel="nofollow"` |
150
+ | `path_pattern` | | Proc building a path from a value, for SEO-friendly URLs |
151
+
152
+ ### Options for lists (`list`, `checkboxes`, `tree`, `full_tree`)
153
+
154
+ | Option | Default | Description |
155
+ |---|---|---|
156
+ | `source` | `Kind.all` for `:kinds` | Values that can be listed, with their order. With `habtm: true`, the source model needs an association named after the table of the model (`has_and_belongs_to_many :items` or `has_many :items, through: ...`) |
157
+ | `habtm` | `false` | `true` for a `has_and_belongs_to_many` or `has_many :through` association, `false` for a `belongs_to` |
158
+ | `find_by` | `:id` | Column used in the parameters (`find_by: :slug` gives `facets[kinds]=blue,red`) |
159
+ | `display_method` | `to_s` | Proc returning the label of a value |
160
+ | `children_scope` | | (tree only) Proc applied to the children of the selected value, for instance to order them |
161
+
162
+ The source of a tree needs a `root` scope (`scope :root, -> { where(parent: nil) }`) and a `children` association.
163
+
164
+ ### Options for other facets
165
+
166
+ | Facet | Option | Description |
167
+ |---|---|---|
168
+ | `primitive_list` | `field` (required) | Column to filter, like `'items.color'` |
169
+ | `primitive_list` | `source` | Relation used to list the values, instead of the results |
170
+ | `primitive_list`, `date` | `order` | `:asc` (default) or `:desc` |
171
+ | `date` | `source` | Array of years, instead of the years present in the results |
172
+ | `text` | `placeholder` | Placeholder of the search field |
173
+ | `range` | `min`, `max`, `step`, `default_value` | Range input settings (defaults: 0, 100, 1, `min`) |
174
+
175
+ ### Several facets on the same association
176
+
177
+ Use `param_name` to filter twice on the same association:
178
+
179
+ filter_with_list :tags, habtm: true, source: Tag.where(group: 'color'), param_name: :colors
180
+ filter_with_list :tags, habtm: true, source: Tag.where(group: 'size'), param_name: :sizes
181
+
182
+ `?facets[colors]=1,2&facets[sizes]=3` gives the items tagged (1 OR 2) AND 3.
183
+
184
+ ### Custom facets
185
+
186
+ Inherit from a facet class and override `add_scope` (and `values` if needed):
187
+
188
+ class Item::TagsFacet < FacetedSearch::Facets::List
189
+ def add_scope(scope)
190
+ return scope if params_array.blank?
191
+ ids = Item.unscoped.joins(:tags).where(tags: { id: params_array }).select(:id)
192
+ scope.where(id: ids)
193
+ end
194
+ end
195
+
196
+ class Item::Facets < FacetedSearch::Facets
197
+ def initialize(params)
198
+ super
199
+ @model = Item.all
200
+ add_facet Item::TagsFacet, :tags, { title: 'Tags' }
201
+ end
202
+ end
203
+
204
+ Partials are chosen with `kind`: override it to reuse the partials of another facet, or add your own partials in `app/views/faceted_search/facets/<kind>/_all.html.erb` and `_selected.html.erb`.
205
+
206
+ ## Performance: semi-joins, no DISTINCT
207
+
208
+ Since version 4, facets filter with semi-joins (`WHERE items.id IN (SELECT ...)`) instead of joins.
209
+ Rows are never multiplied, so the results do not need a `DISTINCT`, and `COUNT`, ordering and pagination stay cheap.
210
+ Several facets on the same association (or the same table) can be combined: an AND between facets, an OR between the values of one facet.
211
+
212
+ If you wrote a custom facet whose `add_scope` adds a `JOIN` that multiplies the rows, you will get duplicates.
213
+ The best fix is to use a semi-join in this facet, as in the custom facet above.
214
+ Otherwise, you can get the `DISTINCT` back, globally (in an initializer) or for one facets class:
215
+
216
+ FacetedSearch::Facets.distinct_results = true
217
+ Item::Facets.distinct_results = true
218
+
219
+ The values of a facet are loaded with one query and memoized: in your own partials, `facet.values.any?`, `each` and `length` do not run other queries.
220
+
221
+ ## Robots
222
+
223
+ Each combination of filters is a distinct URL, so robots can crawl an almost infinite number of pages, each running several queries.
224
+ Links are `rel="nofollow"` (unless the facet is `searchable`), but it is not enough:
225
+
226
+ - Add `noindex, follow` on filtered pages:
227
+
228
+ <% if @facets.has_params? %>
229
+ <meta name="robots" content="noindex, follow">
230
+ <% end %>
231
+
232
+ - Disallow the filtered URLs in `robots.txt`:
233
+
234
+ User-agent: *
235
+ Disallow: /*facets
236
+
237
+ - Throttle requests by IP, for instance with [Rack::Attack](https://github.com/rack/rack-attack):
238
+
239
+ Rack::Attack.throttle('facets/ip', limit: 30, period: 1.minute) do |request|
240
+ request.ip if request.query_string.include?('facets')
241
+ end
242
+
243
+ ## Upgrading to 4.0
244
+
245
+ If you only use the facets of the gem, the results do not change.
246
+ Custom facets doing a `JOIN`, and code adding conditions on an association to `results`, need a change.
247
+ See [UPGRADING.md](UPGRADING.md) for the step by step migration, and the [CHANGELOG](CHANGELOG.md) for details.
116
248
 
117
249
  ## Note about full tree
118
250
 
@@ -134,6 +266,66 @@ There is no inference whatsoever, so the data MUST be clean.
134
266
 
135
267
  The HTML code is ready for [Nestable2](https://github.com/RamonSmit/Nestable2) implementation. If you want to use this library, add the [CSS](https://github.com/RamonSmit/Nestable2/blob/master/dist/jquery.nestable.min.css) & [JS](https://github.com/RamonSmit/Nestable2/blob/master/dist/jquery.nestable.min.js) in your `vendor` folder and import them in `application.sass` & `application.js`.
136
268
 
269
+ ## Development
270
+
271
+ ### Requirements
272
+
273
+ - Ruby 3.2 or newer (the suite runs with Ruby 4.0) and Bundler 4
274
+ - PostgreSQL running locally, with a user allowed to create databases (the dummy app connects with the default socket, see `test/dummy/config/database.yml`)
275
+
276
+ Install the dependencies:
277
+
278
+ ```bash
279
+ bundle install
280
+ ```
281
+
282
+ ### Running the tests
283
+
284
+ Create the test database once (and again after a schema change):
285
+
286
+ ```bash
287
+ cd test/dummy && RAILS_ENV=test bundle exec bin/rails db:create db:schema:load && cd ../..
288
+ ```
289
+
290
+ Run all the tests:
291
+
292
+ ```bash
293
+ bin/test
294
+ ```
295
+
296
+ Run one file, or one test by its line:
297
+
298
+ ```bash
299
+ bin/test test/semi_joins_test.rb
300
+ ```
301
+
302
+ ```bash
303
+ bin/test test/semi_joins_test.rb:56
304
+ ```
305
+
306
+ `bundle exec rake test` works too.
307
+
308
+ The tests use the fixtures of `test/fixtures` and the models of the dummy app (`test/dummy/app/models`), with the facets defined in `test/dummy/app/models/item/facets.rb`:
309
+
310
+ - `test/faceted_search_test.rb`: results of the main combinations of filters
311
+ - `test/semi_joins_test.rb`: habtm facets combined, OR inside a facet, values of the facets, `COUNT` without `DISTINCT`, queries run by the partials
312
+ - `test/facets_behavior_test.rb`: `find_by`, custom sources and facets, options, paths, trees
313
+
314
+ ### Trying the dummy app
315
+
316
+ The dummy app shows the facets of `Item::Facets` on its home page, with Bootstrap. Create its development database with sample data once:
317
+
318
+ ```bash
319
+ cd test/dummy && bundle exec bin/rails db:create db:schema:load db:seed && cd ../..
320
+ ```
321
+
322
+ Start it:
323
+
324
+ ```bash
325
+ cd test/dummy && bundle exec bin/rails server
326
+ ```
327
+
328
+ Then open http://localhost:3000.
137
329
 
138
330
  ## License
139
331
  The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/UPGRADING.md ADDED
@@ -0,0 +1,144 @@
1
+ # Upgrading from 3.x to 4.0
2
+
3
+ Version 4.0 makes the facets much cheaper for PostgreSQL: they filter with semi-joins (`WHERE items.id IN (SELECT ...)`) instead of `JOIN` + `DISTINCT`.
4
+
5
+ **If you only use the facets of the gem** (`filter_with_list`, `filter_with_tree`…) without overriding them, the results do not change: update the gem, run your tests, done.
6
+ You can still read the "Clean up" section below to remove workarounds.
7
+
8
+ **If you wrote custom facets, or use `@facets.results` with conditions on an association**, read on.
9
+
10
+ ## 1. Update the gem
11
+
12
+ ```ruby
13
+ gem 'faceted_search', '~> 4.0'
14
+ ```
15
+
16
+ ```bash
17
+ bundle update faceted_search
18
+ ```
19
+
20
+ ## 2. Check your custom facets
21
+
22
+ `results` no longer adds a `DISTINCT`. A custom facet whose `add_scope` adds a `JOIN` on a `has_many` or habtm association now returns **duplicates** when an item matches several values.
23
+
24
+ Find them:
25
+
26
+ ```bash
27
+ grep -rn "def add_scope" app/
28
+ ```
29
+
30
+ Look for `joins`, `left_joins`, `includes(...).references` or `eager_load` in these methods.
31
+
32
+ Before (3.x):
33
+
34
+ ```ruby
35
+ class Item::TagsFacet < FacetedSearch::Facets::List
36
+ def add_scope(scope)
37
+ return scope if params_array.blank?
38
+ scope.joins(:tags).where(tags: { id: params_array })
39
+ end
40
+ end
41
+ ```
42
+
43
+ After (4.0), with a semi-join:
44
+
45
+ ```ruby
46
+ class Item::TagsFacet < FacetedSearch::Facets::List
47
+ def add_scope(scope)
48
+ return scope if params_array.blank?
49
+ ids = Item.unscoped.joins(:tags).where(tags: { id: params_array }).select(:id)
50
+ scope.where(id: ids)
51
+ end
52
+ end
53
+ ```
54
+
55
+ The semi-join never multiplies rows, and it lets you filter several times on the same association (one facet per group of tags, for instance) without table aliases.
56
+
57
+ If the facet is a standard habtm or `has_many :through` association, you may not need a custom facet anymore:
58
+
59
+ ```ruby
60
+ filter_with_list :tags, habtm: true, source: Tag.where(group: 'color'), param_name: :colors
61
+ filter_with_list :tags, habtm: true, source: Tag.where(group: 'size'), param_name: :sizes
62
+ ```
63
+
64
+ ### Not ready to rewrite them?
65
+
66
+ Get the `DISTINCT` back, globally in an initializer:
67
+
68
+ ```ruby
69
+ # config/initializers/faceted_search.rb
70
+ FacetedSearch::Facets.distinct_results = true
71
+ ```
72
+
73
+ or for one facets class only:
74
+
75
+ ```ruby
76
+ class Item::Facets < FacetedSearch::Facets
77
+ self.distinct_results = true
78
+ end
79
+ ```
80
+
81
+ You keep the 3.x behavior, but also its cost (`DISTINCT` on all the columns of the results, for every `COUNT` and every page).
82
+
83
+ ### Check for duplicates
84
+
85
+ In a test or a console, with filters matching several values:
86
+
87
+ ```ruby
88
+ facets = Item::Facets.new(tags: "#{tag_1.id},#{tag_2.id}")
89
+ facets.results.count == facets.results.distinct.count # must be true
90
+ ```
91
+
92
+ ## 3. Check your code using the results
93
+
94
+ habtm facets do not join their association on the results anymore. Code adding conditions or an order on the table of the association now fails with `missing FROM-clause entry for table "kinds"`:
95
+
96
+ ```ruby
97
+ # 3.x: worked because kinds was joined by the facet (only when the facet was selected)
98
+ @facets.results.where(kinds: { published: true })
99
+ ```
100
+
101
+ Add the join yourself, or better, a semi-join:
102
+
103
+ ```ruby
104
+ @facets.results.where(id: Item.joins(:kinds).where(kinds: { published: true }).select(:id))
105
+ ```
106
+
107
+ ## 4. Check the order of the values
108
+
109
+ The values of a list (`list`, `checkboxes`, `full_tree`) were in an undefined order, because of the `DISTINCT`. They are now in the order of the `source`.
110
+ If the order matters, give an ordered source:
111
+
112
+ ```ruby
113
+ filter_with_list :kinds, habtm: true, source: Kind.order(:title)
114
+ ```
115
+
116
+ ## 5. Facets with `find_by`
117
+
118
+ Selected values are now found with `find_by` (they were found with `id`).
119
+ With `find_by: :slug` or `find_by: :title`, a selected value without results used to disappear from the facet, so it could not be unselected. It is now listed.
120
+ Nothing to do, unless you relied on this behavior.
121
+
122
+ ## 6. Overridden methods
123
+
124
+ `FacetedSearch::Facets::DefaultList` has new protected methods: `results_for_values`, `values_with_results` and `ids_matching_params`.
125
+ If one of your facets defines a method with the same name, the gem will call yours: rename it, or check that it returns the same thing (see `app/models/faceted_search/facets/default_list.rb`).
126
+
127
+ `values` now returns a **loaded** relation for list and tree facets. You can still chain it (`facet.values.where(...)`), it runs a new query.
128
+
129
+ ## Clean up
130
+
131
+ These workarounds are not needed anymore:
132
+
133
+ - **`DISTINCT` removed by hand**: an override of `results_except` returning `super.distinct(false)` can go.
134
+ - **`values` rewritten with a semi-join**, to avoid `SELECT DISTINCT ... JOIN`: the gem does it now. For a `belongs_to` facet, it does not join anything (`WHERE styles.id IN (SELECT items.style_id ...)`).
135
+ - **habtm `add_scope` rewritten with a semi-join**, or with table aliases to filter twice on the same table: the gem does it now, use `param_name` to declare several facets on the same association.
136
+ - **Partials loading the values once** (`values = facet.values.to_a`): `facet.values` is loaded and memoized, `any?`, `each` and `length` do not run other queries.
137
+ - **An ordered model breaking the facets** (`@model = Item.order(:title)`): ordering is now removed from the subqueries.
138
+
139
+ Remove them one at a time, and compare the results and the values of the facets before and after on a few combinations of filters.
140
+
141
+ ## While you are at it: robots
142
+
143
+ Each combination of filters is a distinct URL. If robots crawl them, they run several queries per page.
144
+ Add `noindex, follow` on filtered pages, `Disallow: /*facets` in `robots.txt`, and throttle by IP: see the "Robots" section of the [README](README.md#robots).
@@ -7,7 +7,8 @@ module FacetedSearch
7
7
  @options[:source]
8
8
  else
9
9
  results = params_array.blank? ? facets.results : facets.results_except(param_name)
10
- results.send(:all).pluck(name).compact.map(&:year).uniq.sort
10
+ # DISTINCT on the plucked column only, years are sorted below
11
+ results.reorder(nil).distinct.pluck(name).compact.map(&:year).uniq.sort
11
12
  end
12
13
  end
13
14
  end
@@ -15,23 +15,26 @@ module FacetedSearch
15
15
 
16
16
  # Adds a scope corresponding to this facet
17
17
  # to the scope sent as an argument
18
- # and return the modified scope
18
+ # and return the modified scope.
19
+ # habtm facets use a semi-join (WHERE id IN (subquery)) instead of a JOIN:
20
+ # rows are not multiplied, so no DISTINCT is needed, and several facets
21
+ # on the same association can be combined without table aliases.
19
22
  def add_scope(scope)
20
23
  return scope if params_array.blank?
21
- habtm? ? scope.joins(name).where(name => { find_by => params_array })
24
+ habtm? ? scope.where(primary_key_of(scope) => ids_matching_params(scope))
22
25
  : scope.where(name => params_array)
23
26
  end
24
27
 
25
- # Show all values that have corresponding results with the current params.
26
- # This is a regular SQL inner join.
28
+ # Show all values that have corresponding results with the current params,
29
+ # and the selected values.
30
+ # This is a semi-join (WHERE id IN (subquery)), without DISTINCT.
31
+ # The relation is loaded once: any?, each and length do not run other queries.
27
32
  def values
28
33
  @values ||= begin
29
- joined_table = facets.model_table_name.to_sym
30
- results = params_array.blank? ? facets.results : facets.results_except(param_name)
31
- # Ordering can mess up the next query, so we remove it
32
- results = results.reorder(nil)
33
- values = source.all.joins(joined_table)
34
- values.where(joined_table => { id: results }).or(values.where(id: params_array)).distinct
34
+ values = source.all
35
+ with_results = values_with_results(values)
36
+ with_results = with_results.or(values.where(find_by => params_array)) if params_array.present?
37
+ with_results.load
35
38
  end
36
39
  end
37
40
 
@@ -56,5 +59,50 @@ module FacetedSearch
56
59
  def habtm?
57
60
  @options[:habtm]
58
61
  end
62
+
63
+ # Results to use for the values: the results without this facet
64
+ def results_for_values
65
+ params_array.blank? ? facets.results : facets.results_except(param_name)
66
+ end
67
+
68
+ # Ids of the model matching this facet's params
69
+ # SELECT items.id FROM items INNER JOIN items_kinds ... INNER JOIN kinds ... WHERE kinds.id IN (...)
70
+ def ids_matching_params(scope)
71
+ model = scope.all.klass
72
+ model.unscoped
73
+ .joins(name)
74
+ .where(name => { find_by => params_array })
75
+ .select(model.arel_table[model.primary_key])
76
+ end
77
+
78
+ # Values (from the source) having results, with a semi-join
79
+ def values_with_results(values)
80
+ results = results_for_values.all
81
+ model = results.klass
82
+ # Ordering and custom selects can mess up the subquery, so we remove them
83
+ results = results.unscope(:order, :select)
84
+ reflection = model.reflect_on_association(name)
85
+ if reflection&.belongs_to? && !reflection.polymorphic?
86
+ # WHERE styles.id IN (SELECT items.style_id FROM items WHERE ...)
87
+ # No join at all
88
+ values.where(reflection.association_primary_key => results.select(model.arel_table[reflection.foreign_key]))
89
+ else
90
+ # WHERE kinds.id IN (
91
+ # SELECT kinds.id FROM kinds INNER JOIN items_kinds ... INNER JOIN items ...
92
+ # WHERE items.id IN (SELECT items.id FROM items WHERE ...)
93
+ # )
94
+ source_model = values.klass
95
+ joined_table = facets.model_table_name.to_sym
96
+ ids = source_model.unscoped
97
+ .joins(joined_table)
98
+ .where(joined_table => { model.primary_key => results.select(model.arel_table[model.primary_key]) })
99
+ .select(source_model.arel_table[source_model.primary_key])
100
+ values.where(source_model.primary_key => ids)
101
+ end
102
+ end
103
+
104
+ def primary_key_of(scope)
105
+ scope.all.klass.primary_key
106
+ end
59
107
  end
60
108
  end
@@ -30,7 +30,9 @@ module FacetedSearch
30
30
 
31
31
  def values
32
32
  @values ||= begin
33
- values = (source.pluck(field).uniq.reject(&:blank?) | params_array.compact).sort
33
+ # DISTINCT on the plucked column only, values are sorted below
34
+ plucked = source.reorder(nil).distinct.pluck(field)
35
+ values = (plucked.reject(&:blank?) | params_array.compact).sort
34
36
  order == :asc ? values : values.reverse
35
37
  end
36
38
  end
@@ -10,14 +10,19 @@ module FacetedSearch
10
10
  end
11
11
 
12
12
  def selected_object
13
- source.find_by(find_by => params_array.last)
13
+ return @selected_object if defined?(@selected_object)
14
+ @selected_object = source.find_by(find_by => params_array.last)
14
15
  end
15
16
 
16
17
  # All values, not filtered
17
18
  # Otherwise, we would need to search all the children to do a good filtering
19
+ # Loaded once: any?, each and length do not run other queries
18
20
  def values
19
- root? ? values_root
20
- : values_children
21
+ @values ||= begin
22
+ values = root? ? values_root : values_children
23
+ # children_scope can return an Array
24
+ values.respond_to?(:load) ? values.load : values
25
+ end
21
26
  end
22
27
 
23
28
  protected
@@ -2,6 +2,14 @@ module FacetedSearch
2
2
  class Facets
3
3
  attr_reader :list, :params, :model
4
4
 
5
+ # Facets filter with semi-joins (WHERE id IN (subquery)), so results are not
6
+ # multiplied and do not need a DISTINCT.
7
+ # Set to true to get the DISTINCT back, for instance if a custom facet
8
+ # still adds a JOIN that multiplies the rows.
9
+ # Can be set globally (FacetedSearch::Facets.distinct_results = true)
10
+ # or for one facets class (Item::Facets.distinct_results = true).
11
+ class_attribute :distinct_results, instance_writer: false, default: false
12
+
5
13
  def initialize(params)
6
14
  if params.is_a? ActionController::Parameters
7
15
  @params = params.to_unsafe_hash
@@ -45,7 +53,8 @@ module FacetedSearch
45
53
  next if facet_param_names.include?(facet.param_name) || facet.ignore_scope?
46
54
  scope = facet.add_scope(scope)
47
55
  end
48
- scope.distinct
56
+ distinct_results ? scope.distinct
57
+ : scope.all
49
58
  end
50
59
 
51
60
  def model_table_name
@@ -1,3 +1,3 @@
1
1
  module FacetedSearch
2
- VERSION = '3.6.4'
2
+ VERSION = '4.0.0.beta1'
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: faceted_search
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.6.4
4
+ version: 4.0.0.beta1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Arnaud Levy
@@ -118,9 +118,11 @@ executables: []
118
118
  extensions: []
119
119
  extra_rdoc_files: []
120
120
  files:
121
+ - CHANGELOG.md
121
122
  - MIT-LICENSE
122
123
  - README.md
123
124
  - Rakefile
125
+ - UPGRADING.md
124
126
  - app/assets/stylesheets/faceted_search.sass
125
127
  - app/models/faceted_search/facets.rb
126
128
  - app/models/faceted_search/facets/boolean.rb
@@ -180,7 +182,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
180
182
  - !ruby/object:Gem::Version
181
183
  version: '0'
182
184
  requirements: []
183
- rubygems_version: 3.6.7
185
+ rubygems_version: 4.0.20
184
186
  specification_version: 4
185
187
  summary: Faceted search with Active Record
186
188
  test_files: []