CRUD Operation In MVC Using Elastic Search

Background

We already know about MVC. Let’s explore the Elastic Search search engine and integrate it in an ASP.NET MVC application.

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

Elastic search uses standard RESTful APIs and JSON. It’s a NoSQL. Elastic Search contains multiple indices which contain multiple types.

An index is like a ‘database’ in a relational database. It has a mapping which defines multiple types.

SQL Server => Databases => Tables => Columns/Rows
Elastic search => Indices => Types => Documents with Properties

These types hold multiple Documents (rows), and each document has Properties or Fields (columns).

For more information about Elastic Search, I would suggest visiting the official website of it.

More about how to work with .NET

To connect Elastic Search using C#, MVC, Web API, or ASP.NET Core, we use .NET Elastic client, i.e., NEST.

In the given example, I have created 2 projects under the same solution,

  1. DBSetUp
    It is a console application which will create your Index (Database) and Type (table) in the Elastic Search by using a common library.

  2. MVC project (Web application)
    To perform the crud operation in Elastic search, the application is created by using the common library.

NEST package should be added to both the projects.

While working with Elastic Search, please ensure that Elastic Search is installed on your system and running properly.  Please have a look at the below screen as the Elastic Search Engine is running.


CRUD operation in MVC

CRUD operation in MVC
Solution

Perform the following steps to secure the Customer PII data using CLE.

Step 1

Create MVC project and the console application in the solution. 

CRUD operation in MVC
Step 2

Add the .Net Elastic client (NEST)

CRUD operation in MVC

Use the below code to create the Index and Type in Elastic search.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Nest;  
  7. using Elasticsearch.Net;  
  8. using Common.Data;  
  9.   
  10. namespace Elastic.DB  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             Console.WriteLine("Started creating Database in Elastic search");  
  17.             CreateIndex();  
  18.             CreateMappings();  
  19.             Console.WriteLine("Database created.");   
  20.         }  
  21.   
  22.         /// <summary>  
  23.         ///   
  24.         /// </summary>  
  25.        public static void CreateIndex()  
  26.         {  
  27.             ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));  
  28.             settings.DefaultIndex("employeestore");  
  29.             ElasticClient client = new ElasticClient(settings);  
  30.             client.DeleteIndex(Indices.Index("employeestore"));  
  31.             var indexSettings = client.IndexExists("employeestore");  
  32.             if(!indexSettings.Exists)  
  33.             {  
  34.                 var indexName = new IndexName();  
  35.                 indexName.Name = "employeestore";  
  36.                 var response = client.CreateIndex(indexName);  
  37.             }  
  38.   
  39.             if(indexSettings.Exists)  
  40.             {  
  41.                 Console.WriteLine("Created");  
  42.             }  
  43.   
  44.         }  
  45.   
  46.         /// <summary>  
  47.         ///   
  48.         /// </summary>  
  49.         public static void CreateMappings()  
  50.         {  
  51.             ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));  
  52.             settings.DefaultIndex("employeestore");  
  53.             ElasticClient esClient = new ElasticClient(settings);  
  54.             esClient.Map<Employee>(m =>  
  55.             {  
  56.                 var putMappingDescriptor = m.Index(Indices.Index("employeestore")).AutoMap();  
  57.                 return putMappingDescriptor;  
  58.             });  
  59.         }  
  60.          
  61.     }  
  62. }  

Step 3

Go to solution explorer. Right click on MVC project and set as a Start-up project.

Add the UserController and design your View. Below is the code snippet you can use to add the user.

  1. /// <summary>  
  2.      ///   
  3.      /// </summary>  
  4.      /// <param name="um"></param>  
  5.      /// <returns></returns>  
  6.      [HttpPost]  
  7.      public async Task<ActionResult> Registration(UserModel um)  
  8.      {  
  9.          ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));            
  10.   
  11.          settings.DefaultIndex("employeestore");  
  12.          ElasticClient esClient = new ElasticClient(settings);  
  13.          Employee emp = new Employee { EmployeeID = um.ID, EmployeeName = um.Name,Address=um.Address };  
  14.          var response = await esClient.IndexAsync<Employee>(emp, i => i  
  15.                                            .Index("employeestore")  
  16.                                            .Type(TypeName.From<Employee>())  
  17.                                            .Id(um.ID)  
  18.                                            .Refresh(Elasticsearch.Net.Refresh.True));  
  19.   
  20.   
  21.          return RedirectToAction("GetUsers");  
  22.      }  

You can design your View in your way. Please refer the below screen which I have designed for User Management.

CRUD operation in MVC
CRUD operation in MVC
CRUD operation in MVC
Please download the attached sample code for complete CRUD operation.


Similar Articles