Getting started with Elasticsearch. Net (1 ),
The examples in this article share the Elasticsearch. Net tutorial for your reference. The specific content is as follows:
First download the Elasticsearch 2.3.4 installation package from the official website, decompress the package, go to the installation directory on the cmd command line, go to the bin directory, and run the elasticsearch. bat command.
Elasticsearch plug-in elasticsearch-head installation:
Run the plugin-install mobz/elasticsearch-head command in the bin directory.
Then start. net Programming and build the console application.
The Program. cs code is as follows:
Class Program {static void Main (string [] args) {Console. writeLine ("* Run Program:" + DateTime. now); var business = new Business (); var swRead = new Stopwatch (); // swRead. start (); // business. addToDb (); // Add data to the SQL Server database // 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 ();}}
BLL layer Business. cs class:
Public class Business {private List <PersonDetail> _ personList = new List <PersonDetail> (); // SQLSERVER database PersonDbProvider dbProvider = new PersonDbProvider (); // ElasticSearch ESProvider esProvider = new ESProvider (); public void AddToDb () {_ personList = Util. getaskpersondetails (); // helper class that generates 10000 pieces of data foreach (var personDetail in _ personList) {dbProvider. addPerson (personDetail) ;}} public void AddToElasticIndex () {_ personList = Util. getinclupersondetailswithid (); foreach (var personDetail in _ personList) {esProvider. index (personDetail) ;}} public List <PersonDetail> GetFromDB () {return dbProvider. getAllPersonDetails ();} public List <PersonDetail> GetFromES () {return esProvider. getAll ();}}
PersonDbProvider. cs, ElasticSearchProvider. cs, Util. cs, and Setting. cs:
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 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 following index method, if no index is specified, ElasticSearch will directly use defaultIndex in setting. If no, the var index = client is automatically created. index (person); return index. created;} catch (Exception ex) {Consol E. writeLine ("cmdton 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. connectionSettings); # region full-text search keyword = String. format ("* {0} *", keyword ); // The default Operator is Or. When keyword is similar to a space in the middle of "One Two", it is used as Two keyword searches, then perform the or operation on the search results. Therefore, we need to adjust Operator var searchResults = client as needed. search <PersonDetail> (s => s. index ("elastic-search-app "). query (q => q. queryString (qs => qs. query (keyword ). defaultOperator (Operator. and); // else // In addition, because elasticsearch is word segmentation, when we use "One" to search for the complete word "JustOne" You must add ** outside "One", similar to % keyword % in SQL, however, this method will cause the search results to fail when using the complete word. Therefore, we need to use the following method // 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 = wholeKeyword}; // query = query | wholeWordQuery; /// var searchResults = client. search <Person> (s => s //. index ("zhixiao-application ")//. query (query) //); # endregion # region specifies the attribute to search // use the term Query // Term is an exact value to be indexed, that is, Foo, foo, FOO is not equal, so // when using the term query, note that the Field searched by the term query has been indexed It cannot be capitalized. // QueryContainer query2 = new TermQuery {Field = item. key, Value = item. value. toLower ()}; // returns // var searchResults = client. search <PersonDetail> (s => s //. index ("elastic-search-app ")//. query (q => q. term (t => t. onField (f => f. lastName = "keyword") //); // The effect is the same as above. // QueryContainer termQuery = new TermQuery {Fie Ld = "lastname", Value = "keyword"}; // var searchResults = client. search <PersonDetail> (s => s //. index ("elastic-search-app ")//. query (termQuery) //); // Query // use query String query // QueryString Query is generally used for full-text search, but it can also be used for searching a single attribute (set the DefaultField attribute ), queryString query can be case-insensitive. Another benefit of QueryString is that we can search for a part of a term, // For example, lastname is "t Boterhuis 1 ", so we can use "terhuis" to search for this data (although we need to put it on the outer bread **), we can't do it in the term query, ES analyzes the values of each attribute into separate terms, improving the search efficiency. // 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 delete the original index var response = client. deleteIndex (new DeleteIndexRequest (new IndexNameMarker () {Name = "elastic-search-app", Type = typeof (PersonDetail )})); // 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, FirstName = "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 10000 pieces of sqlserver test data public static List <PersonDetail> getinclupersondetails () {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 10000 ElasticSearch test data public static List <PersonDetail> getinclupersondetailswithid () {var personDetailsList = new List <PersonDetail> (); for (int I = 0; I <10000; I ++) {personDetailsList. add (new PersonDetail () {Id = I * new Random (). next (99), 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 {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> PersonDetails {get; set ;} protected override void OnModelCreating (DbModelBuilder modelBuilder) {// you can directly call the ing Class in the override OnModelCreating method, which reduces the complexity of the OnModelCreating method and enhances the readability of code maintenance modelBuilder. events. add (new PersonDetailMap (); // attribute ing Convention }}
// Fluent API Configuration ing class public class PersonDetailMap: EntityTypeConfiguration <PersonDetail> {public PersonDetailMap () {// primary key this. hasKey (t => new {t. id, t. firstName, t. lastName}); // attribute this. property (t => t. id ). hasDatabaseGeneratedOption (DatabaseGeneratedOption. identity); this. property (t => t. firstName ). isRequired (); this. property (t => t. lastName ). isRequired (); // table & Column ing 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 ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[PersonDetails]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [FirstName] [nvarchar](max) NOT NULL, [LastName] [nvarchar](max) NOT NULL ) ON [PRIMARY] GO
Result chart:
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.