使用NEST调用ElasticSearch
前言
ElasticSearch(以后简称ES)是一个稳定可靠快速的分布式文档存储(内存+本地持久化)和搜索引擎
本文使用.NetCore3.1调用ES作为示例。ES的.NET SDK采用NEST
注意:ES版本与NEST版本需要匹配,否则会造成”Invalid NEST response built from a unsuccessful () low level call on POST“。示例使用elasticsearch:7.16.1+NEST:7.17.0
ElasticSearch安装部署
# ElasticSearch安装手册 ## 拉取镜像 ``` docker pull elasticsearch:7.16.1 ``` ## 创建本地映射 ``` mkdir -p /elasticsearch/data chmod -R 777 /elasticsearch/data ``` ## 开启容器 ``` docker run --name es -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -v /elasticsearch/data:/usr/share/elasticsearch/data -d elasticsearch:7.16.1 ``` ## 修改配置 ``` docker exec -it es /bin/bash ls cd config ls vi elasticsearch.yml # 加入跨域配置 http.cors.enabled: true http.cors.allow-origin: "*" http.cors.allow-headers: Authorization xpack.security.enabled: true xpack.security.transport.ssl.enabled: true # 设置密码(如果运行以下命令提示不成功,exit退出容器后restart再进入) bin/elasticsearch-setup-passwords interactive ``` ## 重启容器 ``` docker restart es ```
.NETCORE3.1调用
1.Nuget中获取NEST(v7.17.0)
2.appsettings.json中配置ES地址
"EsUrl": "http://192.168.1.10:9200/"
3.增加ES操作服务
IEsClientProvider.cs
using Nest; namespace Elasticsearch.Service { public interface IEsClientProvider { ElasticClient GetClient(); } }
EsClientProvider.cs
using Microsoft.Extensions.Configuration; using Nest; using System; namespace Elasticsearch.Service { public class EsClientProvider : IEsClientProvider { private readonly IConfiguration _configuration; private ElasticClient _client; public EsClientProvider(IConfiguration configuration) { _configuration = configuration; } public ElasticClient GetClient() { if (_client != null) return _client; InitClient(); return _client; } private void InitClient() { var node = new Uri(_configuration["EsUrl"]); _client = new ElasticClient(new ConnectionSettings(node).DefaultIndex("tracks")); } } }
4.Startup.ConfigureServices中注册服务
services.AddSingleton<IEsClientProvider, EsClientProvider>();
5.Controller中获取注入的服务
using Elasticsearch.Service; using Microsoft.AspNetCore.Mvc; using Nest; using System.Collections.Generic; namespace Elasticsearch.Controllers { [Route("api/[controller]")] [ApiController] public class ValueController : ControllerBase { private readonly ElasticClient _client; public ValueController(IEsClientProvider clientProvider) { _client = clientProvider.GetClient(); } /// <summary> /// 提交数据 /// </summary> /// <param name="post"></param> /// <returns></returns> [HttpPost("[action]")] public Post Submit(Post post) { IndexResponse res=_client.IndexDocument(post); if (res.IsValid) { return post; } else { return null; } } /// <summary> /// 查询数据 /// </summary> /// <param name="shipguid"></param> /// <returns></returns> [HttpGet("[action]")] public IReadOnlyCollection<Post> Search(string shipguid) { return _client.Search<Post>(s => s .From(0) .Size(10) .Query(q => q.Match(m => m.Field(f => f.shipGuid).Query(shipguid)))).Documents; } } }