CRUD Operation In MVC Using Elastic Search

Background

We already know about MVC. Let’s explore the Elastic Search search engine and integrate it into 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 that 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 a .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 that 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 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.

 Elastic Search

MVC

Solution

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

Step 1. Create an MVC project and the console application in the solution.

MVC project

Step 2. Add the .Net Elastic client (NEST)

NEST

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nest;
using Elasticsearch.Net;
using Common.Data;

namespace Elastic.DB
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Started creating Database in Elastic search");
            CreateIndex();
            CreateMappings();
            Console.WriteLine("Database created.");
        }

        /// <summary>
        /// 
        /// </summary>
        public static void CreateIndex()
        {
            ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));
            settings.DefaultIndex("employeestore");
            ElasticClient client = new ElasticClient(settings);
            client.DeleteIndex(Indices.Index("employeestore"));
            var indexSettings = client.IndexExists("employeestore");
            if (!indexSettings.Exists)
            {
                var indexName = new IndexName();
                indexName.Name = "employeestore";
                var response = client.CreateIndex(indexName);
            }

            if (indexSettings.Exists)
            {
                Console.WriteLine("Created");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static void CreateMappings()
        {
            ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));
            settings.DefaultIndex("employeestore");
            ElasticClient esClient = new ElasticClient(settings);
            esClient.Map<Employee>(m =>
            {
                var putMappingDescriptor = m.Index(Indices.Index("employeestore")).AutoMap();
                return putMappingDescriptor;
            });
        }
    }
}

Step 3. Go to Solution Explorer. Right-click on the MVC project and set it as a Start-up project.

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

/// <summary>  
///  
/// </summary>  
/// <param name="um"></param>  
/// <returns></returns>  
[HttpPost]  
public async Task<ActionResult> Registration(UserModel um)  
{  
    ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));                
    settings.DefaultIndex("employeestore");  
    ElasticClient esClient = new ElasticClient(settings);  
    Employee emp = new Employee 
    { 
        EmployeeID = um.ID, 
        EmployeeName = um.Name, 
        Address = um.Address 
    };  
    var response = await esClient.IndexAsync<Employee>(emp, i => i  
        .Index("employeestore")  
        .Type(TypeName.From<Employee>())  
        .Id(um.ID)  
        .Refresh(Elasticsearch.Net.Refresh.True));  

    return RedirectToAction("GetUsers");  
}  

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

Get Users

Registration

Details

Please download the attached sample code for complete CRUD operation.


Similar Articles