How To Create CRUD Operations with ElasticSearch in c#
Print Friendly, PDF & Email

This article is mainly focused on newcomers or the ones who are keen on learning the use of ElasticSearch in their Dot Net program.

Most of you must be aware of the term ElasticSearch and its proper illustration. However, when it comes to using this technology along with CRUD Operations, as well as in C#, then it becomes a bit technical and inquisitive. In case you are interested in grasping this knowledge, let’s get started.

Steps to Create CRUD Operations with ElasticSearch in C#

Below are all steps needed to create CRUD operations with ElasticSearch in C#.

Step 1

Here, I am going to create one sample application in c#.
Open visual studio, click on the file menu, go to new, and click on the project.

Open visual studio, click on the file menu, go to new, and click on the project

Click on the project menu, open a popup, select the visual C# tab, and select the windows forms application.

Click on the project menu, open a popup, select the visual C# tab, and select the windows forms application

Write the project name as your choice.

You can see the screenshot below to design a form.

Designing a form

Step 2

Right-click on the project from solution explorer. Add a class and provide the class name ConnectionToES.

Add a class and provide the class name ConnectionToES

Write the following code in ConnectionToES class to create the connection of elastic search:

class ConnectionToES
{

public static ElasticClient EsClient()
{
ConnectionSettings connectionSettings;
ElasticClient elasticClient; 
connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200/"));
elasticClient = new ElasticClient(connectionSettings);
return elasticClient;
}
}

Step 3

Right-click on the project from solution explorer add one more class and provide the class name Employee and write the below code:

class Employee
{
public string name { get; set; }
public string address { get; set; }
public string MobileNo { get; set; }
 
}

Step 4

Right-click on the project from solution explorer, add one more class, provide the class name DocumentAttributes, and write the below code:

public class DocumentAttributes
{
public string name { get; set; }
public string address { get; set; }
public string MobileNo { get; set; }
}

Step 5

Right-click on the project from solution explorer, add one more class, provide the class name UpdateDocumentAttributes, and write the below code:

public class UpdateDocumentAttributes
{
public string name { get; set; }
public string address { get; set; }
public string MobileNo { get; set; }
}

Step 6

Right-click on the project from solution explorer, add one more class provide the class name CRUDEmployee, and write the below code.

public class CRUDEmployee
{
public static DataTable getAllDocument()
{
DataTable dataTable = new DataTable("Employee");
dataTable.Columns.Add("ID", typeof(string));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("address", typeof(string));
dataTable.Columns.Add("MobileNo", typeof(string));

var res = ConnectionToES.EsClient().Search<Employee>(s => s
.Index("employee")
.Type("doc")
.From(0)
.Size(1000)
.Query(q => q.MatchAll()));



foreach (var hit in res.Hits)
{
dataTable.Rows.Add(hit.Id.ToString(), Convert.ToString(hit.Source.name), Convert.ToString(hit.Source.address), Convert.ToString(hit.Source.MobileNo));
}

return dataTable;
}

public static bool insertEmployee(int ID, string Name, string Address, string MobileNO)
{
bool status;
var myJson = new
{
name = Name,
address = Address,
MobileNo = MobileNO
};

var response = ConnectionToES.EsClient().Index(myJson, i => i.Index("employee").Type("doc").Id(ID).Refresh());

if (response.IsValid)
{
status = true;
}
else
{
status = false;
}

return status;
}

public static bool updateEmployee(int ID, string Name, string Address, string MobileNO)
{
bool status;

var response = ConnectionToES.EsClient().Update<DocumentAttributes, UpdateDocumentAttributes>(ID, d => d
.Index("employee")
.Type("doc")
.Doc(new UpdateDocumentAttributes
{
name = Name,
address = Address,
MobileNo = MobileNO
}));



if (response.IsValid)
{
status = true;
}
else
{
status = false;
}

return status;
}

public static bool deleteEmployee(string searchID)
{
bool status;

var response = ConnectionToES.EsClient().Delete<DocumentAttributes>(searchID, d => d
.Index("employee")
.Type("doc"));

if (response.IsValid)
{
status = true;
}
else
{
status = false;
}

return status;
}

public static Tuple<string, string, string, string> GetEmployeeByID(string ID)
{
string id = "";
string name = "";
string address = "";
string MobileNo = "";

var response = ConnectionToES.EsClient().Search<DocumentAttributes>(s => s
.Index("employee")
.Type("doc")
.Query(q => q.Term(t => t.Field("_id").Value(ID)))); //Search based on employeeID



foreach (var hit in response.Hits)
{
id = hit.Id.ToString();
name = Convert.ToString(hit.Source.name);
address = Convert.ToString(hit.Source.address);
MobileNo = Convert.ToString(hit.Source.MobileNo);
}

return Tuple.Create(id, name, address, MobileNo);
}

public static string ValidateEmployee(string name, string address, string MobileNo)
{
string msg = string.Empty;
long ID = 0;
if (String.IsNullOrWhiteSpace(name))
{
msg = "Please enter employee name. \n";
}
bool convert = long.TryParse(name, out ID);
if (convert == true)
{
msg = msg + "Please enter a valid employee name.\n";
}
if (String.IsNullOrWhiteSpace(address))
{
msg = msg + "Please enter employee address.\n";
}
bool convert1 = long.TryParse(address, out ID);
if (convert1 == true)
{
msg = msg + "Please enter a valid employee address.\n";
}

Regex validator = new Regex("(3|4|5|6|7|8|9){1}[0-9]{9}");
string match = validator.Match(MobileNo).Value.ToString();
if (match.Length == 10)
{

}
else
{
msg = msg + "Please enter a valid mobile no.";
}

return msg;

}

}

Step 7

In form1.cs you declare the global variable given below:

string documentID = "";
int id;
string name = "";
string address = "";
string MobileNo = "";

Step 8

Double click on the GetData button and write the below code:

private void btnGetEmployee_Click(object sender, EventArgs e)
{

DataTable dt = CRUDEmployee.getAllDocument();
dataGridView1.DataSource = dt;
}

Step 9

Double click on the Insert button and write the below code:

private void btnInsert_Click(object sender, EventArgs e)
{
bool status = false;

long ID = 0;
bool convert = long.TryParse(txtID.Text, out ID);
if (convert == true)
{

string msg = CRUDEmployee.ValidateEmployee(txtName.Text, txtAddress.Text, txtMobileNo.Text);

if (msg == string.Empty)
{
id = Convert.ToInt32(txtID.Text);
name = txtName.Text;
address = txtAddress.Text;
MobileNo = txtMobileNo.Text;

status = CRUDEmployee.insertEmployee(id, name, address, MobileNo);

if (status == true)
{
MessageBox.Show("Document Inserted/ Indexed Successfully");
btnGetEmployee_Click(sender, e);
txtID.Text = "";
txtName.Text = "";
txtAddress.Text = "";
txtMobileNo.Text = "";
}
else
{
MessageBox.Show("Error! Occured During Document Insert/ Index!");
}
}
else
{
MessageBox.Show(msg);
}



}
else
{
MessageBox.Show("Please enter a valid employee ID.");
}

}

Step 10

Double click on the Update button and write the below code:

private void btnUpdate_Click(object sender, EventArgs e)
{
bool status;
long ID = 0;
bool convert = long.TryParse(txtID.Text, out ID);
if (convert == true)
{
id = Convert.ToInt32(txtID.Text);
name = txtName.Text;
address = txtAddress.Text;
MobileNo = txtMobileNo.Text;

status = CRUDEmployee.updateEmployee(id, name, address, MobileNo);

if (status == true)
{
MessageBox.Show("Document Updated Successfully");
btnGetEmployee_Click(sender, e);
txtID.Text = "";
txtName.Text = "";
txtAddress.Text = "";
txtMobileNo.Text = "";
}
else
{
MessageBox.Show("Error! Occured During Document Update!");
}
}
else
{
MessageBox.Show("Please enter a valid employee ID.");
}



}

Step 11

Double click on the Delete button and write the below code:

private void btnDelete_Click(object sender, EventArgs e)
{
bool status;
documentID = txtID.Text;
long ID = 0;
bool convert = long.TryParse(documentID, out ID);
if (convert == true)
{
status = CRUDEmployee.deleteEmployee(ID.ToString());

if (status == true)
{
MessageBox.Show("Document Deleted Successfully");
btnGetEmployee_Click(sender, e);
txtID.Text = "";
}
else
{
MessageBox.Show("Error Occured During Document Delete!");
}
}
else
{
MessageBox.Show("Please enter a employee id.");
}



}

Step 12

Double click on the Search button and write the below code:

private void btnSearch_Click(object sender, EventArgs e)
{

long ID = 0;
bool status = long.TryParse(txtSearch.Text, out ID);
if (status == true)
{
var empItem = CRUDEmployee.GetEmployeeByID(ID.ToString());
txtID.Text = empItem.Item1;
txtName.Text = empItem.Item2;
txtAddress.Text = empItem.Item3;
txtMobileNo.Text = empItem.Item4;

}
else
{
MessageBox.Show("Please enter a valid employee ID.");
}
}

At last, I am going to open my project solution file. You can see it below:

The output of the whole exercise.

Concluding Words

ElasticSearch is a flexible RestFul and NoSQL database or search engine that can index text objects easily and dynamically. If you can programmatically index content, then this solution is almost boundless in terms of its ability to generate search results that your applications or users can utilize.

In this article, I recommend some basic concepts of how to use ElasticSearch. The way you interact with the CRUD through your application is entirely up to you. ElasticSearch is simply a RestFul and NoSQL database or search engine that you can quickly access the data from the database. I hope you enjoyed reading this article!

LEAVE A REPLY

Please enter your comment!
Please enter your name here