通过 NEST 6.5.4 for .NET 中的脚本更新弹性搜索 API

Elastic Search Update API by script in NEST 6.5.4 for .NET

我使用的是 Nest 6.5.4。我无法在索引中的特定文档上使用脚本执行更新。 我尝试了很多方法,但出现语法错误。 我的查询如下。

var clientProvider = new ElasticClientProvider();
var projectModel = new ProjectModel();
 var res = clientProvider.Client.Update<ProjectModel>(projectModel, i => i
                .Index("attachment_index")
                .Type("attachments")
                .Id(projectId)
.Script(script=>script.Source("ctx._source.fileInfo.fileViewCount= ctx._source.fileInfo.fileViewCount + 1"))
                );

正在抛出错误 "Update Descriptor does not have a definition for Id" 在 Kibana

中尝试时,相同的查询正在运行
POST attachment_index/attachments/1/_update
{
  "script": {
    "source":"ctx._source.fileInfo.fileViewCount += 1"
  }
}

我不知道哪里出错了。

UpdateDescriptor<T, TPartial> 上没有 .Id() 方法,因为 id 是更新 API 调用的必需参数,因此此约束是通过构造函数强制执行的。

.Update<T>(...) 的第一个参数是 DocumentPath<T>,可以从中导出索引、类型和 ID 以用于更新 API 调用。如果 ProjectModel CLR POCO 有一个 Id 属性 和一个值,这将用于调用的 Id。例如

public class ProjectModel 
{
    public int Id { get; set; }
}

var client = new ElasticClient();

var projectModel = new ProjectModel { Id = 1 };

var updateResponse = client.Update<ProjectModel>(projectModel, i => i
    .Index("attachment_index")
    .Type("attachments")
    .Script(script => script
        .Source("ctx._source.fileInfo.fileViewCount= ctx._source.fileInfo.fileViewCount + 1"))
);

结果是

POST http://localhost:9200/attachment_index/attachments/1/_update
{
  "script": {
    "source": "ctx._source.fileInfo.fileViewCount= ctx._source.fileInfo.fileViewCount + 1"
  }
}

如果要显式指定Id,可以传值给DocumentPath<T>

var updateResponse = client.Update<ProjectModel>(1, i => i
    .Index("attachment_index")
    .Type("attachments")
    .Script(script => script
        .Source("ctx._source.fileInfo.fileViewCount= ctx._source.fileInfo.fileViewCount + 1"))
);
client.UpdateAsync<ProjectModel, object>(
                new DocumentPath<ProjectModel>(id),
                u => u
                    .Index(ConfigurationManager.AppSettings.Get("indexname"))
                    .Type(ConfigurationManager.AppSettings.Get("indextype"))
                    .Doc(ProjectModel)
                    .DocAsUpsert()
                    .Refresh(Elasticsearch.Net.Refresh.True));

这会起作用,如果您仍然遇到任何问题,请告诉我。