简体   繁体   中英

How to sum boost points of elasticsearch results and sort them?

I have User model.

class User < ActiveRecord::Base
  attr_accessible :last_visited_at, :friend_id, :blacklisted
  has_many :friends
end

And conditions:

  1. If phrase exist in description, give this user a score of 10.
  2. If last visited was less than 3 days ago, give this user a score of 5.
  3. If has any friends, give this user a score of 8.
  4. If blacklisted, show this user on the end of the result list, not depending on the score.

How to implement this using Elasticsearch? How to count points of user and sort search results?

Right now I have

def self.search(params)
  tire.search(load: true) do
    query do
      custom_filters_score do
        query { all }

        filter do
          filter :range, last_contact_at: { gte: 3.days.ago }
          boost 1
        end

        score_mode :total
      end
    end
  end
end

EDIT:

In point 4 I want to reset score to 0 if User on blacklist.

Have a look at the custom_filters_score query, which has exactly this purpose: to influence _score by how many filters match a document. Tire integration: https://github.com/karmi/tire/blob/master/test/integration/custom_filters_score_queries_test.rb

(You can, of course compute the score manually with a script for a custom_score query https://github.com/karmi/tire/blob/master/test/integration/custom_score_queries_test.rb , but that won't be as effective and could be less expressive/maintainable.)

Here is how I would look at this case -

Points 3 and 4 seem to be very domain specific (ie ES makes minimum influence). Ie at index time, your entity should be able to determine and have these attributes captured (basically compute this score at index time).

As for point 2 - consider something like this answer that allows query which boost latest documents (this is query time logic, hence the date is to be inferred at the time of querying the logic)

If the above address the points 2-4, implementing (1) should be easy enough, you could choose Standard or Whitespace analyzer and use n-gram tokenizer, if you need partial match of words.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM