ruby-on-railsrubyelasticsearchruby-on-rails-5elasticsearch-rails

Add Filter To ElasticSearch Query


I'm trying to create a query where the user can search for ES documents where the brand field is equal to some string. Here is the query I currently have that works but has no filtering. I'm using elasticsearch-rails with Ruby on Rails.

@products = Product.search(
     query:{
        function_score:{
          query: {    
            multi_match: {
              fields: ['brand^5', '_all'],
              query: "#{query}",
              fuzziness: "AUTO"
            }
          },
          field_value_factor:{
            field: "popularity",
            modifier: "log1p"
          }
        }
     }).page(page).per(25)

I've statically assigned a brand name to the filter for testing purposes. In this case the user should be seeing results for their search keyword where the brand name is "NordicTrack".

query:{
        function_score:{
          query: {    
            multi_match: {
              fields: ['brand^5', '_all'],
              query: "#{query}",
              fuzziness: "AUTO"
            }
          },
          filter: {
            term: {"brand":"NordicTrack"}
          }, 
          field_value_factor:{
            field: "popularity",
            modifier: "log1p"
          }
        }
     }
     ).page(page).per(25)

This query gives me the following error:

[400] {"error":{"root_cause":[{"type":"parsing_exception","reason":"no [query] registered for [filter]","line":1,"col":139}],"type":"parsing_exception","reason":"no [query] registered for [filter]","line":1,"col":139},"status":400}

I'm not sure why this isn't working. Any help would be appreciated!


Solution

  • I'm not sure about how Elasticsearch-rails with Ruby on Rails parses Query. But I tried below query in Kibana :

    GET test/testt/_search
    {
      "query": {
        "filter": {
          "term": {
            "brand": "NordicTrack"
          }
        }
      }
    }
    

    which is somewhat similar to your part of the query which is giving you the error and I too got that same error. But when I wrap the term query with bool query then it returns desired results. Query :

    GET test/_search
    {
      "query": {
        "bool": {
          "filter": {
            "term": {
              "brand": "NordicTrack"
            }
          }
        }
      }
    }
    

    Give it a Shot.