Cu1ture
Cu1ture

Reputation: 1283

How do you filter a query with elasticsearch-rails gem?

I have a Piece model with a boolean attribute of published.

I want the search results to only contain Pieces that are plublished: true.

My index action for the PiecesController is:

def index
    @list = params[:list]
    @sort = params[:sort]
    if params[:q]
      @pieces = Piece.search(params[:q]).records
    else
      @pieces = Piece.all_in_category(@list, @sort)
    end
end

From searching around it seems that I should overwrite the search method in the Piece controller but I am not sure the correct way of doing this to maintain the current search methods functionality.

What is the best way to filter the elasticsearch results using the elasticsearch-rails gem?

Upvotes: 4

Views: 4608

Answers (2)

Oleksandr Bondar
Oleksandr Bondar

Reputation: 41

Try this format:

Elasticsearch v2.4

@customers = Customer.__elasticsearch__.search(
        query: { 
          bool: {
            filter: {
              term: {"account_id" => current_account.id.to_s}
            },
            must: {
              query_string: {
                query: "*#{params[:q]}*"
              }
            }
          },
        },
        size: options[:per_page],
        from: options[:from]
      ).records

Upvotes: 2

CoupDeMistral
CoupDeMistral

Reputation: 198

have you tried

@pieces = Piece.search(params[:q]).records.where(published: true)

it works on one of my ES models

Upvotes: -1

Related Questions