Elastic Search : Create Index using NEST in .NET

Standard

In order to connect to your elastic search node from .NET application, do the following steps:

  • Download NEST package from Nuget
    PM> Install-Package NEST
  • Define elastic search Node running address
    EsNode = new Uri("http://localhost:9200/");
  • Preapre connection settings and using it create elastic client objectSnippet
    EsConfig = new ConnectionSettings(EsNode);
    EsClient = new ElasticClient(EsConfig);
  • Setup number of replicas and shards for indexSnippet
    var settings = new IndexSettings{NumberOfReplicas = 1, NumberOfShards = 2};
     
    var indexConfig = new IndexState
    {
        Settings = settings
    };
  • Fetch fields of index from POCO using AutoMap api
    EsClient.CreateIndex("employee", c => c
            .InitializeUsing(indexConfig)
            .Mappings(m => m.Map<Employee>(mp => mp.AutoMap())));
  • Make sure index doesnt exist earlier
    !EsClient.IndexExists("employee").Exists
    

C# Snippet

using System;
using System.Collections.Generic;
using System.Linq;
using Nest;
 
namespace ElasticSearchDemo
{
    public class Employee
    {
        public int EmpId { set; get; }
 
        public string Name { set; get; }
 
        public string Department { set; get; }
 
        public int Salary { set; get; }
    }
    class Program
    {
        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);
            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())));
            }
        }
    }
}
Advertisements

7 thoughts on “Elastic Search : Create Index using NEST in .NET

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