Elasticsearch 7 和 Nest 7 - 检索结果时,我收到键值对列表或空对象列表

Elasticsearch 7 and Nest 7 - When retrieving results I receive a keyvalue pair list or a list of empty objects

我正在将一些旧代码从 Nest 1.9.4 转换到全新版本的 Nest 7.4。

在旧代码中,我们从返回多种对象类型的别名索引中查询,因此我们将对象用作泛型类型,如下所示:

var response = ElasticClient.Search<object>(search)

搜索完成后,我们从响应中获取文档集合,并根据对象的类型分离我们的对象: var posts = response.Documents.OfType<Blog.Post>;

这是第一个问题,对于当前的 Nest 实现,如果我提供 "object" 作为通用类型,我会收到一个 IReadOnlyCollection,其中我的文档的每个属性都是一个字典。它迫使我更改我的代码,但没什么大不了的,我知道当前实现使用的版本已经过时了,但将这种结果转换为实际对象并不容易。

第二个问题是,如果我更改我的代码以查询正确的类型 var response = ElasticClient.Search<Blog.Post>(search) elasticsearch returns 正确的命中数但文档属性为空,所有这些。

如果我尝试使用我的类型反序列化来自服务器的响应,它工作正常。

有人见过这种行为吗?

您将要 运行 了解的一个非常大的区别是,在 NEST 1.9.4 中,Elasticsearch 在命中元数据中包含一个 _type,用于匹配查询的每个命中.结合元数据中的_index,NEST可以将每次命中的_sourceJSON对象反序列化为预期的POCO。在您的示例中,尽管您将 object 指定为 return 的每个文档的类型,但 NEST 可以根据客户端已配置的索引和类型将其中一些文档反序列化为 Blog.Post和。这样就可以使用 LINQ 的 .OfType<T>() 进行过滤以正常工作。

From Elasticsearch 6.0 onwards, types are being removed, so there is no longer a _type field in the hit metadata that NEST can use to infer which POCO a document should be deserialized to. One way in which this can be resolved is by introducing a discriminator field to the document that can be used to determine what POCO type the document should ultimately be deserialized into. For example, you might consider hooking up JsonNetSerializer from the Nest.JsonNestSerializer nuget package, and serializing type information to use when deserializing.