ruby-on-rails - 无法索引 ElasticSearch 中的非模型字段
问题描述
我正在使用带有elasticsearch-rails
gem 的 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" : { }
},
当我索引模型中定义的数据库字段时,一切都按预期工作,但我需要索引函数的返回值。
解决方案
你试过这个吗,我希望它有效
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
推荐阅读
- javascript - 如何获得显示的单元格的精确副本?
- c# - How should property types be used correctly in class design
- cron - Debian 9 的 crontab 权限问题
- discord.py - Discord.py:更改服务器名称
- python - Pandas drop.duplicate 函数无法按预期工作
- android - 使用 Firestore 的 Recycler View 在数据更改时显示在顶部
- github - 有没有办法删除 github 工作流
- java - 使用 JpaRepository 进行内部连接,无需编写查询
- javascript - 关于 html DOM 事件的安全问题
- php - Xampp sql 数据库错误1049。我在xampp 中将sql 文件保存在哪里?