1. 程式人生 > >ASP.NET Web API + Elasticsearch 6.x 快速做個全文搜尋

ASP.NET Web API + Elasticsearch 6.x 快速做個全文搜尋

最近想做個全文搜尋,設想用 ASP.NET Web API + Elasticsearch 6.x 來實現。

網上搜了下 Elasticsearch 的資料,大部分是講 linux 平臺下如何用 java 來開發,有少量講在 windows 平臺下用 c# 開發的,且版本是 Elasticsearch 5.x 。無奈上官網擼串,這裡梳理下官網的教程,希望對大家有所幫助。

 

一、Elasticsearch 的安裝 

 

下載  MSI(https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.0.1.msi

)安裝檔案,完成後雙擊安裝,點下一步,全部預設設定。

 

二、執行 Elasticsearch

 

開啟 cmd,輸入

cd %PROGRAMFILES%\Elastic\Elasticsearch\bin

回車,輸入 

.\elasticsearch.exe

回車

 

三、開發環境搭建

 

1、新建一個 webApi 工程

2、安裝 NEST,用來連線 Elasticsearch

 

開啟 NuGet 包管理器控制檯,輸入以下命令

Install-Package NEST -Version 6.0
.1

注意安裝時帶上版本號,NEST 與 Elasticsearch 版本對應,這是個坑。

 

3、連線 Elasticsearch

 

新建一個連線類 ClientHelper.cs

 1 public class ClientHelper
 2 {
 3     private static ClientHelper clientHelper = null;
 4     // 預設索引
 5     public static string DEFAULT_INDEX = "resource";
 6     private ElasticClient Client()
7 { 8 var nodes = new Uri[] 9 { 10 new Uri("http://127.0.0.1:9200") 11 }; 12 var pool = new StaticConnectionPool(nodes); 13 var settings = new ConnectionSettings(pool) 14 .DefaultIndex(DEFAULT_INDEX) 15 .PrettyJson(); 16 //.BasicAuthentication("elastic", "changeme"); 17 18 return new ElasticClient(settings); 19 } 20 21 public static ElasticClient getInstance() 22 { 23 if(clientHelper==null){ 24 clientHelper = new ClientHelper(); 25 } 26 return clientHelper.Client(); 27 } 28 }

 

新建對映類 Resource.cs

1 [ElasticsearchType(Name = "resource", IdProperty = "ID")]
2 public class Resource
3 {
4     [Keyword(Name = "id")]
5     public string ID { get; set; }
6 
7     [Text(Name = "name")]
8     public string NAME { get; set; }
9 }

 

4、增刪查改操作

 

新建一個 api 控制器 ESController.cs

 1 public class ESController : ApiController
 2 {
 3   // GET: api/ES/1
 4   // 按 id 查詢單條記錄
 5   public Resource Get(string id)
 6   {
 7       var client = ClientHelper.getInstance();
 8       var response = client.Get<Resource>(id, idx => idx.Index(ClientHelper.DEFAULT_INDEX));
 9       return response.Source;
10   } 
11      
12   // POST api/ES   
13   // 批量匯入資料庫資料
14   public string Post()
15   {
16       using (DataContext db = new DataContext())
17        {
18           var client = ClientHelper.getInstance();
19           List<Demo>  items= db.demo.ToList();
20           for (int i = 0; i < 100;i++ )
21           {
22              var item = items[i];
23              Resource mod = new Resource();
24              mod.ID = item.ID;
25              mod.NAME = item.NAME;
26              client.Index<Resource>(mod, idx => idx.Index(ClientHelper.DEFAULT_INDEX));
27           }
28       }
29       return "OK";
30    }
31 
32    // PUT api/ES/5
33    // 按 id 更新單條資料
34    public Result Put(string id)
35    {
36        var client = ClientHelper.getInstance();
37        var response = client.Update<Resource>(id, idx => idx.Index(ClientHelper.DEFAULT_INDEX));
38        return response.Result; 
39    }
40 
41     // DELETE api/ES/5
42     // 按 id 刪除單條資料
43     public Result Delete(string id)
44     {
45       var client = ClientHelper.getInstance();
46       var response = client.Delete<Resource>(id, idx => idx.Index(ClientHelper.DEFAULT_INDEX));
47       return response.Result; 
48     }
49 }

 

另新建一個api 控制器 SearchController.cs 用來提供搜尋服務

 1 public class SearchController : ApiController
 2 {
 3     // GET: api/Search/
 4     public List<IHit<Resource>> Get(string id)
 5     {
 6         var client = ClientHelper.getInstance();
 7         var modList = client.Search<Resource>(s => s
 8             .From(0)
 9             .Size(10)
10             .Query(q => q.Term(t => t.NAME, id))
11         );
12         return modList.Hits.ToList();
13     }
14 }

 

5、試一試

(1) 匯入資料到 Elasticsearch

POST http://localhost:8389/api/es

 

(2) 查詢 id 為 1 的記錄

GET http://localhost:8389/api/es/1

 

(3) 更新 id 為 1 的記錄

PUT http://localhost:8389/api/es/1

 

(4) 刪除 id 為 1 的記錄

DELETE http://localhost:8389/api/es/1

 

(5) 查詢名字中帶有 中 的記錄

GET http://localhost:8389/api/Search/中

 

一個簡單的全文索引服務就完成了!