简体   繁体   中英

How to set up a elasticsearch facet search on a nested rails model

Is it possible to setup a facet search on a nested model? I have a user model that has a profile model. I can search the user model for terms in the profile model. Now I want to filter the search results (users) by the location attribute in the profile model.

User Model:

class User< ActiveRecord::Base
  has_one :profile

  include Tire::Model::Search
  include Tire::Model::Callbacks

  mapping do
   indexes :profiles do
    indexes :first_name
    indexes :last_name
    indexes :summary, type: 'string'
    indexes :location, type: 'string', boost: 50
    indexes :subjects, type: 'string', boost: 100
    indexes :education, type: 'string'
   end
  end

  def self.search(params)
    tire.search(load: true, page: params[:page], per_page: 10) do |s|
      s.query { string params[:query]} if params[:query].present?
      s.facet "locations" do
        terms :location???
      end
    end
  end

  # Rest of class omitted
end

In the search method I do not know what to put down for the "terms". terms :location???

View:

  <% @allusers.facets['locations'??]['terms'].each do |facet| %> **error on this line, locations cannot be nil**
      <li>
      <%= link_to_unless_current Profile.find(facet['term']).location, params.merge(id: facet['term']) %>
        <% if params[:location??] == facet['term'].to_s %>
          (<%= link_to "remove", location: nil %>)
        <% else %>
          (<%= facet['count'] %>)
        <% end %>
      </li>
    <% end %>

In the view I do not know what to put down for the params in place of [:location]

You should be able to replace terms :location with terms "profiles.location" . Notice how it's a string now instead of a symbol. Although you might need to use term instead, or do you allow your users to have multiple locations in their profile?

The form field and facet name doesn't need to change. You could name your facet "foobar" and it would still work as long as the facet name is the same in both the model and view. The param is similar, it's just holding the value and can be named anything. I would consider renaming it to profile_location just to follow the rails convention of separating associations with an underscore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM