ElasticSearch NEST API 更新值为空

本文关键字:更新 NEST API ElasticSearch | 更新日期: 2023-09-27 18:37:15

我正在使用 NEST api,但我在使用client.Update<T, K>方法将值更新为null

调用更新时是否有任何参数或设置允许通过嵌套 API 设置null

我知道我可以理智地做到这一点。

ElasticSearch NEST API 更新值为空

与其更改整个请求的 null 序列化方式,最安全、最隔离的方法是为更新引入单独的 POCO,其中要清除的属性具有以下属性。

[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 的更新示例:

var partialUpdate = new PartialElasticsearchProjectWithNull { Country = null };
this._client.Update<ElasticsearchProject, PartialElasticsearchProjectWithNull>(update => update
    .Id(3) 
    .Doc(partialUpdate)
);

这将生成以下 JSON:

{
  "doc": {
    "country": null
  }
}
  • 就我而言,我有一个 .NET DateTime? 属性,我想将 ElasticSearch date 属性更新为 null 或空。
  • 我不能用Doc方法做到这一点。它不会将我的空赋值推送到 elasticsearch(可能是因为 elasticsearch date 类型不支持 null)。

这就是我所做的:

  1. 我修改了elasticsearch.yml文件以包含此设置:script.groovy.sandbox.enabled: true
  2. 我将 C# 代码修改为以下内容,以从文档中删除该属性:

        _elasticClient.Update<MyIndexType, object>(u => u
            .Id(myDocumentId)
            .Index(myIndexName)
            .Type(myType)
            .Script(string.Format("ctx._source.remove('"{0}'")", myPropertyName))
            .RetryOnConflict(3));