2015-01-13 62 views
4

我使用NEST API和我使用client.Update<T, K>方法更新值nullElasticSearch NEST API更新值設置爲null

遇到問題有沒有設置任何參數或調用更新時的設置,將允許null槽巢api?

我知道我能做到。

+0

你已經找到了一個解決方案?這適用於合併更新,但會在設置時忽略空值。也許有這個選項? – mbudnik

+0

它似乎插入工作相同 - 忽略空值。 – mbudnik

回答

4

然後改變應該爲整個請求序列化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 
    } 
} 
1
  • 在我的情況下,我有一個.NET DateTime?屬性,我想將ElasticSearch date屬性更新爲null或空。
  • 我不能這樣做Doc method。它不會將我的空賦值推送到elasticsearch(可能是因爲elasticsearch date類型不支持null)。

因此,這裏是我所做的:

  1. 我修改了elasticsearch.yml文件,包括this settingscript.groovy.sandbox.enabled: true
  2. 我修改了我的C#代碼以下to remove the property from the document

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