本文執行個體為大家分享了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 = "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 { //產生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 ONGO SET QUOTED_IDENTIFIER ONGO CREATE TABLE [dbo].[PersonDetails]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [FirstName] [nvarchar](max) NOT NULL, [LastName] [nvarchar](max) NOT NULL) ON [PRIMARY] GO
結果圖:
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援topic.alibabacloud.com。