【问题标题】:Elastic Search Update API by script in NEST 6.5.4 for .NETNEST 6.5.4 for .NET 中脚本的弹性搜索更新 API
【发布时间】:2019-09-06 18:49:31
【问题描述】:

我使用的是 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"))
                );

它抛出错误“更新描述符没有 Id 的定义” 在 Kibana 中尝试使用相同的查询

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

我不知道哪里出错了。

【问题讨论】:

    标签: elasticsearch nest elastic-stack


    【解决方案1】:

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

    .Update&lt;T&gt;(...) 的第一个参数是 DocumentPath&lt;T&gt;,可以从中派生索引、类型和 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&lt;T&gt;的值

    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"))
    );
    

    【讨论】:

      【解决方案2】:
      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));
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-04
        • 2016-11-22
        • 2020-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多