ruby-on-railselasticsearchchewy-gem

Merging elastic search query and filter doesn't work correctly


I have to merge to query and filter. we did this in elastic search 2.4 using filter_mode(:must) after merging query and filter.

Now filter_mode and query_mode in incompatible. I am merging query using 'and'. I am using chewy for using elastic search in rails framework

query_string = index.query(bool: { should: [{ term: { title: query } }, { term: { tags: query } }] })

domain_filter = index.filter(term: { domain_id: domain_id })

merged_query = query_string.and(domain_filter)

now query_string product 1 result. so filter should produce a subset of that result.

instead when I do query_string.filter(term: { domain_id: domain_id })

It produces 44 results. My main goal is to merge both the query to filter results on domain_id. when i write domain_filter as query it produced a filterd result

domain_filter  = index.query(term: { domain_id: domain_id })


merged_query = query_string.and(domain_filter)

the above-merged query produces the correct result. but I think its wrong to use it like this. I want to use ES filter. can someone help me with this?

Detailed query produced with query_string.and(domain_filter)

{:index=>["resource_domain"], :type=>["resource_domain"], :body=>{:query=>{:bool=>{:should=>[{:term=>{:title=>"club-4"}}, {:term=>{:tags=>"club-4"}}], :filter=>{:term=>{:domain_id=>6}}}}}}

the above one produces wrong result

Expected:

{:index=>["resource_domain"], :type=>["resource_domain"], :body=>{:query=>{:bool=>{:must=>[{:bool=>{:should=>[{:term=>{:title=>"club-4"}}, {:term=>{:tags=>"club-4"}}]}}, {:term=>{:domain_id=>6}}]}}}}

Solution

  • You need to shove your domain filter into a bool/filter clause, like this

    query = index.query(bool: { minimum_should_match: 1, should: [{ term: { title: query } }, { term: { tags: query } }], filter: [{term: { domain_id: domain_id }}] })