ELASTIC SEARCH : UPDATE DOCUMENT Adding New Field USING NEST IN .NET

Standard

For connecting with elastic nodes read this: CREATE INDEX USING NEST IN .NET

For inserting documents read this: INSERT DOCUMENTS IN INDEX USING NEST IN .NET

In order to update specific document by adding new fields in document use UPDATE API with document path and index reference as parameter. Please note if type of document has been customized by you during creating index, explicitly mention that type with index for instance (you need to do this if you have not set DefaultIndex API with connection setting object )

public static object UpdateDocumentWithNewField()
        {
            var response = EsClient.Update(DocumentPath<object>
                .Id(3),
                u => u
                    .Index("employee")
                    .Type("myEmployee")
                    .DocAsUpsert(true)
                    .Doc(new { EmpId = 3, Name = "John_up", Department = "IT", Salary = 85000, Country = "USA" }));
            return response;
        }

C# Snippet

using System;
using Nest;
 
namespace ElasticSearchDemo
{
    class ProgramDemo
    {
        public static Uri EsNode;
        public static ConnectionSettings EsConfig;
        public static ElasticClient EsClient;
        static void Main(string[] args)
        {
            EsNode = new Uri("http://localhost:9200/");
            EsConfig = new ConnectionSettings(EsNode).DefaultIndex("employee");
            EsClient = new ElasticClient(EsConfig);
 
            var settings = new IndexSettings { NumberOfReplicas = 1, NumberOfShards = 2 };
 
            var indexConfig = new IndexState
            {
                Settings = settings
            };
 
            if (!EsClient.IndexExists("employee").Exists)
            {
                EsClient.CreateIndex("employee", c => c
                    .InitializeUsing(indexConfig)
                    .Mappings(m => m.Map<Employee>(mp => mp.AutoMap()))
                );
            }
 
            UpdateDocumentWithNewField();
        }
 
        public static object UpdateDocumentWithNewField()
        {
            var response = EsClient.Update(DocumentPath<object>
                .Id(3),
                u => u
                    .Index("employee")
                    .Type("myEmployee")
                    .DocAsUpsert(true)
                    .Doc(new { EmpId = 3, Name = "John_up", Department = "IT", Salary = 85000, Country = "USA" }));
            return response;
        }
    }
 
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s