<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

Elasticsearch made easy with .Net

Rahul More Apr 21, 2018

.NET Elasticsearch Json

Let me put this in very simple words. Elastic Search is a database which stores the data in the document format (JSON) and facilitates a speedy search. In technical terms one can say it is a "full text search" on a database that stores the data in document format (JSON) which is indexed and very useful for doing the full text search queries. Elastic Search is a search engine based on "Lucene".

Elastic Search Data can be distributed in a number of shards which can have multiple replicas.

Elastic Search is Java Friendly as it is developed in Java, but Microsoft users don’t have to fret as they can use NEST Nugget Package.

How to install Elastic Search ?

Google it! Just kidding!

  • Go to: https://www.elastic.co/downloads/elasticsearch and download the .zip file.
  • Once downloaded, extract the zip file which will give u following listing:
    rahul figure1
  • In the bin folder execute "elasticsearch.bat". This will start running the elastic search.

    Note : Please make sure that you have Java installed on the machine and all the environment paths are set accordingly.
  • Copy paste the following url "http://localhost:9200/" in the browser. If this URL is working then you are all set to go.

Now that was simple, wasn’t it?

How can it be used with .Net ?

There are nugget packages available for installing NEST , please find the image below or follow the link

rahul image 2

This will install the Nugget package in the application. 

Get Ready for some coding:

Before starting, make sure to have this in the using section:

"using Nest;"

To connect the Using .Net

public class fileModel

public class fileModel
{
public string fileName { get; set; }
public string fileContents { get; set; }

public double? searchScore { get; set; }
}

#region -- Connectivity --

Uri Node;
ConnectionSettings settings;
ElasticClient client;
Node = new Uri("http://127.0.0.1:9200/");
settings = new ConnectionSettings(Node);
client = new ElasticClient(settings);

#endregion

Once connected to node the next part is to create the index

#region -- Check Duplication and Create Index --

string indexName = "Index1";

 var existingIndex = client.IndexExists(Indices.AllIndices, eI => eI.Index(indexName));

There are 2 ways of creating the Indexes

var createIndexResponse = client.CreateIndex(indexName, c => c
.Settings(s => s
.NumberOfShards(1)
.NumberOfReplicas(0)

)
.Mappings(cIR => cIR
.Map<fileModel>(mapDocument => mapDocument
.IndexField(x => x.Enabled())
)

)
.Mappings(mu => mu.Map<[Model]>(x => x.AutoMap()))
);
----------------------------------OR -----------------------------------------

var createIndexResponse = client.CreateIndex(indexName, c => c
.Mappings(m => m
.Map<pdfFileModel>(mm => mm
.Properties(p => p
.Text(t => t
.Name(n => n.fileContents)
.Analyzer("standard")
.IndexOptions(IndexOptions.Offsets)
.Index(true)
)
)
)
)
.Settings(s => s
.NumberOfShards(1)
.NumberOfReplicas(0)
)
);

#endregion

Now we have connected to Elastic Search and created the index. Now it’s time to add some data to the Elastic Search. 

"This may be tricky. So in the example we have considered fileName and fileContent which will be added on file upload control which will be so that "fileModel" will already have contents"

#region -- Add Data --
bool isUpdateAvaiable = false;
dynamic resultBlobUpdate = null;
if (!string.IsNullOrEmpty(objfileModel.fileName))
{
var result = client.Index(objfileModel, x => x.Index(indexName));
client.Refresh(indexName);
}
#endregion

This is as simple as it gets.

Now to check if the data is actually added in Node and Index, use Post Man with GET with this url,

http://localhost:9200/[IndexName]/[ModelName]/_search

This API will return all the contents added in the Model which is created.

or 

Install the "head-master" utility which is a web based application that shows all the detailed information about nodes and its contents.

It's time to do some searching.

Search Text on all the Fields

var resp1 = client.Search<dynamic>(s => s
.AllTypes().Index(IndexName)
.Query(qry => qry
.Bool(b => b
.Must(m => m
.QueryString(qs => qs
.DefaultField("_all")
.Query("[Search Text String]"))))));

-----------------------------------------------------------------------------------------

USING Field Query using "Match"

var searchResponse = client2.Search<dynamic>(s => s
.Query(q => q
.Match(m => m
.Field("[FieldName]")
.Query("12345*")
.FuzzyRewrite(MultiTermQueryRewrite.ScoringBoolean)
)
)
.Index(IndexName)
);

-----------------------------------------------------------------------------------------

USING Filter and SubQuery

var searchResults1 = client2.Search<dynamic>(s => s

.Query(q => q
.Bool(b => b
.Filter(
subQuery => subQuery.Term(new Field("[FieldName]"), "*1234*")))
)
.Index("2-1-1"))
;

Let’s move to some Complex Query Making

Making Or Conditions

dynamic orcondition |= Query<dynamic>.QueryString(x => x.Fields(columnValue).Query(itemIteratorValue));

making And Conditions

dynamic andcondition &= Query<dynamic>.QueryString(x => x.Fields(columnValue).Query(itemIteratorValue));

Making Use of Conditions

resp = client.Search<dynamic>(s => s
.Index(indexName)
.AllTypes()
.From(0)
.Take(10000)
.Query(
x =>
{
dynamic formedQuery = null;

if (isOrApplied)
formedQuery = orcondition;
else
formedQuery = andcondition;

return formedQuery;

}
));

Happy Elastic searching!!!

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.