Linked Questions

Popular Questions

How to update nested objects using Nest Elasticsearch?

Asked by At

I have product index which for simplicity has two fields Id and ProductAttributes as nested object defined as following:

public class ProductType
{
    public Guid Id { get; set; }

    public List<ProductAttribute> ProductAttributes { get; set; }
 }

public class ProductAttribute
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public string Value { get; set; }
}

And the following mapping:

elasticClient.CreateIndex("product", i => i
       .Settings(s => s
                 .NumberOfShards(2)
                 .NumberOfReplicas(0)
                 )
                 .Mappings(m => m
                   .Map<ProductType>(map => map
                         .AutoMap()
                         .Properties(p => p
                          .Nested<ProductAttribute>(n => n
                            .Name(c => c.ProductAttributes)
                            .AutoMap()
                            .Properties(nc => nc
                               .Keyword(t => t
                                   .Name(nn => nn.Name)
                                   )
                              .Keyword(t => t
                                .Name(nn => nn.Value)
                             )
                  )
             )

Now I am trying to update name field inside nested object and I have tried implementing that using scripted update as following:

        var scriptParams = new Dictionary<string, object>
                            {
                                {"name", "new name"}
                            };

        var result = elasticClient.UpdateByQuery<ProductType>(u => u
                              .Script(sn => sn
                                   .Inline(
                                          $"ctx._source.productAttributes= params.name;" 
                                      )
                                  .Params(scriptParams)
                              )
                              .Conflicts(Conflicts.Proceed)
                              .Refresh(true)
                          );

But using the above query I couldn't update the nested object, could you please tell how can I update nested object using _update_by_query api using nest ES?

Related Questions