Home > OS >  How to set field to null in Elasticsearch using C# NEST script?
How to set field to null in Elasticsearch using C# NEST script?

Time:10-29

For example we have following document in elastic:

{
  "name": "Bob",
  "age": "22",
  "phrase": "ohohoho",
  "date": "2022-10-20T00:00:00Z"
}

string phrase ;

DateTime? date;

Then we want put following:

{
  "name": "not Bob",
  "age": "22",
  "phrase": null,
  "date": null
}

in c#:

 var updateRequest = new UpdateRequest<T, T>(entity)
            {
                ScriptedUpsert = true,
                Script = new InlineScript(
                    $"if (someCondition) {{ctx._source.putAll(params.entity);}} else {{ctx.op = \"noop\";}}")
                {
                    Lang = "painless",
                    Params = new Dictionary<string, object>() { { "entity", entity } },
                },
                Upsert = Activator.CreateInstance<T>()
            }; 

but in the end it will not update phrase and date. It makes following request:


POST /myIndex/_update/b90278fd-1a66-40bf-b775-d076122c6c02
{
    "script": {
        "source": ""if (someCondition) {{ctx._source.putAll(params.entity);}} else {{ctx.op = \"noop\";}}"",
        "lang": "painless",
        "params": { 
          "entity": {
               "name": "",
               "age": 22
            }
        }
    },
    "upsert": {
        "age": 0
    }
}

Idk why but it skips all fields with null. How to update nullable fields to null?

CodePudding user response:

NEST does not support sending null values by default.

You can have a check in script such that if a value is not passed then you can remove it from document.

var updateRequest = new UpdateRequest<T, T(entity)
            {
                ScriptedUpsert = true,
                Script = new InlineScript($"if (params.entity.phrase==null)ctx._source.remove('phrase');")
                {
                    Lang = "painless",
                    Params = new Dictionary<string, object>() { { "entity", entity } },
                },
                Upsert = Activator.CreateInstance<T>()
            };

You can check for more details here

  • Related