net8.0一键创建支持(Elastic)
Necore项目生成器 - 在线创建Necore模板项目 | 一键下载
ElasticController.cs
using CSRedis;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Nest;
using System.Threading.Tasks;
using UnT.Template.Application.Responses;
using UnT.Template.Domain;namespace UnT.Template.Controllers
{[Route("api/elastics")][ApiController]public class ElasticController : ControllerBase{private readonly ElasticClient _elasticClient;public ElasticController(ElasticClient elasticClient){_elasticClient = elasticClient;}[HttpPost("insert")][Produces("application/json")][ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]public async Task<IActionResult> Insert(){try{if (!_elasticClient.Indices.Exists("pro_products").Exists){var response = await _elasticClient.Indices.CreateAsync("pro_products", c => c.Map<Pro_Product>(m => m.AutoMap() // 自动映射.Properties(p => p.Number(n => n.Name(nn => nn.Id).Type(NumberType.Integer)).Text(t => t.Name(n => n.Name).Analyzer("ik_max_word")) // 使用中文分词器)));if (!response.IsValid){throw new Exception($"创建索引失败: {response.DebugInformation}");}}var responseCreateDoc = await _elasticClient.IndexAsync(new Pro_Product { Name = DateTime.Now.ToFileTime().ToString() }, i => i.Index("pro_products"));if (!responseCreateDoc.IsValid){throw new Exception($"索引文档失败: {responseCreateDoc.DebugInformation}");}return Ok(new ApiResponse<bool> { Success = true, Data = true });}catch (Exception ex){return Ok(new ApiResponse<bool> { Success = false, Message = ex.Message, Data = false });}}[HttpPost("count")][Produces("application/json")][ProducesResponseType(typeof(ApiResponse<int>), StatusCodes.Status200OK)]public async Task<IActionResult> Count(){try{var response = await _elasticClient.SearchAsync<Pro_Product>(s => s.Index("pro_products").Query(q => q.MatchAll()));if (!response.IsValid){throw new Exception($"搜索失败: {response.DebugInformation}");}var products = response.Documents;return Ok(new ApiResponse<int> { Success = true, Data = products.Count() });}catch (Exception ex){return Ok(new ApiResponse<int> { Success = false, Message = ex.Message });}}}
}