Search code examples
elasticsearchnestelastic-stack

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


I am using Nest 6.5.4. I am not able to perform Update with script on a particular document in an index. I have tried many ways but I am getting a syntax error. My query is as follows.

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

It is throwing an error "Update Descriptor does not have a definition for Id" The same query is working when tried in Kibana

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

I dont know where I am getting error.


Solution

  • There is no .Id() method on UpdateDescriptor<T, TPartial> because an id is a required parameter for an Update API call, so this constraint is enforced through the constructors.

    The first parameter to .Update<T>(...) is a DocumentPath<T> from which an index, type and id can be derived for the update API call. If the ProjectModel CLR POCO has an Id property with a value, this will be used for Id of the call. For example

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

    which results in

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

    If you want to explicitly specify the Id, you can pass the value for 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"))
    );