简体   繁体   English

如何在Rails中使用elasticsearch来搜索category.name?

[英]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". 但是我必须键入“ 1”或“ 2”才能获得“室友”或“子租约”的结果。 Model has a column called category_id which is an integer. 模型有一个名为category_id的列,该列是整数。 Model Category has column :name which is a string. 模型Category:name是字符串。

Thus, I have category_id 1 is having "roommate" and 2 is "sublet" 因此,我有category_id 1是“ roommate”,2是“ 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 ? 如何修复fields: ['title^10', 'category_id']因此,用户可以搜索“ roommate”,而不是必须搜索整数“ 1”以获得室友的结果?

I tried fields: ['title^10', 'category.name'] but not working. 我尝试了以下fields: ['title^10', 'category.name']但不起作用。

fields: ['title^10', 'category.name'] won't work unless you have correct mapping defined. fields: ['title^10', 'category.name']将不起作用,除非您定义了正确的映射。 Elasticsearch doesn't know about your associations. Elasticsearch不了解您的关联。 ES is a document store and searches for records using it's own document store. ES是一个文档存储,并使用其自己的文档存储来搜索记录。 So unless you add your category name to the document stored in ES, you won't be able to search it. 因此,除非您将类别名称添加到ES中存储的文档中,否则您将无法搜索它。

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 现在,类别现在将作为嵌套对象存储在索引内,因此可以使用category.name搜索

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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