ElasticSearch NEST GET响应未反序列化

时间:2018-01-23 14:54:05

标签: c# elasticsearch get deserialization nest

我们从第三方连接到ElasticSearch以获取NEST nuget包的一些数据。但是,如果我们使用GET<>调用响应未在强类型POCO中反序列化。 HTTP调用成功,在正文中有一个带有数据的json对象。

var result = _elasticSearchClient.Get<Contractor>(188153, request => request
.Index("{index_name}")
.Type("{type_name}"));

--POCO. Naming of the property as in the json message
public class Contractor
{
public int contractor_id { get; set; }
public string type { get; set; }
public string type_description { get; set; }
public string contractor_code { get; set; }
public string name { get; set; }
...
}

使用HttpClient和JsonCovert调用反序列化对象

var response = Task.Run(() => _httpClient.GetAsync(url)).Result;
var responseMessage = Task.Run(() => response.Content.ReadAsStringAsync()).Result;
var contractor = JsonConvert.DeserializeObject<Contractor>(responseMessage);

ElasticSearchClient的配置

var url = new Uri($"{BaseUrl}");

var connectionSettings = new ConnectionSettings(url);
connectionSettings.ClientCertificate(GetCertificateFromStore());
connectionSettings.BasicAuthentication(Username, Password);
connectionSettings.ThrowExceptions();
connectionSettings.PrettyJson();
connectionSettings.DisableDirectStreaming();
connectionSettings.DefaultFieldNameInferrer(p => p);

var elasticSearchClient = new ElasticClient(connectionSettings);

DebugInformation: 在GET上成功进行低级别调用构建的有效NEST响应:/ {index_name} / {type_name} / 188153?pretty = true

此API调用的审计跟踪:   - [1] HealthyResponse:节点:https:// {baseUrl} / Took:00:00:01.0835021 请求:未捕获请求流或已通过序列化程序读取完成。在ConnectionSettings上设置DisableDirectStreaming()以强制在响应上设置它。

响应:

{
  "_index" : "{index_name}",
  "_type" : "{type_name}",
  "_id" : "188153",
  "_version" : 1,
  "found" : true,
  "_source" : {
    "contractor" : {
      "contractor_id" : 188153,
      "type" : "OVE",
      "type_description" : "Overig",
      "contractor_code" : "RES0000826",
      "name" : "OrganizationName", 
   }
}

NEST NuGet包5.6.0

Elasticsearch版本6.0.0

我错过了什么?

1 个答案:

答案 0 :(得分:1)

它没有被NEST反序列化,因为Elasticsearch中的_source文档是一个具有一个属性"contractor"的对象,其值是包含属性的对象。

为了正确反序列化,Elasticsearch中的_source文档需要

  "_source" : {
      "contractor_id" : 188153,
      "type" : "OVE",
      "type_description" : "Overig",
      "contractor_code" : "RES0000826",
      "name" : "OrganizationName"
   }

或者,POCO应该是

public class ContractorWrapper //choose any type name you like :)
{
    public Contractor contractor { get;set; }
}

匹配JSON结构。