Getting Started With ElasticSearch

Introduction

Elasticsearch is a scalable open-source full-text searching tool and also analytics engine. It is used to save, search, and analyze huge data faster and also in real time.

First of all, Elasticsearch is Rest Service. We can communicate with any Elasticsearch Service, using four verbs or functions.

  1. Get
  2. Post
  3. Put
  4. Delete

We all know that

  • Get is used to search. 
  • Post is used to add or insert. 
  • Put is used for updation. 
  • Delete is used to remove. 
As Elasticsearch is some kind of NoSQL like MongoDB, we can store the data persistently in the form of JSON.

Let's understand how to use Elasticsearch step by step.
  • Download and development environment.
  • How to create Rest Services, using Elasticsearch.
  • Configuration part.
  • How to test Rest Services developed in Elasticsearch.

Also, we will understand how we can consume this rest API with any other Application developed in C#.

Download and Environment Setup

First, download Elasticsearch from this URL.

Unzip to location e.g. E:\elasticsearch

Go to the file location from command prompt e.g. E:\elasticsearch\elasticsearch-2.4.0\bin and start Elasticsearch.(E:\elasticsearch\elasticsearch-2.4.0\bin> Elasticsearch and press enter),

Environment

Now, open the Browser and open localhost:9200.

Environment
If you are receiving the above JSON as a response, then Elasticsearch Server starts properly.

Now, we will start settng up the development environment on the local machine. It’s too easy as you have to just download the plugin for Chrome Sense. After successful installation is done, you will get the icon, given below, for sense- 

Environment

Select that icon to start sense

Environment

Start Development,

Insert data - First Enter below json,

  1. POST /test/test/  
  2. {  
  3.    "color":"blue",  
  4.    "price":30  
  5. }  
Press Green button to execute.

Environment

You will get an output.

Environment
  1. {  
  2.     "_index""test",  
  3.     "_type""test",  
  4.     "_id""AVeAkPROSRYbKbs9pYch",  
  5.     "_version": 1,  
  6.     "created"true  
  7. }  
To understand the terms like index and type in details, please go through the link, given below, from Elasticsearch Website.

Select or search data

GET /test/test/_search

Searching conditional data

This Service will give you first value.

GET /test/test/1

This will return the records, which matches the condition mentioned in the query.
  1. GET /test/test/_search  
  2. {    
  3.    "size": 3,  
  4.    "query": { "match": { "color""red" } }  
  5. }  
Aggregation

This is used, when we need sum, min, max or any other arithmetic operation results.
  1. "aggregations" : {  
  2. "group_by_state" : {  
elasticsearch-gui

This gives you a user interface, where you can get detailed dashboard information about Elasticsearch with the list of indexes, you can also remove size as well.

Use the command, given below, from command prompt to add or install on your machine bin/plugin install jettro/elasticsearch-gui

Next, you can browse to your Elasticsearch instance - http://localhost:9200/_plugin/gui/index.html

html

Elasticsearch integrate with C#

Here, we will create one sample Application in C#, where we can call Elasticsearch Services through Elasticsearch client and use Elasticsearch as a database.

For this sample, I am using Unit Test project.

Create unit test project UnitTestElasticsearchSample, create test class ElastisearchTest.

Right click on the project from Solution Explorer.

html

Select Manage NuGet Packages.

html

.NET client is created to consume Elasticsearch Services. There are couple of more .NET clients, which are also available and one can use them as well.

You can select next and install. After successful installation, you will get the screenshot, as shown below-

html

In Solution Explorer, expand the references and you will get "get added".

html

Now, we will start the actual development.

Create one sample model City.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace UnitTestElasticsearchSample.model {  
  8.     public class City {  
  9.         public int ID {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         public int Name {  
  14.             get;  
  15.             set;  
  16.         }  
  17.         public int State {  
  18.             get;  
  19.             set;  
  20.         }  
  21.         public int Country {  
  22.             get;  
  23.             set;  
  24.         }  
  25.         public int Population {  
  26.             get;  
  27.             set;  
  28.         }  
  29.     }  
  30. }  
  31.   
  32. using Nest;  
  33. using System;  
  34. using System.Collections.Generic;  
  35. using System.Linq;  
  36. using UnitTestElasticsearchSample.model;  
  37.   
  38. namespace UnitTestElasticsearchSample {  
  39.     public class Elasticsearch {  
  40.         ElasticClient client = null;  
  41.         public Elasticsearch() {  
  42.             var uri = new Uri("http://localhost:9200");  
  43.             var settings = new ConnectionSettings(uri);  
  44.             client = new ElasticClient(settings);  
  45.             settings.DefaultIndex("city");  
  46.         }  
  47.         public List < City > GetResult() {  
  48.             if (client.IndexExists("city").Exists) {  
  49.                 var response = client.Search < City > ();  
  50.                 return response.Documents.ToList();  
  51.             }  
  52.             return null;  
  53.         }  
  54.   
  55.         public List < City > GetResult(string condition) {  
  56.             if (client.IndexExists("city").Exists) {  
  57.                 var query = condition;  
  58.   
  59.                 return client.SearchAsync < City > (s => s  
  60.                     .From(0)  
  61.                     .Take(10)  
  62.                     .Query(qry => qry  
  63.                         .Bool(b => b  
  64.                             .Must(m => m  
  65.                                 .QueryString(qs => qs  
  66.                                     .DefaultField("_all")  
  67.                                     .Query(query)))))).Result.Documents.ToList();  
  68.             }  
  69.             return null;  
  70.         }  
  71.   
  72.         public void AddNewIndex(City model) {  
  73.             client.IndexAsync < City > (model, null);  
  74.         }  
  75.     }  
  76. }  
Write the test case to insert the records in Elasticsearch [TestMethod].
  1. public void AddNewIndexTest()  
  2. {  
  3. Elasticsearch objSearch = new Elasticsearch();  
  4.   
  5. objSearch.AddNewIndex(new model.City(1, "delhi", "delhi", "India", "9.879 million"));  
  6. objSearch.AddNewIndex(new model.City(2, "mumbai", "Maharashtra", "India", "11.98 million"));  
  7. objSearch.AddNewIndex(new model.City(3, "chenai", "Tamil Nadu", "India", "4.334 million"));  
  8. objSearch.AddNewIndex(new model.City(4, "kolkata", "W. Bengal", "India", "4.573 million"));  
  9. objSearch.AddNewIndex(new model.City(4, "Banglore", "Karnataka", "India", "4.302 million"));  
  10. objSearch.AddNewIndex(new model.City(4, "Pune", "Maharashtra", "India", "2.538 million"));  
  11. }  
Execute this testcase

Thus, all these records are added one by one.

[TestMethod]
  1. public void GetResultTest()  
  2. {  
  3.    Elasticsearch objSearch = new Elasticsearch();  
  4.    var result = objSearch.GetResult();  
  5.   
  6.    Assert.IsTrue(result.FirstOrDefault<model.City>(x => x.Name == "delhi") != null);  
  7.    Assert.IsTrue(result.FirstOrDefault<model.City>(x => x.Name == "mumbai") != null);  
  8.    Assert.IsTrue(result.FirstOrDefault<model.City>(x => x.Name == "chenai") != null);  
  9. }  
This way, one can add more functionality to interact with Elasticsearch and add test cases as well. Please find the attached sample project for reference. If you are facing any issue, please contact. Thanks for reading.

Keep coding.