Avishai
Avishai

Reputation: 4732

Group by entire field value in Tire/ElasticSearch

I'm using the Tire rubygem to connect to ElasticSearch. How can you return facets based on a particular field's value?

For example, I have a field areas, and I'd like to show the top 10 areas as filter options:

Areas

def self.search(params={})
        tire.search(page: 1 || params[:page], per_page: 10, load: true) do
          # Set up query
          query do
            boolean do
              must { string params[:query], default_operator: "AND" } if params[:query].present?
              must { range :price, { gte: (params[:min_price] || 0), lte: params[:max_price] } } if params[:max_price].present?
            end
          end
          # Facets to return
          # this is where I get stuck:
          facet 'areas' do
            terms [:area_name], size: 10
          end
       end
end

The facet block just returns:

{"areas"=>{"_type"=>"terms", "missing"=>5754, "total"=>0, "other"=>0, "terms"=>[]}}

Even though all of the records have a value for area name.

Upvotes: 0

Views: 542

Answers (1)

karmi
karmi

Reputation: 14419

Facets are computed from the documents returned by a query, so if you don't get any hits, no facets are computed. Your facet definition is incorrect, you should pass the field name as a Symbol or String, see https://github.com/karmi/tire/blob/master/test/integration/facets_test.rb#L16.

Upvotes: 1

Related Questions