首页 > 解决方案 > 无法索引 ElasticSearch 中的非模型字段

问题描述

我正在使用带有elasticsearch-railsgem 的 Rails 6。我正在尝试索引函数的结果,但它没有出现在索引中并且不可搜索。这是我的课。

class Asset < ApplicationRecord

    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks

    def my_field
       return "this is my field"
    end

    def as_indexed_json(options={})
        as_json(only: [:my_field])
    end



    settings index: {
       number_of_shards: 10,
       max_ngram_diff: 50
   },
   analysis: {
       filter: {
       ngram_filter: {
          type: "ngram",
          min_gram: "3",
          max_gram: "10",
       }
   },
   analyzer: {
      ngram_filter: {
         type: "custom",
         tokenizer: "standard",
         filter: ["lowercase", "ngram_filter"]
       }
   }


  } do
  mapping do

     indexes :my_field, type: "text", analyzer: "standard"

   end
 end

end

当我查询索引时curl(我省略了其他命中,因为除了 id 之外它们都相同):

curl -X GET 'localhost:9200/assets/_search?_source=true&pretty'

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 10,
    "successful" : 10,

    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1911,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "assets",
        "_type" : "_doc",
        "_id" : "13",
        "_score" : 1.0,
        "_source" : { }
      }, 

当我索引模型中定义的数据库字段时,一切都按预期工作,但我需要索引函数的返回值。

标签: ruby-on-railsrubyelasticsearchruby-on-rails-6

解决方案


你试过这个吗,我希望它有效

class Asset < ApplicationRecord
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  def my_field
    { my_field: "this is my field" }
  end

  def as_indexed_json(options={})
    as_json(only: [:id]).merge(my_field)
  end
end

推荐阅读