我在我的 C# 项目中尝试结合使用 ElasticSearch 和 NEST。我的用例包括几个具有不同文档类型的索引,到目前为止我分别查询这些索引。现在我想实现一个全局搜索功能,该功能可以查询所有现有索引、文档类型并对结果进行正确评分。
所以我的问题是:如何使用 NEST 来实现这一点?
目前我正在使用函数 SetDefaultIndex
但我如何定义多个索引?
也许为了更好地理解,这是我想用 NEST 实现的查询:
{
"query": {
"indices": {
"indices": [
"INDEX_A",
"INDEX_B"
],
"query": {
"term": {
"FIELD": "VALUE"
}
},
"no_match_query": {
"term": {
"FIELD": "VALUE"
}
}
}
}
}
TIA
最佳答案
您可以明确告诉 NEST 使用多个索引:
client.Search<MyObject>(s=>s
.Indices(new [] {"Index_A", "Index_B"})
...
)
如果你想搜索所有索引
client.Search<MyObject>(s=>s
.AllIndices()
...
)
或者如果你想搜索一个索引(那不是默认索引)
client.Search<MyObject>(s=>s.
.Index("Index_A")
...
)
请记住,从 elasticsearch 19.8 开始,您还可以在索引名称上指定通配符
client.Search<MyObject>(s=>s
.Index("Index_*")
...
)
至于你的indices_query
client.Search<MyObject>(s=>s
.AllIndices()
.Query(q=>q
.Indices(i=>i
.Indices(new [] { "INDEX_A", "INDEX_B"})
.Query(iq=>iq.Term("FIELD","VALUE"))
.NoMatchQuery(iq=>iq.Term("FIELD", "VALUE"))
)
)
);
更新
这些测试展示了如何让 C# 的协变为您工作:
在您的情况下,如果所有类型都不是共享基类的子类,您仍然可以使用“对象”
即:
.Search<object>(s=>s
.Types(typeof(Product),typeof(Category),typeof(Manufacturer))
.Query(...)
);
这将搜索 /yourdefaultindex/products,categories,manufacturers/_search
并设置默认 ConcreteTypeSelector
了解每个返回文档的类型。
使用 ConcreteTypeSelector(Func<dynamic, Hit<dynamic>, Type>)
您可以根据某些 json 值(动态)或命中元数据手动返回类型。
关于elasticsearch - NEST:如何查询多个索引并处理不同的子类(文档类型)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16235039/