准备工作: VSCode开发环境,在终端控制台(Ctrl+~)输入命令 dotnet add package Nest 安装NEST包,安装好后打开项目的.csproj文件如下图。

用 【NEST】 在C#中操作ElasticSearch

一、索引数据:

 1 using Nest;
 2 using System;
 3 
 4 namespace NetCoreFirst
 5 {
 6     public class ImportES
 7     {
 8         public static string ElasticsearchMethod()
 9         {
10             //1.通过es服务器 localhost:9200 来定义es client
11             var node = new Uri("http://localhost:9200");
12             var indexName = "esbot";
13             var settings = new ConnectionSettings(node).DefaultIndex(indexName);
14             var elastic = new ElasticClient(settings);
15             
16             //es服务器健康检查
17             var res = elastic.ClusterHealth();
18             Console.WriteLine(res.Status);
19 
20             //2.创建索引esbot
21             if (!elastic.IndexExists(indexName).Exists)
22             {
23                 var createIndexResponse = elastic.CreateIndex(indexName);
24                 var mappingBlogPost = elastic.Map<Resume>(s => s.AutoMap());
25             }
26 
27             //3.构造数据
28             string[] nameArray = {"Cody", "Blake", "Dennis", "Evan ", "Harris", "Jason ", "Lambert ", "Louis ", "Milton ", "Cody" };
29             string[] skillArray = {"c#", "c++", "java", "python", "php", "Linux", "ruby", "matlab", "perl", "powershell" };
30             long[] ageRange = { 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 };
31             for(int i=0; i< 10;i++)
32             {
33                 var resume = new Resume
34                 {
35                     Id= Guid.NewGuid(),
36                     Name=nameArray[i],
37                     Age=ageRange[i],
38                     Skills="My skill is Azure and " + skillArray[i]
39                 };
40                 //4.导入数据到索引
41                 IIndexResponse bulkIndexResponse = elastic.Index(resume, p => p.Type(typeof(Resume)).Id(i).Refresh(null));
42             }
43 
44             //5. 简单搜索
45             var searchResult = elastic.Search<Resume>(sr => sr.Query(q => q.MatchAll()));
46             // System.Console.WriteLine(searchResult.Hits.Count);
47             // System.Console.ReadLine();
48             var resumesCount = searchResult.Hits.Count.ToString();
49             return resumesCount;
50         }
51     }
52 }

Resume类的定义:

 1 using Nest;
 2 using System;
 3 
 4 namespace NetCoreFirst
 5 {
 6     [ElasticsearchType(Name="candidate", IdProperty="Id")]
 7     public class Resume
 8     {
 9         [Text(Name="id", Index=false)]
10         public Guid? Id { get; set; }
11 
12         [Text(Name="name", Index=true)]
13         public string Name { get; set; }
14 
15         [Text(Name="age", Index=false)]
16         public long Age { get; set; }
17 
18         [Text(Name="skills", Index=true)]
19         public string Skills { get; set; }
20     }
21 }
View Code

相关文章: