elasticsearch,nest,C#,elasticsearch,Nest" /> elasticsearch,nest,C#,elasticsearch,Nest" />

C# 将null设置为文档属性,并在更新时从数据库中删除字段

C# 将null设置为文档属性,并在更新时从数据库中删除字段,c#,elasticsearch,nest,C#,elasticsearch,Nest,我有下面的C级 我也在为我的文档使用模板,下面的模板用于演示测试 { "version": 2, "index_patterns": "documents-test*", "order": 2, "aliases": { "docs-test": {} }, "settings": { "number_of_shards": 1 }, "mappings": { "_doc": { "dynamic": "strict",

我有下面的C级

我也在为我的文档使用模板,下面的模板用于演示测试

{
  "version": 2,
  "index_patterns": "documents-test*",
  "order": 2,
  "aliases": {
    "docs-test": {}
  },
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_doc": {
      "dynamic": "strict",
      "properties": {
        "id": {
          "type": "keyword"
        },
        "description": {
          "enabled": false
        }
      }
    }
  }
}
我正在将
Description
属性设置为
has值
,并为其编制索引。下面是数据库中的一个示例

{
  "_index": "documents-test-2019-07-2-2",
  "_type": "_doc",
  "_id": "55096ff7-5072-4ded-b6a3-94b8e155c9d0",
  "_score": 1,
  "_source": {
    "id": "55096ff7-5072-4ded-b6a3-94b8e155c9d0",
    "description": "has value"
  }
}
查询文档,将
Description
属性设置为
null
,并使用下面的嵌套
IElasticClient.UpdateAsync
方法更新文档

public async Task<Result> UpdateAsync(
 T document,
 string indexName = null,
 string typeName = null,
 Refresh ? refresh = null,
 CancellationToken cancellationToken =
 default) {

 var response = await Client.UpdateAsync<T,
  object>(
   document.Id,
   u => u.Doc(document)
   .Index(indexName ? ? DocumentMappings.IndexStrategy)
   .Type(typeName ? ? DocumentMappings.TypeName)
   .Refresh(refresh),
   cancellationToken);

 var errorMessage = response.LogResponseIfError(_logger);

 return errorMessage.IsNullOrEmpty() ? Result.Ok() : Result.Fail(errorMessage);
}
public异步任务UpdateAsync(
T文件,
字符串indexName=null,
字符串typeName=null,
刷新?刷新=null,
取消令牌取消令牌=
默认值){
var response=await Client.UpdateAsync(
文件Id,
u=>u.Doc(文档)
.Index(indexName??DocumentMappings.IndexStrategy)
.Type(typeName??DocumentMappings.typeName)
.刷新(刷新),
取消令牌);
var errorMessage=response.LogResponseIfError(_logger);
返回errorMessage.IsNullOrEmpty()?Result.Ok():Result.Fail(errorMessage);
}
问题在于,在更新命令后,文档将保持不变,而
说明
字段的值为
has value

在我看来,最合适的解决方案是将C#class
Description
属性设置为null并更新要从文档中删除的字段

public async Task<Result> UpdateAsync(
 T document,
 string indexName = null,
 string typeName = null,
 Refresh ? refresh = null,
 CancellationToken cancellationToken =
 default) {

 var response = await Client.UpdateAsync<T,
  object>(
   document.Id,
   u => u.Doc(document)
   .Index(indexName ? ? DocumentMappings.IndexStrategy)
   .Type(typeName ? ? DocumentMappings.TypeName)
   .Refresh(refresh),
   cancellationToken);

 var errorMessage = response.LogResponseIfError(_logger);

 return errorMessage.IsNullOrEmpty() ? Result.Ok() : Result.Fail(errorMessage);
}

我已经看到了一些答案,但不确定会有什么变化,或者是否有比使用NEST忽略null(繁琐)更好的解决方案或覆盖行为,我最终创建了以下方法

public async Task<Result> UpdateAsync(
    T document, 
    string indexName = null, 
    string typeName = null,
    Refresh? refresh = null, 
    CancellationToken cancellationToken = default)
{
    Guard.Argument(document, nameof(document)).NotNull();

    await RemoveNullFieldsFromDocumentAsync(document, document.Id, indexName, typeName, cancellationToken);

    var response = await Client.UpdateAsync<T, object>(
        document.Id, 
        u => u.Doc(document)
            .Index(indexName ?? DocumentMappings.IndexStrategy)
            .Type(typeName ?? DocumentMappings.TypeName)
            .Refresh(refresh), 
        cancellationToken);

    var errorMessage = response.LogResponseIfError(_logger);

    return errorMessage.IsNullOrEmpty() ? Result.Ok() : Result.Fail(errorMessage);
}

public async Task<Result> UpdateAsync(
    string id, 
    object partialDocument, 
    string indexName = null, 
    string typeName = null,
    Refresh? refresh = null, 
    CancellationToken cancellationToken = default)
{
    Guard.Argument(partialDocument, nameof(partialDocument)).NotNull();
    Guard.Argument(id, nameof(id)).NotNull().NotEmpty().NotWhiteSpace();

    await RemoveNullFieldsFromDocumentAsync(partialDocument, id, indexName, typeName, cancellationToken);

    var response = await Client.UpdateAsync<T, object>(
        id, 
        u => u.Doc(partialDocument)
            .Index(indexName ?? DocumentMappings.IndexStrategy)
            .Type(typeName ?? DocumentMappings.TypeName)
            .Refresh(refresh), 
        cancellationToken);

    var errorMessage = response.LogResponseIfError(_logger);

    return errorMessage.IsNullOrEmpty() ? Result.Ok() : Result.Fail(errorMessage);
}

private async Task<Result> RemoveNullFieldsFromDocumentAsync(
    object document,
    string documentId,
    string indexName = null, 
    string typeName = null,
    CancellationToken cancellationToken = default)
{
    var result = Result.Ok();
    var allNullProperties = GetNullPropertyValueNames(document);
    if (allNullProperties.AnyAndNotNull())
    {
        var script = allNullProperties.Select(p => $"ctx._source.remove('{p}')").Aggregate((p1, p2) => $"{p1}; {p2};");
        result = await UpdateByQueryIdAsync(
                                        documentId, 
                                        script,
                                        indexName,
                                        typeName,
                                        cancellationToken: cancellationToken);
    }

    return result;
}

private static IReadOnlyList<string> GetNullPropertyValueNames(object document)
{
    var allPublicProperties =  document.GetType().GetProperties().ToList();

    var allObjects = allPublicProperties.Where(pi => pi.PropertyType.IsClass).ToList();

    var allNames = new List<string>();

    foreach (var propertyInfo in allObjects)
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            var isNullOrEmpty = ((string) propertyInfo.GetValue(document)).IsNullOrEmpty();
            if (isNullOrEmpty)
            {
                allNames.Add(propertyInfo.Name.ToCamelCase());
            }
        }
        else if (propertyInfo.PropertyType.IsClass)
        {
            if (propertyInfo.GetValue(document).IsNotNull())
            {
                var namesWithobjectName = GetNullPropertyValueNames(propertyInfo.GetValue(document))
                    .Select(p => $"{propertyInfo.PropertyType.Name.ToCamelCase()}.{p.ToCamelCase()}");
                allNames.AddRange(namesWithobjectName);
            }
        }
    }

    return allNames;
}

public async Task<Result> UpdateByQueryIdAsync(
    string documentId,
    string script,
    string indexName = null, 
    string typeName = null, 
    bool waitForCompletion= false,
    CancellationToken cancellationToken = default)
{
    Guard.Argument(documentId, nameof(documentId)).NotNull().NotEmpty().NotWhiteSpace();
    Guard.Argument(script, nameof(script)).NotNull().NotEmpty().NotWhiteSpace();

    var response = await Client.UpdateByQueryAsync<T>(
        u => u.Query(q => q.Ids(i => i.Values(documentId)))
                .Conflicts(Conflicts.Proceed)
                .Script(s => s.Source(script))
                .Refresh()
                .WaitForCompletion(waitForCompletion)
                .Index(indexName ?? DocumentMappings.IndexStrategy)
                .Type(typeName ?? DocumentMappings.TypeName), 
        cancellationToken);

    var errorMessage = response.LogResponseIfError(_logger);

    return errorMessage.IsNullOrEmpty() ? Result.Ok() : Result.Fail(errorMessage);
}
public异步任务UpdateAsync(
T文件,
字符串indexName=null,
字符串typeName=null,
刷新?刷新=null,
CancellationToken CancellationToken=默认值)
{
参数(document,nameof(document)).NotNull();
Wait RemoveNullFieldsFromDocumentAsync(文档、文档.Id、索引名、类型名、取消令牌);
var response=await Client.UpdateAsync(
文件Id,
u=>u.Doc(文档)
.Index(indexName??DocumentMappings.IndexStrategy)
.Type(typeName??DocumentMappings.typeName)
.刷新(刷新),
取消令牌);
var errorMessage=response.LogResponseIfError(_logger);
返回errorMessage.IsNullOrEmpty()?Result.Ok():Result.Fail(errorMessage);
}
公共异步任务UpdateAsync(
字符串id,
对象部分文档,
字符串indexName=null,
字符串typeName=null,
刷新?刷新=null,
CancellationToken CancellationToken=默认值)
{
参数(partialDocument,nameof(partialDocument)).NotNull();
参数(id,nameof(id)).NotNull().NotEmpty().NotWhiteSpace();
Wait RemoveNullFieldsFromDocumentAsync(partialDocument、id、indexName、typeName、cancellationToken);
var response=await Client.UpdateAsync(
身份证件
u=>u.Doc(部分文件)
.Index(indexName??DocumentMappings.IndexStrategy)
.Type(typeName??DocumentMappings.typeName)
.刷新(刷新),
取消令牌);
var errorMessage=response.LogResponseIfError(_logger);
返回errorMessage.IsNullOrEmpty()?Result.Ok():Result.Fail(errorMessage);
}
专用异步任务RemoveNullFieldsFromDocumentAsync(
目标文件,
字符串documentId,
字符串indexName=null,
字符串typeName=null,
CancellationToken CancellationToken=默认值)
{
var result=result.Ok();
var allNullProperties=GetNullPropertyValueNames(文档);
if(allNullProperties.AnyAndNotNull())
{
var script=allNullProperties.Select(p=>$“ctx.\u source.remove('{p}'))).Aggregate((p1,p2)=>$”{p1};{p2};”;
结果=等待更新ByQueryIdaSync(
文档ID,
剧本
indexName,
字体名,
cancellationToken:cancellationToken);
}
返回结果;
}
私有静态IReadOnlyList GetNullPropertyValueNames(对象文档)
{
var allPublicProperties=document.GetType().GetProperties().ToList();
var allObjects=allPublicProperties.Where(pi=>pi.PropertyType.IsClass).ToList();
var allNames=新列表();
foreach(AllObject中的var propertyInfo)
{
if(propertyInfo.PropertyType==typeof(字符串))
{
var isNullOrEmpty=((字符串)propertyInfo.GetValue(文档)).isNullOrEmpty();
if(isNullOrEmpty)
{
Add(propertyInfo.Name.ToCamelCase());
}
}
else if(propertyInfo.PropertyType.IsClass)
{
if(propertyInfo.GetValue(document.IsNotNull())
{
var namesWithobjectName=GetNullPropertyValueNames(propertyInfo.GetValue(文档))
.Select(p=>$”{propertyInfo.PropertyType.Name.ToCamelCase()}.{p.ToCamelCase()});
allNames.AddRange(namesWithobjectName);
}
}
}
返回所有名称;
}
公共异步任务UpdateByQueryIdAsync(
字符串documentId,
字符串脚本,
字符串indexName=null,
字符串typeName=null,
bool waitForCompletion=false,
CancellationToken CancellationToken=默认值)
{
参数(documentId,nameof(documentId)).NotNull().NotEmpty().NotWhiteSpace();
参数(script,nameof(script)).NotNull().NotEmpty().NotWhiteSpace();
var response=await Client.UpdateByQueryAsync(
u=>u.Query(q=>q.id(i=>i.Values(documentId)))
.冲突(冲突。继续)
.Script(s=>s.Source(Script))
.Refresh()
.WaitForCompletion(WaitForCompletion)
.Index(indexName??DocumentMappings.IndexStrategy