This example for you to share the elasticsearch.net use of tutorials for your reference, the specific contents are as follows
First go to the official website download Elasticsearch 2.3.4 installation package, after decompression, in the cmd command line into the installation directory, and then into the bin directory, run Elasticsearch.bat command.
Elasticsearch Plug-in Elasticsearch-head installation:
Execute command in bin directory Plugin-install Mobz/elasticsearch-head
Then start. NET programming and build console applications
The Program.cs code is as follows:
Class program
{
static void Main (string[] args)
{
Console.WriteLine ("*program started:" + DateTime.Now);
var business = new Business ();
var swread = new Stopwatch ();
Swread.start ();
Business. Addtodb ();//sqlserver database Add Data
//swread.stop ();
Console.WriteLine ("DB Write Time:" + swread.elapsedmilliseconds);
Swread.reset ();
Swread.start ();
Business. Addtoelasticindex ();
Swread.stop ();
Console.WriteLine ("ES Write Time:" + swread.elapsedmilliseconds);
var sw = new Stopwatch ();
Sw. Start ();
var Personsfromdb = business. Getfromdb ();
Sw. Stop ();
Console.WriteLine ("DB Read time:" + SW.) Elapsedmilliseconds);
Sw. Reset ();
Sw. Start ();
var personsfromes = business. Getfromes ();
Sw. Stop ();
Console.WriteLine ("ES Read time:" + SW.) Elapsedmilliseconds);
Console.ReadLine ();
}
The Business.cs class of the BLL layer:
public class Business
{
private list<persondetail> _personlist = new list<persondetail> ();
SQL Server database
persondbprovider dbprovider = new Persondbprovider ();
Elasticsearch
Esprovider esprovider = new Esprovider ();
public void Addtodb ()
{
_personlist = util.get10000persondetails ();//auxiliary class, generates 10,000 data
foreach (var Persondetail in _personlist)
{
Dbprovider.addperson (persondetail);
}
}
public void Addtoelasticindex ()
{
_personlist = Util.get10000persondetailswithid ();
foreach (Var persondetail in _personlist)
{
esprovider.index (persondetail);
}
}
Public list<persondetail> Getfromdb ()
{return
dbprovider.getallpersondetails ();
}
Public list<persondetail> getfromes ()
{return
esprovider.getall ();
}
}
PersonDbProvider.cs and ElasticSearchProvider.cs and Util.cs,setting.cs classes:
public class Persondbprovider {public bool Addperson (Persondetail persondetail) {try {//Database context using (var db = new Personcontext ()) {db.
Persondetails.add (Persondetail); Db.
SaveChanges ();
return true;
} catch (Exception) {return false; } public list<persondetail> Getallpersondetails () {try {using (var db = new Personcontex T ()) {return db.
Persondetails.tolist ();
} catch (Exception) {return null; }
}
}
public class Esprovider {public static elasticclient client = new Elasticclient (setting.connectionsettings);
public bool Index (persondetail person) {var client = new Elasticclient (setting.connectionsettings);
try {//Add data////When calling the index method below, if you do not specify which Index,elasticsearch will use directly our defaultindex in setting, if not, you will automatically create var index = client.
Index (person); return index.
Created; The catch (Exception ex) {Console.WriteLine ("Excepton message:" + ex.)
message);
return false; Public list<persondetail> GetAll () {var searchresults = client. Search<persondetail> (s => S. From (0).
Size (10000));
return SearchResults.Documents.ToList (); Public list<persondetail> getentities (string keyword) {var client = new Elasticclient (setting.connect
Ionsettings);
#region Full-Text Search keyword = String.Format ("*{0}*", keyword); The default operator is or, when keyword is similar to "one Two"In the middle of the space, will be treated as two keyword search, and then search results for or operations//So we need to adjust to the operator var searchresults = client. Search<persondetail> (s => S. Index ("Elastic-search-app"). Query (q => q.querystring (Qs => Qs.) Query (keyword).
Defaultoperator (Operator.and))); --------------------------------------------------------------------------------------//In addition because ES is a participle search, so when we want to use " One "to search for the complete word" justone ", you must add * * outside of" one ", similar to the%keyword% in SQL, but this will result in the search in full words when searching results, so we need to use the following way//
Wholekeyword = keyword;
Keyword = String.Format ("*{0}*", keyword);
Querycontainer query = new Querystringquery () {query = keyword, defaultoperator = Operator.and}; if (! String.IsNullOrEmpty (Wholekeyword))//{//Querycontainer wholewordquery = new Querystringquery () {Query = WholeK
Eyword}; query = Query | |
Wholewordquery; }//var searchresults = client. Search<person> (s => S//. Index ("zhixiao-application")//.
Query (query)//);
#endregion #region Specify a property search//Use term Query//term is an indexed exact value, i.e. Foo, foo, foo is not equal, so//in use term que
RY note that term query does not support uppercase when the search field has been indexed. Querycontainer Query2 = new Termquery {Field = Item. Key, Value = Item.
Value.tolower ()}; --------------------------------------------------------------------------------------//var searchresults = Client. Search<persondetail> (s => S//. Index ("Elastic-search-app")//.
Query (q => q.term (t => T.onfield (f => f.lastname = "keyword")));
Effect ditto//querycontainer termquery = new Termquery {Field = "LastName", Value = "keyword"}; var searchresults = client. Search<persondetail> (s => S//. Index ("Elastic-search-app")//.
Query (Termquery)//); --------------------------------------------------------------------------------------//Using Query String query/ /querystring query is typically used for full-text search, but can also be used for a single property search (Setting the Defaultfield property), QueryString query canTo be case-insensitive. QueryString also has the advantage that we can search a part of a term,//For example LastName "T Boterhuis 1", then we can use "Terhuis" to search for this data (although the need for outer bread on the * *), in the term
Query can not do, because the es of each attribute value are analyzed into a separate term, improve the efficiency of the search.
Keyword = "t boterhuis 2";
Querycontainer wholewordquery = new Querystringquery () {Query = keyword, defaultoperator = Operator.and}; var searchresults = client. Search<persondetail> (s => S//. Index ("Elastic-search-app")//.
Query (Wholewordquery)//);
#endregion return searchResults.Documents.ToList (); Public list<persondetail> Sort (string keyword) {//First we removed the original index from the var response = client. Deleteindex (New Deleteindexrequest (new Indexnamemarker () {Name = "Elastic-search-app", Type =
typeof (Persondetail))); Then recreate the index var indexresult = client.
CreateIndex ("Pd-application"); var response1 = client.
Map<persondetail> (M => m.mapfromattributes ()); Ienumerable<persondetail> PERsons = new List<persondetail> {new Persondetail () {Id = 4, FirstName = "Boterhuis-040", LastName = "Gusto-040",}, New Persondetail () {Id = 5, FirstName = "Sales@historichouse Hotels.com ", LastName =" T Boterhuis 1 ",}, New Persondetail () {Id = 6, FirstName =" Abe
Rdeen #110 ", LastName =" sales@historichousehotels.com ",}, New Persondetail () {Id = 7,
FirstName = "Aberdeen #110", LastName = "T Boterhuis 2",},}; foreach (var person in persons) {client.
Index (person); var searchresults = client. Search<persondetail> (s => S. Index ("Pd-application"). Sort (sort => sort.) Onfield (f => f.id).
Order (sortorder.ascending)));
return SearchResults.Documents.ToList ();
}
}
public static class Util {//Generate 10,000 SQL Server test data public static List<per
Sondetail> get10000persondetails () {var persondetailslist = new list<persondetail> (); for (int i = 0; I < 10000 i++) {Persondetailslist.add (new Persondetail () {FirstName = "FN" + new Random (). Next (int. MaxValue), LastName = "LN" + New Random (). Next (int.
MaxValue)});
return persondetailslist; //Generate 10,000 Elasticsearch test data public static list<persondetail> Get10000persondetailswithid () {var pe
Rsondetailslist = new list<persondetail> (); for (int i = 0; I < 10000 i++) {Persondetailslist.add (new Persondetail () {Id = i * new Random (). Next (), FirstName = "FN" + New Random (). Next (int. MaxValue), LastName = "LN" + New Random (). Next (int.
MaxValue)});
return persondetailslist; }
}
public static class Setting
{
The public static Uri Node
{get
{The return
new Uri ("http://localhost : 9200 ");
}
}
Connection configuration public
static ConnectionSettings connectionsettings
{get
{return
new ConnectionSettings (Node, Defaultindex: "Es-index-app");}}
Model Layer Code:
public partial class Persondetail
{public
long Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
}
public partial class Personcontext:dbcontext {static Personcontext () {
Database.setinitializer<personcontext> (NULL); Public Personcontext (): Base (' Name=personcontext ') {} public dbset<persondetail> Persondetai
ls {get; set;} protected override void Onmodelcreating (Dbmodelbuilder modelbuilder) {//The mapping class can be called directly in the overridden Onmodelcreating method, thereby reducing the onmod The complexity of the Elcreating method also enhances the readability of Code maintenance MODELBUILDER.CONFIGURATIONS.ADD (New Persondetailmap ()); Property Mapping Convention}
Fluent API Configuration Configuration Mapping class public classes
persondetailmap:entitytypeconfiguration<persondetail>
{ Public
Persondetailmap ()
{
//primary key this
. Haskey (t => new {t.id, T.firstname, t.lastname});
Property This
. Property (t => t.id)
. Hasdatabasegeneratedoption (databasegeneratedoption.identity);
This. Property (t => t.firstname)
. IsRequired ();
This. Property (t => t.lastname)
. IsRequired ();
Table & Column Mappings this
. ToTable ("Persondetails");
This. Property (t => t.id). Hascolumnname ("Id");
This. Property (t => t.firstname). Hascolumnname ("FirstName");
This. Property (t => t.lastname). Hascolumnname ("LastName");
}
SQL Server script:
Use the [person] go
set ANSI_NULLS on Go Set QUOTED_IDENTIFIER on Go
CREATE TABLE [dbo].[ Persondetails] (
[Id] [bigint] IDENTITY (1,1) not NULL,
[FirstName] [nvarchar] (max) is not null,
[LastName] [ NVARCHAR] (max) not NULL in
[PRIMARY] Go
Result diagram:
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.