Search code examples
c#elasticsearchnestelasticsearch-5

Elasticsearch NEST update by script


I'm trying to update some fields by script. In Postman I'm sending the following request:

https://search.test.com/items_example/item/en_01_2/_update

the request's body:

{
  "script": {
    "inline": "ctx._source.Title = params.Title; ctx._source.Desc = params.Desc",
    "params": {
        "Title": "New Title",
        "Desc": "New Desc"
    }  
  }
}

But I have no idea how I can send this request using NEST. Can someone please help me? Elasticsearch 5.4.1 version, NEST 5.6.1


Solution

  • Update it with your index settings & query

    var elasticClient = new ElasticClient(settings);
    var scriptParams = new Dictionary<string, object>
    {
        {"Title", "New Title"},
        {"Desc", "New Desc"}
    };
    
    var response = elasticClient
        .UpdateByQuery<dynamic>(q => q.Query(rq => rq.Term(....))
        .Script(script =>
            script.Inline(
                $"ctx._source.Title = params.Title;" +
                $"ctx._source.Desc  = params.Desc ;"
            )
        .Params(scriptParams));
    

    Edit: If you're looking for just Update, just change the syntax to

    var response = elasticClient.Update<dynamic>(
        "items_example/item/en_01_2" //This is your document path
        , request => request.Script(
            script =>
                script.Inline(
                        $"ctx._source.Title = params.Title;" +
                        $"ctx._source.Desc  = params.Desc ;"
                    )
                    .Params(scriptParams)));