Elasticsearch.net Getting Started Tutorials (1)

Source: Internet
Author: User
Tags map class
The example of this article for everyone to share the elasticsearch.net use of the tutorial, for your reference, the specific content as follows

First go to the official website to 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 the Elasticsearch.bat command.

Elasticsearch plug-in Elasticsearch-head installation:

Execute command plugin-install mobz/elasticsearch-head in the bin directory

Then start. NET programming, build a console application

The Program.cs code is as follows:

Class program  {   static void Main (string[] args)   {    Console.WriteLine ("*program starts running:" + 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 {//DB 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 Personcontext ()) {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 be used directly with our defaultindex in setting, if not, the Var I will be created automatically Ndex = client.     Index (person); return index.    Created; } 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.connection      Settings);    #region Full-Text Search keyword = String.Format ("*{0}*", keyword); The default operator is or, when keyword is similar to "one Two" and the like, when there are spaces in the middle, will be used as two keyword search, and then search results for or operations    So we need to adjust operator var searchresults = client based on demand. 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 word breaker, so when we want to use " One "to search the full word" justone ", you have to add a * * outside the" one ", similar to the%keyword% in SQL, but this will result in a full word to search for the time when the search 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 = WholeKey    Word}; query = Query | |    Wholewordquery; }//var searchresults = client. Search<person> (s = = S//. Index ("zhixiao-application")//.      Query (query)//); #endregion #region Specified attribute search//Use term QuerY//term is an index of the exact value, that is, Foo, foo, foo is not equal, so//when using the term query, note that the term query in the search field has been indexed, is not support capitalization. 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)//); --------------------------------------------------------------------------------------//Use query String to query// QueryString query is generally used for full-text search, but it can also be used for a single property search (Setting the Defaultfield property), QueryString query can be case insensitive. QueryString Another advantage is that we can search for a part of a term,//For example LastName as "T BoterhuiS 1 ", then we can use" Terhuis "to search for this data (although need on the outer bread * *), in the term query can not be done, because ES the value of each attribute is 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 remove the original index first by removing the var response = client. Deleteindex (New Deleteindexrequest (new Indexnamemarker () {Name = "Elastic-search-app", type = Type      Of (Persondetail)}); Then re-create 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 @historichousehotels. com ", LastName =" T Boterhuis 1 ",}, New Persondetail () {Id = 6, Firstnam      E = "Aberdeen #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<person         Detail> get10000persondetails () {var persondetailslist = new list<persondetail> (); for (int i = 0; i < 10000; i++) {Persondetailslist.add (new Persondetail () {FirstName = "FN" + new Ran Dom (). Next (int. MaxValue), LastName = "LN" + New Random (). Next (int.    MaxValue)});   } return persondetailslist; }//Generate 10,000 Elasticsearch test data public static list<persondetail> Get10000persondetailswithid () {var person         Detailslist = 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  {public   static URI Node   {    get   {     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 () {Data Base.   Setinitializer<personcontext> (NULL); Public Personcontext (): Base ("Name=personcontext") {} public dbset<persondetail> Persondetails { Get Set } protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {//can invoke the mapping class directly in the overridden Onmodelcreating method, thus reducing the O The complexity of the nmodelcreating method, while also enhancing the readability of code maintenance MODELBUILDER.CONFIGURATIONS.ADD (New Persondetailmap ()); Property Mapping Convention}} 
The Fluent API configures the configuration map class public  class Persondetailmap:entitytypeconfiguration<persondetail>  { Public   Persondetailmap ()   {    //primary key this    . Haskey (t = new {t.id, T.firstname, t.lastname});      property of 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 [person] GO   SET ansi_nulls ongo   SET quoted_identifier Ongo   CREATE TABLE [dbo].[ Persondetails] (  [Id] [bigint] IDENTITY (a) not null,  [FirstName] [nvarchar] (max) is not null,  [LastName] [ NVARCHAR] (max) not NULL) on [PRIMARY]   GO

Result diagram:

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.