Elastic Search/Tire: How do I filter a boolean attribute?
Asked Answered
P

3

11

I want to filter the private boolean of my class so it only shows resources that aren't private but it's not working for me. (I dumbed down the code tremendously)

mapping do
  indexes :private,  type: "boolean"
  indexes :name, type: "string"
 end 
end

def self.search(params)
    tire.search(load: true, page: params[:page], per_page: 20) do
       query  { string params[:query] } if params[:query].present?
       # So far I've tried...
       # filter :bool, :private => ["false"] 
       # filter :bool,  private: false
    end
end

How do I do this correctly?

Poult answered 23/8, 2012 at 1:8 Comment(0)
C
16
  filter :term, :private => false

Should do the trick. Depending on whether you want to do stuff with facets it may be more efficient to do your filtering a filtered query rather than at the top level, ie

tire.search(...) do 
  query do
    filtered do
      query { string, params[:query] }
      filter :term, :private => false
    end
  end
end

It shouldn't change the results though.

You can also do this with a bool filter, but not quite how you tried - within a bool filter you need to build up a structure that says what's optional and what's not

For example

tire.search(load: true, page: params[:page], per_page: 20) do
   query  { string params[:query] } if params[:query].present
   filter :bool, :must => {:term => {:private => true}}
end

A bool filter is slower than using an and filter (which is what tire does behind the scenes if you specify multiple filters) but obviously gives you more flexibility.

Calamus answered 25/8, 2012 at 5:5 Comment(0)
M
4

You can try:

tire.search(load: true, page: params[:page], per_page: 20) do
    query do
        boolean do
            must { string params[:query] } if params[:query].present?
            must { term :private, true }
        end
    end
end
Manners answered 25/8, 2012 at 4:50 Comment(0)
S
3

According to the elasticsearch - guide, booleans are stored as T or F, so I would try filtering by T or F.

For example

filter :terms, :private => ['T']

I haven't actually used tires, this is just based on some research on the guide and in the examples.

Stempson answered 25/8, 2012 at 4:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.