使用 NEST 在多个 elasticsearch 索引中搜索

Searching in multiple elasticsearch indexes using NEST

我正在尝试使用 nest 7.10.1 在 elasticsearch 中搜索文本。我想在两个不同的索引中搜索,我得到了文档形式的响应,但我无法访问它的属性,因为结果包含两个索引的组合。下面是我试过的代码。这两个索引具有相同的属性。我在 foreach 循环中使用什么来访问结果文档的键和值。

public void searchIndices(string query) {
    var response = client.Search<object>(
      s => s.Index("knowledgearticles_index, index2")
            .Query(q => q.Match(m => m.Field("locationName")
                         .Query(query))));

    Console.WriteLine(response.Documents);
    
    foreach(object r in response.Documents) {
      
    }
}

我正在使用 elasticsearch 7.10.2

the search response has the _index meta field 中返回的每个原始命中与其关联:

"hits" : {
  "total" : {
    "value" : 91,
    "relation" : "eq"
  },
  "hits" : [
    {
      "_index" : "knowledgearticles_index",   <---
      "_type" : "_doc",
      "_id" : "r_oLl3cBZOT6A8Qby8Qd",
      "_score" : 1.0,
      "_source" : {
        ...
      }
    }

现在,在 NEST,

.Documents is a convenient shorthand for retrieving the _source for each hit

-- 这意味着您将无法访问元属性。

所以诀窍是 use a loop 像这样:

foreach (var hit in response.HitsMetadata.Hits) {
  Console.WriteLine(hit);
}

如果您要搜索的两个索引包含不同的 JSON 结构,则 Search<T> 中的 T 需要是不同的 JSON 结构可以反序列化为。 object 将按照您问题中的示例工作,但是没有任何属性的类型化访问。

克服这个问题的一个简单方法是 hook up the JsonNetSerializer 然后使用 JObjectT

var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings =
    new ConnectionSettings(pool, sourceSerializer: JsonNetSerializer.Default);
var client = new ElasticClient(connectionSettings);

var response = client.Search<JObject>(s => s
    .Index("knowledgearticles_index, index2")
    .Query(q => q
        .Match(m => m
            .Field("locationName")
            .Query(query)
        )
     )
);

我们现在可以访问 JObject 上的属性,但仍需要处理每个 属性 的类型。