.NET Core Elasticsearch.Net and NEST
1. 安装包
powershell
Install-Package NEST
Install-Package Elasticsearch.Net
1
2
2
2. 在 appsettings.json
中增加配置项
关于 .net core 中的配置项的用法可以参照 .NET Core The New Configuration Model in ASP.NET Core。
json
"B2bElasticSearch": {
"Uris": [
"http://192.168.0.72:9200"
]
}
1
2
3
4
5
2
3
4
5
3. 增加配置项对应的配置类 ElasticSearchConfig
cs
public class ElasticSearchConfig
{
public IEnumerable<string> Uris { get; set; }
}
1
2
3
4
2
3
4
4. 增加自定义的连接池 B2bElasticConnectionPool
cs
public class B2bElasticConnectionPool : SniffingConnectionPool
{
public B2bElasticConnectionPool(IOptions<ElasticSearchConfig> options) : base(options.Value.Uris.Select(uri => new Uri(uri)))
{
}
}
1
2
3
4
5
6
2
3
4
5
6
5. 增加自定义的客户端 ElasticClient
cs
public class B2bElasticClient : ElasticClient
{
public B2bElasticClient(IConnectionPool pool) : base(new ConnectionSettings(pool))
{
}
}
1
2
3
4
5
6
2
3
4
5
6
6. 在 Startup.cs
中注册配置和服务
cs
public void ConfigureServices(IServiceCollection services)
{
// ...
// 注册 ElasticSearch 设定
services.Configure<ElasticSearchConfig>(Configuration.GetSection("B2bElasticSearch"));
// 注入 ElasticSearch 连接池
services.AddSingleton<IConnectionPool, B2bElasticConnectionPool>();
// 注入 ElasticSearch Client
services.AddScoped<IElasticClient, B2bElasticClient>();
services.AddMvc();
// ...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
7. 在 Controller
中创建、查询 ElasticSearch
文档
cs
[Produces("application/json")]
[Route("api/Line")]
public class LineController : Controller
{
private readonly IElasticClient _elasticClient;
private static string LINE_INDEX = "net-core-test-index";
public LineController(IElasticClient elasticClient)
{
_elasticClient = elasticClient;
}
// GET api/line
[HttpGet]
public IEnumerable<Line> Get()
{
// 首次访问时追加初始数据
var countResponse = _elasticClient.Count<Line>(c => c.Index(LINE_INDEX).Query(q => q.MatchAll()));
if (countResponse.Count <= 0)
{
for (int i = 0; i < 10; i++)
{
// indexing
var line = new Line()
{
Id = i,
Title = $"测试线路 {i}",
Price = 1000 * i,
};
var indexResponse = _elasticClient.Index(line, id => id.Index(LINE_INDEX));
}
}
// Searching
var searchResponse = _elasticClient.Search<Line>(s => s
.Index(LINE_INDEX)
.From(0)
.Size(10)
);
return searchResponse.Documents;
}
// GET api/line/5
[HttpGet("{id}")]
public IEnumerable<Line> Get(int id)
{
// Searching
var searchResponse = _elasticClient.Search<Line>(s => s
.Index(LINE_INDEX)
.From(0)
.Size(10)
.Query(q => q
.Ids(i => i.Values(id)
)
)
);
return searchResponse.Documents;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63