How can I express this SQL in Elasticsearch-rails and Elasticsearch-model?

595 Views Asked by At

I used gem elasticsearch-rails and elasticsearch-model and I have difficult to write this query in elasticsearch-rails.

SELECT "news".* FROM "news" 
WHERE "news"."is_active" = 'true' AND 
  ((priority is not null AND created_at > '2014-07-08 08:55:52.888587') OR 
   (created_at > '2014-07-08 08:55:52.888820' AND is_persisted = 't') ) 
ORDER BY "news"."priority" ASC, "news"."created_at" DESC 
LIMIT 10 OFFSET 0

In my previous project I used "Tire Model", I used something like this: filter :bool, must: {and: [{term: {field with options}}, {term: {field with options}}]}, It works in tire model

But if I use something like this in elasticsearch-rails, it throws missing filtered error I write something like this for filtering active record:

def self.news_index(page = 1)
  query =:
  response=self.elasticsearch.search query: { match: { is_active: true }}
  response=response.page(page)
end

In the above method, I want to add combined filter with bool option. Can anyone guide me?

1

There are 1 best solutions below

0
On

Elasticsearch-ruby is far closer to the elasticsearch DSL when it comes to querying. Most of the time you'll be passing in hashes (or hash-like objects) to the query method.

Something like this should get you close:

self.search query: {
  filtered: {
    query: { match: { is_active: true }},
    filter: { 
      bool: {
        must: { 
          and: [{term: {field with options}}, {term: {field with options}}]
        }
      }
    } 
  }
}

The difference is that instead of filter being a method call in the tire query which took arguments :bool and the filter. You now need to specify a :filter key with a hash value which then contains a :bool key with your existing filter as the value.