这似乎是一个非常简单的问题,但我从其他解决方案和网站尝试的所有东西都不起作用。我有三个不想被索引或查询的字段--:p_s、:gender和:part_of_speech--但是elasticsearch仍然从这些字段返回值,即使我没有指定它们应该被索引或查询。大约在一半的时候,this article说对索引说no,但他们没有指出这将发生在哪里。
术语控制器:
def search
@terms = Term.search(params[:query]).page(params[:page])
end型号:
require 'elasticsearch/model'
class Term < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
settings index: { number_of_shards: 1, number_of_replicas: 0 },
do
mappings dynamic: 'false' do
indexes :id, index: :not_analyzed
indexes :name, analyzer: :spanish_analyzer
indexes :definition, analyzer: :combined_analyzer
indexes :etymology1, analyzer: :combined_analyzer
indexes :etymology2, analyzer: :combined_analyzer
indexes :uses, analyzer: :combined_analyzer
indexes :notes1, analyzer: :combined_analyzer
indexes :notes2, analyzer: :combined_analyzer
end
end
def self.search(query)
__elasticsearch__.search(
{
query: {
multi_match: {
query: query,
fields: ['name^7', 'definition^6', 'etymology1^5', 'etymology2^4', 'uses^3', 'notes1^2', 'notes2^1'],
operator: 'and'
}
}
}
)
end
end
# Delete the previous term index in Elasticsearch
Term.__elasticsearch__.client.indices.delete index: Term.index_name rescue nil
# Create the new index with the new mapping
Term.__elasticsearch__.client.indices.create \
index: Term.index_name,
body: { settings: Term.settings.to_hash, mappings: Term.mappings.to_hash }
# Index all term records from the DB to Elasticsearch
Term.import(force: true)发布于 2016-06-25 03:10:12
要将字段标记为非索引字段,请使用以下命令:
mappings dynamic: 'false' do
...
indexes :p_s, index: :no
indexes :gender, index: :no
indexes :part_of_speech, index: :no
...
end默认情况下,elasticsearch返回"_source"键下的所有文档字段。要仅获取特定字段,您可以在顶级查询级别指定fields数组,如下所示
def self.search(query)
__elasticsearch__.search(
{
query: {
multi_match: {
query: query,
fields: ['name^7', 'definition^6', 'etymology1^5', 'etymology2^4', 'uses^3', 'notes1^2', 'notes2^1'],
operator: 'and'
}
},
fields: ['name', 'definition', 'etymology1', 'etymology2', 'uses', 'notes1', 'notes2']
}
)
end或过滤器"_source"
def self.search(query)
__elasticsearch__.search(
{
query: {
multi_match: {
query: query,
fields: ['name^7', 'definition^6', 'etymology1^5', 'etymology2^4', 'uses^3', 'notes1^2', 'notes2^1'],
operator: 'and'
}
},
'_source': ['name', 'definition', 'etymology1', 'etymology2', 'uses', 'notes1', 'notes2']
}
)
endSee Elasticsearch source filtering docs for more.
当使用multi_match子句时,内部的fields元素指定要在其上运行搜索的字段,还可以指定boost,如示例中所示。outer fields或'_source‘子句决定返回哪些字段,这就是您要返回的字段。
为了在调试elasticsearch查询时更好地了解正在发生的事情,可以使用Sense这样的工具。当您得到想要的结果时,将查询转换为ruby代码可能比反之容易得多。
发布于 2016-06-25 02:58:47
我认为使用包含的elasticsearch方法非常有意义。然而,在我自己的情况下,在我的模型中,我做了一些类似的事情,根据您自己的情况进行了修改:
def as_indexed_json
as_json(only: [:id, :name, :definition, :etymology1, :etymology2, :uses, :notes1, :notes2])
end这应该是可行的,因为在默认情况下,Elasticsearch会调用模型中的as_indexed_json方法来获取它需要索引的数据。
https://stackoverflow.com/questions/38020022
复制相似问题