Seong Kim
Seong Kim

Reputation: 585

How can I do search category.name by using elasticsearch in Rails?

My search working fine. But I have to type "1" or "2" to get results of "roommate" or "sublet". Model has a column called category_id which is an integer. Model Category has column :name which is a string.

Thus, I have category_id 1 is having "roommate" and 2 is "sublet"

below is my Housing model:

class Housing < ActiveRecord::Base
    extend FriendlyId
    friendly_id :title, use: :slugged
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks

    belongs_to :user
    belongs_to :category

    validates :title, :presence => true
    validates :category_id, :presence => true
    validates :created_at, :presence => false
    validates :user_email, :presence => true
    validates :description, :presence => false
    validates_length_of :title, :maximum => 30

    def self.search(query)
      __elasticsearch__.search(
        {
          query: {
            # multi_match: {
            simple_query_string: {
              query: query,
              fields: ['title^10', 'category_id']
            }
          }
        }
      )
    end

end

How can I fix fields: ['title^10', 'category_id'] So user can search "roommate" instead of must search integer "1" to get result of roommate ?

I tried fields: ['title^10', 'category.name'] but not working.

Upvotes: 0

Views: 188

Answers (1)

udit mittal
udit mittal

Reputation: 537

fields: ['title^10', 'category.name'] won't work unless you have correct mapping defined. Elasticsearch doesn't know about your associations. ES is a document store and searches for records using it's own document store. So unless you add your category name to the document stored in ES, you won't be able to search it.

TL;DR

Define a mapping. Example:

mapping dynamic: 'strict' do
    indexes :category do
      indexes :name
    end
    indexes :title
end

Here category will now be stored as nested object inside your index and hence is searchable using category.name

Upvotes: 1

Related Questions