且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ElasticSearch NEST API将值更新为null

更新时间:2022-05-07 00:06:31

而不是更改整个请求应序列化null的方式,最安全,最隔离的方法是为该属性引入一个单独的POCO进行更新您要清除的具有以下属性.

Rather then changing how null should be serialised for the entire request the safest and most isolated way to do this is to introduce a separate POCO for the update where the property you want to clear has the following attribute.

[JsonProperty(NullValueHandling = NullValueHandling.Include)]

示例POCO:

// <summary>
/// This POCO models an ElasticsearchProject that allows country to serialize to null explicitly
/// So that we can use it to clear contents in the Update API
/// </summary>
public class PartialElasticsearchProjectWithNull
{
    [JsonProperty(NullValueHandling = NullValueHandling.Include)]
    public string Country { get; set; }
}

使用该POCO的示例更新:

Example update using that POCO:

var partialUpdate = new PartialElasticsearchProjectWithNull { Country = null };

this._client.Update<ElasticsearchProject, PartialElasticsearchProjectWithNull>(update => update
    .Id(3) 
    .Doc(partialUpdate)
);

这将生成以下JSON:

which will generate the following JSON:

{
  "doc": {
    "country": null
  }
}