Search code examples
elasticsearchruby-on-rails-2tire

Multi type search with independent filters in elasticsearch


I have a separate index for each account, in which the mappings for each model (user and comments - just an example, actual app has many models) are specified.

include Tire::Model::Search

Tire.index('account_1') do
  create(
    :mappings => {
      :user => {
        :properties => {
          :name => { :type => :string, :boost => 10 },
          :company_name => { :type => :string, :boost => 5 },
          :blocked => { :type => :boolean, :include_in_all => false }
        }
      },
      :comments => {
        :properties => {
          :description => { :type => :string, :boost => 5 }
        }
      }
    }
  )
end

How do I add a filter in my search query such that, only users with blocked => true are returned in search results. This should not affect the search results of comments type. Is this possible? Is there any filter in elasticsearch to do the same?


Solution

  • Got the answer...

    You can use an or combo of not-exists and term filter...

        search_key = 'test'
        Tire.search [account_1] do
          query do
            filtered do
                query { string search_key }
                filter :or, { :not => { :exists => { :field => :blocked } } },
                            { :term => { :blocked => true } }
            end
          end
        end