安装NuGet包,搜索Nest 并安装
如上图:选择最新稳定版本安装
注:操作Json的话 还要下载一个Newtonsoft.Json 包
开始使用
这里是以服务的方式进行实现的,经过测试ElasticSearch访问性能最高的是注册成单例服务,请求时要使用异步。这样性能可以提升到极致。
(1)创建IESSever接口类,创建两个Client,这里一个client支持linq查询,一个client支持json查询
///<summary>
///访问ElasticSearch服务接口类
///</summary>
publicinterface IESSever
{
/// <summary>
/// Linq查询的官方Client
/// </summary>
IElasticClient ElasticLinqClient { get; set; }
/// <summary>
/// Js查询的官方Client
/// </summary>
IElasticLowLevelClient ElasticJsonClient { get; set; }
}
(2)创建ESSever实现类,继承上面的接口 如下
///<summary>
/// 访问ElasticSearch服务类
/// </summary>
public class ESSever : IESSever
{
/// <summary>
/// Linq查询的官方Client
/// </summary>
public IElasticClient ElasticLinqClient { get; set; }
/// <summary>
/// Js查询的官方Client
/// </summary>
public IElasticLowLevelClient ElasticJsonClient { get; set; }
public ESSever(IConfiguration configuration)
{
var uris = configuration["ElasticSearchContext:Url"].Split(",").ToList().ConvertAll(x => new Uri(x));//配置节点地址,以,分开
var connectionPool = new StaticConnectionPool(uris);//配置请求池
var settings = new ConnectionSettings(connectionPool).RequestTimeout(TimeSpan.FromSeconds(30));//请求配置参数
this.ElasticJsonClient = new ElasticLowLevelClient(settings);//json请求客户端初始化
this.ElasticLinqClient = new ElasticClient(settings);//linq请求客户端初始化
}
}
注:请求配置时,如果ElasticSearch需要账号密码时需要把settings修改为如下
var settings = new ConnectionSettings(connectionPool)
.BasicAuthentication("user", "password")
.RequestTimeout(TimeSpan.FromSeconds(30));
(4)注册服务
在startup里面在ConfigureServices下面添加如下代码即可
services.AddSingleton<IESSever, ESSever>();
(5)在Controller中使用
linq查询如下所示
[Route("api")]
[ApiController]
public class TestController : Controller
{
[HttpGet("tessst")]
public async Task<List<Persons>> ElasticTest([FromServices] IESSever eSSever)
{
var list = await eSSever.ElasticLinqClient.SearchAsync<Persons>(
p => p.Index("persons")
.Type("Persons")
.Query(op => op.Match(
ss => ss.Field(
qq => qq.EnterpriseName == "测试有限责任公司"))));
return list.Documents.ToList();
}
}
Json查询如下所示
[Route("api")]
[ApiController]
public class TestController : Controller
{
[HttpGet("test")]
public async Task<JObject> ElasticTest1([FromServices] IESSever eSSever)
{
var jsonobject = new { query = new { match = new { EnterpriseName = "测试有限责任公司" } } };
string json = JsonConvert.SerializeObject(jsonobject);
var stringResponse = await eSSever.ElasticJsonClient.SearchAsync<StringResponse>("persons", "Persons", json);
return JObject.Parse(stringResponse.Body);
}
}
简单使用在这里就完毕了。
原文链接:
https://blog.csdn.net/qq_38762313/article/details/90290284