无法在elasticsearch中索引非模型字段

zdwk9cvp  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(1)|浏览(383)

我正在使用Rails6和 elasticsearch-rails 宝石。我试图索引一个函数的结果,但它没有出现在索引中,并且不可搜索。这是我的课。

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" : { }
      },

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

bakd9h0s

bakd9h0s1#

你试过这个吗,希望有用

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

相关问题