Breaking

Search Here

12 May 2020

ELASTIC SEARCH CREATE INDEX USING NEST IN .NET







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())));
            }
        }
    }
}

No comments:

Post a Comment

Hello all, if you have any doubt feel free comment

Comments