简体   繁体   中英

Rails ElasticSearch Tire - filter nested field on multiple parameters the same time

I have a Movie model and a search page that has a movie genres facet. It's possible to select a checkbox near every facet on the search page. I pass the list of checked facet terms to a controller and I want to filter movies collection to include only those movies that have genres selected with checkboxes.

My model with indexes and search definition is:

class Movie < ActiveRecord::Base
  include Tire::Model::Search
  include Tire::Model::Callbacks

  mapping do
    indexes :id,           :index    => :not_analyzed
    indexes :title,        :analyzer => 'snowball', :boost => 100
    indexes :description,  :analyzer => 'snowball'
    indexes :genres do
      indexes :title, analyzer: 'keyword'
    end
  end

  def to_indexed_json
    to_json( include: { genres: { only: [:title, :id] } } )
  end

  def self.search(params={})
    tire.search(page: params[:page], per_page: 5, load: false) do
      query do
        all
        #boolean do
        #  must { string params[:query], :default_field => 'title' }
        #end
      end


      #filter 'genres.title', :values => params[:genres] if params[:genres].present?
      filter :terms, 'genres.title' => ['Genre 1', 'Genre 2', 'Genre 3']


      facet 'global-genres', global: true do
        terms 'genres.title', size: 15
      end
      facet 'scoped-genres' do
        terms 'genres.title', size: 15
      end
    end
  end

  attr_accessible :description, :title, :year, :genres

  has_and_belongs_to_many :genres, :uniq => true

end

I'm not sure how this part should be rewritten:

#filter 'genres.title', :values => params[:genres] if params[:genres].present?
filter :terms, 'genres.title' => ['Genre 1', 'Genre 2', 'Genre 3']
#filter 'genres.id', :values => [1, 2, 3]

Later, I'm going to pass the list of genres or genre IDs as parameters, and I need to filter on them.

filter :terms, 'genres.title' => ['Genre 1', 'Genre 2', 'Genre 3']

It filters to movies that have 'Genre 1' OR 'Genre 2' OR 'Genre 3' I need those genres to have AND logic.

How can I do this properly?

You need to set the filter with execution: 'and' . I've added this as an example to Tire integration test suite:

s = Tire.search('articles-test') do
  query { all }
  filter :terms, :tags => ['ruby', 'python'], :execution => 'and'
end

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