In Dot Net
0
29 views

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

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

Steps 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 file menu goto new and click on the project.

Click on project menu open a popup and 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.

Step 2

Right-click on the project from solution explorer. 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 and 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 and 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 and 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 global variable given below:

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

Step 8

Double click on 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 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 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 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 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:

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 you to 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!

Recommended Posts
We Are Here to Help!
Name:
Phone:
Email:
Country:
Message:
 

Start typing and press Enter to search