前言

在上一篇文章《ElasticSearch学习第一篇:windows环境下安装使用》,我已经简单介绍了关于ES的安装部署及一些概念性的东西,还有一些简单的增删改查操作。本文主要也是做一些增删改查操作,不同的是,我们要通过代码来实现。

.net关于ES的客户端

在.net客户端中,官网给我们提供了两个客户端Elasticsearch.Net和NEST
Elasticsearch.Net是一个低级别、无依赖的客户端,它对您如何构建和表示您的请求和响应没有任何意见。它已经足够抽象,因此所有Elasticsearch API 端点都表示为方法,但不会太多妨碍您构建 json/request/response 对象的方式。它还带有内置的、可配置/可覆盖的集群故障转移重试机制。Elasticsearch 是有弹性的,那么为什么不是您的客户呢?

NEST是一个高级客户端,将所有请求和响应映射为类型,并带有一个强类型查询 DSL,它使用 Elasticsearch 查询 DSL 映射 1 到 1。它利用特定的 .NET 功能来提供更高级别的抽象,例如CLR 类型的自动映射。在内部,NEST 使用并且仍然公开低级Elasticsearch.Net客户端,提供对 NEST 功能的访问,并允许用户在需要时下拉到低级客户端。
----来自官网的介绍

在.net core 5使用ES

这里我选择的是NEST,首先我创建了一个webapi的项目,将Nest的Nuget包添加进来。

<PackageReference Include="NEST" Version="7.16.0" />

然后在Startup将服务注册进来,并将ES的配置信息放在appsetting,json文件中

public void ConfigureServices(IServiceCollection services)
{
var url = Configuration["Elasticsearch:Url"] ?? "http://localhost:9200";
var defaultIndex = Configuration["Elasticsearch:DefaultIndex"] ?? "news";

var settings = new ConnectionSettings(new Uri(url))
   .DefaultIndex(defaultIndex)
   .BasicAuthentication(Configuration["Elasticsearch:UserName"], Configuration["Elasticsearch:PassWord"]);
var client = new ElasticClient(settings);
services.AddSingleton<IElasticClient>(client);

services.AddControllers();
services.AddSwaggerGen(c =>
{
   c.SwaggerDoc("v1", new OpenApiInfo { Title = "ElasticsearchDemo", Version = "v1" });
});
}

appsetting,json

  "Elasticsearch": {
    "Uri": "http://localhost:9200",
    "DefaultIndex": "stdtrainning",
    "UserName": "elastic",
    "PassWord": "123456"
  }

这时候我们已经可以使用NEST客户端了,直接创建个控制器,然后构造函数,在写简单的CURD操作

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ElasticsearchDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ESController : ControllerBase
    {
        private readonly IElasticClient _elasticClient;
        private readonly IConfiguration _configuration;

        public ESController(IElasticClient elasticClient, IConfiguration configuration)
        {
            _elasticClient = elasticClient;
            _configuration = configuration;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="param"></param>
        [HttpPost("IndexAsync")]
        public async Task<dynamic> IndexAsync([FromBody] News param)
        {
            var response = await _elasticClient.IndexAsync(param, x => x.Index(_configuration["Elasticsearch:DefaultIndex"]));
            return response.IsValid ? Ok(response.Id) : StatusCode(500);
        }
        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="param"></param>
        [HttpGet("GetAsync")]
        public async Task<dynamic> GetAsync(string id)
        {
            var response = await _elasticClient.GetAsync<News>(id, x => x.Index(_configuration["Elasticsearch:DefaultIndex"]));
            return response.IsValid ? Ok(response.Source) : NotFound();
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        [HttpPut("UpdateAsync")]
        public async Task<dynamic> UpdateAsync(string id, [FromBody] News value)
        {
            var response = await _elasticClient.UpdateAsync<News>(id, x => x.Index(_configuration["Elasticsearch:DefaultIndex"]).Doc(value));
            return response.IsValid ? Ok(response.Id) : StatusCode(500);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteAsync")]
        public async Task<dynamic> DeleteAsync(string id)
        {
            var response = await _elasticClient.DeleteAsync<News>(id, x => x.Index(_configuration["Elasticsearch:DefaultIndex"]));
            return response.IsValid;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="param"></param>
        [HttpPost("SearchAsync")]
        public async Task<dynamic> SearchAsync(string keyword)
        {
            var request = new SearchRequest
            {
                From = 0,
                Size = 20,
                Query = new MatchQuery { Field = "title", Query = keyword } ||
                        new MatchQuery { Field = "content", Query = keyword }
            };
            var response = await _elasticClient.SearchAsync<News>(request);
            return Ok(response.Documents);
        }
    }
    public class News 
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Column { get; set; }
        public string Content { get; set; }
    }
}

测试

先直接在postman查询看看news索引库,一共有三条数据

{
    "took": 859,
    "timed_out": false,
    "_shards": {
        "total": 3,
        "successful": 3,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 3,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "news",
                "_type": "_doc",
                "_id": "2",
                "_score": 1.0,
                "_source": {
                    "id": "2",
                    "title": "娱乐新闻2",
                    "column": "娱乐栏目",
                    "content": "娱乐内容2"
                }
            },
            {
                "_index": "news",
                "_type": "_doc",
                "_id": "3",
                "_score": 1.0,
                "_source": {
                    "id": "3",
                    "title": "体育新闻1",
                    "column": "体育栏目",
                    "content": "体育内容1"
                }
            },
            {
                "_index": "news",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "id": "1",
                    "title": "娱乐新闻1",
                    "column": "娱乐栏目",
                    "content": "娱乐内容1"
                }
            }
        ]
    }
}

调用查询接口,模糊查询出来一条数据,没问题
在这里插入图片描述
简单的操作就到这里了,后续我会将完整的一套ES仓储层实现代码上传github

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐