Working On ElasticSearch Using .NET NEST

What is Elasticsearch?

According to Wikipedia - Elasticsearch is a search engine based on the Lucene library. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents. Elasticsearch is developed in Java and is released as open source under the terms of the Apache License.

ElasticSearch is a Document-Oriented Database, which stores data in JSON format. It stores data in unstructured form. Elasticsearch uses Lucene StandardAnalyzer for indexing, automatic type guessing and more precision. Every feature of Elasticsearch is exposed as a REST API. With the help of API, we can Get, Post, Delete, Search the data.

So Let's follow these steps to configure and use Elasticsearch.

Step 1 

To Install and configure Elasticsearch, we need to Install JRE. You can download it from here.

Step 2 

Once you download and install JRE, you need to download the setup Elasticsearch and install it from below link. Download .MSI file:

https://www.elastic.co/downloads/elasticsearch

Step 3 

Once you install Elasticsearch, check whether Elasticsearch is installed or not by hitting below url in any browser.

http://localhost:9200/

Step 4 

Create a WebSolution or WebAPI to do the operations on Elasticsearch. Add nuget package of NEST for .NET.

Either take it from this link https://www.nuget.org/packages/NEST/ OR Use Install-Package NEST -Version 6.5.0

Now you are ready to work on Elasticsearch through .NET.

Now follow the below steps to proceed further:

Step 5 

Add Namespace in your Controller. This will give you facility to connect with your Elasticsearch instance from your .Net code.

  1. using Nest;  

Here points to note is that "index" is Database and "type" is Table. so you need to create INDEX(Database) first, then you need to create TYPE(Table) so that you can insert data in table in the format of JSON.

Step 6 

Please add the below code to connect and create index, type and insert data in it. I have created a complete API as a sample for your reference. Below code is in working state.
  1. [System.Web.Http.Route("ConnectAndInsertData")]  
  2. [System.Web.Http.HttpPost]  
  3. public HttpResponseMessage ConnectAndInsertData(RawData model) // Here RawData is a object of a Class. you can create a class with few sample properties and can pass in the form of JSON from Postman  
  4. {  
  5.     HttpResponseMessage response = new HttpResponseMessage();  
  6.   
  7.     var jsonResult = "";  
  8.     try  
  9.     {  
  10.         if (model != null)  
  11.         {  
  12.             Uri EsInstance = new Uri("http://localhost:9200");  
  13.             ConnectionSettings EsConfiguration = new ConnectionSettings(EsInstance );  
  14.             ElasticClient EsClient = new ElasticClient(EsConfiguration);  
  15.   
  16.             var settings = new IndexSettings { NumberOfReplicas = 1, NumberOfShards = 2 };  
  17.             var indexConfig = new IndexState  
  18.             {  
  19.                 Settings = settings  
  20.             };  
  21.   
  22.             if (!EsClient.IndexExists("sample").Exists) // I am creating database named "sample". check if exist before creating the new  
  23.             {  
  24.                 EsClient.CreateIndex("sample", c => c  
  25.                 .InitializeUsing(indexConfig)  
  26.                 .Mappings(m => m.Map<RawData>(mp => mp.AutoMap())));  
  27.             }  
  28.   
  29.             var getTableData = EsClient.Count<RawData>(s => s.Index("sample").Type("rawdata")); // This will return Count of records in "rawdata" table  
  30.   
  31.             if (EsClient.IndexExists("sample").Exists)  
  32.             {  
  33.                // Here model is the Object containing the data which we passed to API and want to insert in Table/type  
  34.                 var result = EsClient.Index(model, i => i  
  35.                     .Index("sample")  
  36.                     .Type("rawdata")  
  37.                     .Id(getTableData.Count + 1)  
  38.                     .Refresh(Elasticsearch.Net.Refresh.True)  
  39.                     );  
  40.                 if (Convert.ToString(result.Result) == "Created")  
  41.                 {  
  42.                     jsonResult = JsonConvert.SerializeObject("{\"result\":true\"}");  
  43.                     response = Request.CreateResponse(HttpStatusCode.OK);  
  44.                     response.Content = new StringContent(jsonResult, Encoding.UTF8, "application/json");  
  45.                 }  
  46.             }  
  47.         }  
  48.   
  49.     }  
  50.     catch (Exception ex)  
  51.     {  
  52.         jsonResult = JsonConvert.SerializeObject("{\"result\":false\"}");  
  53.         response = Request.CreateResponse(HttpStatusCode.InternalServerError);  
  54.         response.Content = new StringContent(jsonResult, Encoding.UTF8, "application/json");  
  55.     }  
  56.     if (string.IsNullOrEmpty(jsonResult))  
  57.     {  
  58.         jsonResult = JsonConvert.SerializeObject("{\"result\":false\"}");  
  59.         response = Request.CreateResponse(HttpStatusCode.ExpectationFailed);  
  60.         response.Content = new StringContent(jsonResult, Encoding.UTF8, "application/json");  
  61.     }  
  62.     return response;  
  63. }  

Step 7 

Now, we want to check if the data is inserted or not. For that, we need to fetch data from the table. Here I create a new API for getting data from the table.
 
To get data, we need to connect to the Elasticsearch instance.
  1. [System.Web.Http.Route("GetData")]  
  2.         [System.Web.Http.HttpGet]  
  3.         public HttpResponseMessage GetData()  
  4.         {  
  5.             HttpResponseMessage response;  
  6.            Uri EsInstance = new Uri("http://localhost:9200");  
  7.            ConnectionSettings EsConfiguration = new ConnectionSettings(EsInstance );  
  8.            ElasticClient EsClient = new ElasticClient(EsConfiguration);  
  9.   
  10.             var getTableData = EsClient.Search<RawData>(s => s.Index("sample").Type("rawdata").Size(300000).Take(10000)); // you can get maximum 10000 records at a time  
  11.   
  12.             var jsonResult = JsonConvert.SerializeObject("{\"result\":true\"}");  
  13.             List<RawData> lstData = new List<RawData>();  
  14.   
  15.             foreach (var hit in getTableData.Hits)  
  16.             {                 
  17.                 lstData.Add(hit.Source);  
  18.             }  
  19.             if (lstData != null)  
  20.             {  
  21.                 jsonResult = JsonConvert.SerializeObject(getTableData);  
  22.             }  
  23.             response = Request.CreateResponse(HttpStatusCode.OK);  
  24.             response.Content = new StringContent(jsonResult, Encoding.UTF8, "application/json");  
  25.             return response;  
  26.         }  

So, this way, we can insert and get data in elasticsearch using .NET. This is a very basic example for beginners. I will come up with next blog for deleting data and full fledge search.

-- Happy Coding --


Logiciel Softtech Pvt. Ltd.
We help you transform your business ideas with custom products, migrate from legacy applications.