Skip to content

Commit

Permalink
Add a weight scoring function to the search (toptal#380)
Browse files Browse the repository at this point in the history
  • Loading branch information
sevab authored and levent committed Nov 1, 2016
1 parent cccc540 commit ef2a244
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
22 changes: 22 additions & 0 deletions lib/chewy/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,28 @@ def boost_factor(factor, options = {})
chain { criteria.update_scores scoring }
end

# Add a weight scoring function to the search. All scores are
# added to the search request and combinded according to
# <tt>boost_mode</tt> and <tt>score_mode</tt>
#
# This probably only makes sense if you specify a filter
# for the weight as well.
#
# UsersIndex.weight(23, filter: { term: { foo: :bar} })
# # => {body:
# query: {
# function_score: {
# query: { ...},
# functions: [{
# weight: 23,
# filter: { term: { foo: :bar } }
# }]
# } } }
def weight(factor, options = {})
scoring = options.merge(weight: factor.to_i)
chain { criteria.update_scores scoring }
end

# Adds a random score to the search request. All scores are
# added to the search request and combinded according to
# <tt>boost_mode</tt> and <tt>score_mode</tt>
Expand Down
2 changes: 1 addition & 1 deletion lib/chewy/search.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module Search
included do
singleton_class.delegate :explain, :query_mode, :filter_mode, :post_filter_mode,
:timeout, :limit, :offset, :highlight, :min_score, :rescore, :facets, :script_score,
:boost_factor, :random_score, :field_value_factor, :decay, :aggregations,
:boost_factor, :weight, :random_score, :field_value_factor, :decay, :aggregations,
:suggest, :none, :strategy, :query, :filter, :post_filter, :boost_mode,
:score_mode, :order, :reorder, :only, :types, :delete_all, :find, :total,
:total_count, :total_entries, to: :all
Expand Down
8 changes: 8 additions & 0 deletions spec/chewy/query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,14 @@
specify { expect(subject.boost_factor('23', filter: { foo: :bar}).criteria.scores).to eq([{ boost_factor: 23, filter: { foo: :bar } }]) }
end

describe '#weight' do
specify { expect(subject.weight('23')).to be_a described_class }
specify { expect(subject.weight('23')).not_to eq(subject) }
specify { expect(subject.weight('23').criteria.scores).to eq([ { weight: 23 } ]) }
specify { expect { subject.weight('23') }.not_to change { subject.criteria.scores } }
specify { expect(subject.weight('23', filter: { foo: :bar}).criteria.scores).to eq([{ weight: 23, filter: { foo: :bar } }]) }
end

describe '#random_score' do
specify { expect(subject.random_score('23')).to be_a described_class }
specify { expect(subject.random_score('23')).not_to eq(subject) }
Expand Down

0 comments on commit ef2a244

Please sign in to comment.