程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> Elasticsearch.Net使用入門教程(1),

Elasticsearch.Net使用入門教程(1),

編輯:關於.NET

Elasticsearch.Net使用入門教程(1),


本文實例為大家分享了Elasticsearch.Net使用教程,供大家參考,具體內容如下

首先去官網下載Elasticsearch 2.3.4安裝包,解壓後,在cmd命令行進入安裝目錄,再進入 bin目錄,運行elasticsearch.bat命令。

elasticsearch插件elasticsearch-head安裝:

bin目錄下執行命令plugin -install mobz/elasticsearch-head

然後開始.net編程,構建控制台應用程序

Program.cs代碼如下:

class Program 
 { 
  static void Main(string[] args) 
  { 
   Console.WriteLine("*Program 開始運行 : " + DateTime.Now); 
   var business = new Business(); 
 
   var swRead = new Stopwatch(); 
   //swRead.Start(); 
   //business.AddToDb();//sqlserver數據庫增加數據 
   //swRead.Stop(); 
   //Console.WriteLine("DB 寫入時間 : " + swRead.ElapsedMilliseconds); 
 
   //swRead.Reset(); 
   //swRead.Start(); 
   //business.AddToElasticIndex(); 
   //swRead.Stop(); 
   //Console.WriteLine("ES 寫入時間 : " + swRead.ElapsedMilliseconds); 
    
   var sw = new Stopwatch(); 
   sw.Start(); 
   var personsFromDB = business.GetFromDB(); 
   sw.Stop(); 
   Console.WriteLine("DB 讀時間 : " + sw.ElapsedMilliseconds); 
    
   sw.Reset(); 
   sw.Start(); 
   var personsFromEs = business.GetFromES(); 
   sw.Stop(); 
   Console.WriteLine("ES 讀時間 : " + sw.ElapsedMilliseconds); 
 
   Console.ReadLine(); 
  } 
 } 

BLL層的Business.cs類:

public class Business 
 { 
  private List<PersonDetail> _personList = new List<PersonDetail>(); 
   
  //SQLSERVER數據庫 
  PersonDbProvider dbProvider = new PersonDbProvider(); 
 
  //ElasticSearch 
  ESProvider esProvider = new ESProvider(); 
 
  public void AddToDb() 
  { 
   _personList = Util.Get10000PersonDetails();//輔助類,生成10000條數據 
 
   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和ElasticSearchProvider.cs以及Util.cs,Setting.cs類:

public class PersonDbProvider 
 { 
  public bool AddPerson(PersonDetail personDetail) 
  { 
   try 
   { //數據庫上下文 
    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 
   { 
    //添加數據 
    //在調用下面的index方法的時候,如果沒有指定使用哪個index,ElasticSearch會直接使用我們在setting中的defaultIndex,如果沒有,則會自動創建 
    var index = 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.ConnectionSettings); 
 
   #region 全文搜索 
 
   keyword = String.Format("*{0}*", keyword); 
   //默認的Operator是Or,當keyword是類似於"One Two"之類的中間有空格的時候,會被當成兩個關鍵詞搜索,然後搜索結果進行or運算 
   //所以我們需要根據需求來調整Operator 
   var searchResults = client.Search<PersonDetail>(s => s 
    .Index("elastic-search-app") 
    .Query(q => q.QueryString(qs => qs.Query(keyword).DefaultOperator(Operator.And))) 
    ); 
 
   //-------------------------------------------------------------------------------------- 
   //另外由於ES是分詞搜索,所以當我們要用"One"來搜索完整的單詞"JustOne"的時候,就必須在"One"外面添加**,類似於SQL裡面的%keyword%,但是這樣的做法會導致在用完整的單詞來搜索的時候搜索不到結果,所以我們需要使用下面的方式 
 
   //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 指定屬性搜索 
 
   //使用term Query 
   //Term是一個被索引的精確值,也就是說Foo, foo, FOO是不相等的,因此 
   //在使用term query的時候要注意,term query在搜索的Field已經被索引的時候,是不支持大寫的。 
   // 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"))) 
   //); 
   //效果同上 
   //QueryContainer termQuery = new TermQuery { Field = "lastname", Value = "keyword" }; 
   //var searchResults = client.Search<PersonDetail>(s => s 
   // .Index("elastic-search-app") 
   // .Query(termQuery) 
   //); 
   //-------------------------------------------------------------------------------------- 
   //使用 Query String query 
   //QueryString query一般用於全文搜索,但是也可以用於單個屬性的搜索(設置DefaultField屬性),queryString query可以不區分大小寫。QueryString還有一個好處就是我們可以搜索一個term中的一部分, 
   //例如lastname為"t Boterhuis 1",那麼我們可以用"terhuis"搜索到這個數據(雖然需要在外面包上**),在term query裡面就做不到,因為ES把每一個屬性的值都分析成一個個單獨的term,提高了搜索的效率。 
   //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) 
  { 
   // 首先我們把原先的索引先刪除了 
   var response = 
    client.DeleteIndex( 
     new DeleteIndexRequest(new IndexNameMarker() 
     { 
      Name = "elastic-search-app", 
      Type = typeof(PersonDetail) 
     })); 
 
   //然後重新創建索引 
   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 = "[email protected]", 
     LastName = "t Boterhuis 1", 
    }, 
    new PersonDetail() 
    { 
     Id = 6, 
     FirstName = "Aberdeen #110", 
     LastName = "[email protected]", 
    }, 
    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 
 { 
 
  //生成10000條sqlserver測試數據 
  public static List<PersonDetail> 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; 
  } 
 
  //生成10000條ElasticSearch測試數據 
  public static List<PersonDetail> Get10000PersonDetailsWithID() 
  { 
   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"); 
   } 
  } 
  //連接配置 
  public static ConnectionSettings ConnectionSettings 
  { 
   get 
   { 
    return new ConnectionSettings(Node, defaultIndex: "es-index-app"); 
   } 
  } 
 
 } 

Model層代碼:

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) 
  { 
   //在重寫OnModelCreating方法中則可以直接調用映射類,從而減少了OnModelCreating方法的復雜度,同時也增強了代碼維護的可讀性 
   modelBuilder.Configurations.Add(new PersonDetailMap()); //屬性映射約定 
  } 
 } 
//Fluent API配置Configuration映射類 
 public class PersonDetailMap : EntityTypeConfiguration<PersonDetail> 
 { 
  public PersonDetailMap() 
  { 
   // 主鍵 
   this.HasKey(t => new { t.Id, t.FirstName, t.LastName }); 
 
   // 屬性 
   this.Property(t => t.Id) 
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 
 
   this.Property(t => t.FirstName) 
    .IsRequired(); 
 
   this.Property(t => t.LastName) 
    .IsRequired(); 
 
   // 表 & 列 映射 
   this.ToTable("PersonDetails"); 
   this.Property(t => t.Id).HasColumnName("Id"); 
   this.Property(t => t.FirstName).HasColumnName("FirstName"); 
   this.Property(t => t.LastName).HasColumnName("LastName"); 
  } 
 } 

sqlserver腳本:

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 

結果圖:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持幫客之家。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved