【问题标题】:NEST: How to query against multiple indices and handle different subclasses (document types)?NEST:如何查询多个索引并处理不同的子类(文档类型)?
【发布时间】:2013-04-20 13:05:07
【问题描述】:

我在我的 C# 项目中将 ElasticSearch 与 NEST 结合使用。我的用例包括几个具有不同文档类型的索引,到目前为止我分别查询这些索引。现在我想实现一个全局搜索功能,它可以查询所有现有的索引、文档类型并正确地对结果进行评分。

所以我的问题是:我如何通过使用 NEST 来实现这一点?

目前我正在使用函数SetDefaultIndex,但如何定义多个索引?

也许为了更好地理解,这是我想用 NEST 实现的查询:

{
  "query": {
    "indices": {
      "indices": [
        "INDEX_A",
        "INDEX_B"
      ],
      "query": {
        "term": {
          "FIELD": "VALUE"
        }
      },
      "no_match_query": {
        "term": {
          "FIELD": "VALUE"
        }
      }
    }
  }
}

TIA

【问题讨论】:

    标签: elasticsearch nest


    【解决方案1】:

    您可以明确告诉 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&lt;dynamic, Hit&lt;dynamic&gt;, Type&gt;),您可以手动返回基于某个 json 值(动态)或命中元数据的类型。

    【讨论】:

    • 您好Martijn,感谢您的回复!查询不同索引的方法我已经想通了。我目前面临的主要问题是我有 具有不同结构的不同文档类型存储在诸如书籍、汽车等的索引中。我的意思是您的示例是:client.Search MyObject 将在我的案例更通用,因为我想通过一个查询来检索书籍、汽车等。我尝试使用泛型类型但没有成功。
    • 我取回文档的唯一方法是使用 client.Search(query)。我还在连接设置中添加了 MapTypeIndices (...)。你能举个例子来完成类似var results = Client.Search&lt;?????????????????&gt;(s =&gt; s .Indices(new[] { “Book-index", "Car-index" }) .Size(200) .MatchAll() );的事情吗?或者你推荐另一种方法吗?非常感谢您的努力!
    • 更新:目前我正在使用 Books、Cars 等基类,但这不是一个干净的解决方案。 client.Search&lt;BASECLASS&gt;
    • @Neil NEST 也应该在这里介绍您,请参阅我的更新答案。
    • @Martjin,非常感谢您 - 像魅力一样工作!我已经相应地更新了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2016-07-19
    相关资源
    最近更新 更多