欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Elasticsearch.Net使用入门教程(1)

程序员文章站 2022-06-30 10:18:40
本文实例为大家分享了elasticsearch.net使用教程,供大家参考,具体内容如下 首先去官网下载elasticsearch 2.3.4安装包,解压后,在cmd命令...

本文实例为大家分享了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 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 

结果图:

Elasticsearch.Net使用入门教程(1)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。