4

I use Elasticsearch in my Rails application (elasticsearch-model, elasticsearch-rails gems). I wrote a simple search:

def search
    @posts = params[:term] ? Post.search(params[:term]) : [] 
    render json: @posts
end

It works good. But I made some fixes in order to do search among 'deleted=false' and 'enabled=true' subset then :

def search
    @posts = params[:term] ? Post.existing.enabled.search(params[:term]) : [] 
    render json: @posts
end

Post

class Post < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

    scope :existing, ->{ where(deleted: false) }
    scope :enabled,  ->{ where(enabled: true) }
end
Post.import

It doesn't work - I see the same results as in the previous case(with any value in 'deleted' and 'existing' columns. How can I fix it? Thanks in advance.

2 Answers 2

3

Change how your search method works.

@posts = params[:term] ? Post.search(params[:term], existing: true, enabled: true) : []

Post model

def self.search query, options = {}
  __add_filter = lambda do |f|
    search_definition[:filter][:and] ||= []
    search_definition[:filter][:and] |= [f]
  end
  search_definition = {
    query: {},
    filter: {}
  }
  if options[:existing]
    __add_filter.({ term: {'deleted' => false}})
  end
  if options[:enabled]
    __add_filter.({ term: {'enabled' => true}})
  end
  unless query.blank?
    search_definition[:query] = {
      # add your query logic
    }
  else
    search_definition[:query] = { match_all: {}}
  end
  __elasticsearch__.search(search_definition)
end

You could also check elastic_search example

Sign up to request clarification or add additional context in comments.

Comments

0
def self.search query, options = {}
  search_definition = {
    query: {},
    filter: {}
  }
  __add_filter = lambda do |f|
    search_definition[:filter][:and] ||= []
    search_definition[:filter][:and] |= [f]
  end
  if options[:existing]
    __add_filter.({ term: {'deleted' => false}})
  end
  if options[:enabled]
    __add_filter.({ term: {'enabled' => true}})
  end
  unless query.blank?
    search_definition[:query] = {
      # add your query logic
    }
  else
    search_definition[:query] = { match_all: {}}
  end
  __elasticsearch__.search(search_definition)
end

1 Comment

Usually it's better to explain a solution instead of just posting some rows of anonymous code. You can read How do I write a good answer, and also Explaining entirely code-based answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.