elasticsearch - NEST:如何查询多个索引并处理不同的子类(文档类型)?

标签 elasticsearch nest

我在我的 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# 的协变为您工作:

https://github.com/Mpdreamz/NEST/blob/master/src/Nest.Tests.Integration/Search/SubClassSupport/SubClassSupportTests.cs

在您的情况下,如果所有类型都不是共享基类的子类,您仍然可以使用“对象”

即:

 .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/

相关文章:

elasticsearch - 如何找到Elastic NEST查询的总点击数?

elasticsearch - 在DateRangeQuery中进行比较的方式是哪种?

c# - Elasticsearch 1.x 应该使用哪个版本的 NEST NuGet 包?

elasticsearch - Elasticsearch 6.7 _reindex操作不一致报告映射器错误

elasticsearch - Elasticsearch Nest是否不遵守POCO字段上的index = not_indexed?

elasticsearch - 在批量索引期间检测更改

elasticsearch - 每天使用NEST和ElasticSearch计数文档

elasticsearch - 如何使用补全字段为对象建立索引

elasticsearch - 我如何使用批注进行类似@Query(value = “{” query“:”“}”的聚合

elasticsearch - 如何在Elasticsearch中存储 bool 数组并执行XOR操作?