.net core 6 集成 elasticsearch 并 使用分词器

1、nuget包安装NEST、安装elasticsearch、kibana、ik分词器、拼音分词器

2、创建操作对象

//索引库
static string indexName = "testparticper";
//es 操作对象
ElasticClient elasticClient = new ElasticClient(new ConnectionSettings(new Uri("http://192.168.30.98:9200")));

3、创建一个索引库,字段使用ik分词器

#创建索引库
PUT /testparticper
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword",
        "index": false
      },
      "name": {
        "type": "text",
        "analyzer": "ik_smart",
        "copy_to": "all"
      },
      "password": {
        "type": "text",
        "index": false
      },
      "all": {
        "type": "text",
        "analyzer": "ik_smart"
      }
    }
  }
}

4、创建需要的实体

/// 
	/// 数据
	/// 
	public class EsData
	{
		/// 
		/// 名称
		/// 
		public string name { get; set; } = string.Empty;
		/// 
		/// ,密码
		/// 
		public string password { get; set; } = string.Empty;
	}

	/// 
	/// 分词器
	/// 
    public class EsAnalyzer
    {
        /// 
        /// 名称
        /// 
        public string analyzer { get; set; } = string.Empty;
        /// 
        /// ,密码
        /// 
        public string text { get; set; } = string.Empty;
    }

5、创建两个使用的方法

 ps:查询方法和直接使用语句一样

        分词器方法没有找到现成使用方法,所有直接http调用,效果一致

        

GET /testparticper/_search
{
  "query": {
    "term": {
      "name": "名称"
    }
  }
}
/// 
		/// 获取索引
		/// 
		/// 
		public string GetIndex(string name)
		{
            ISearchResponse esData = elasticClient.Search(x =>
			{
				 return x.Index(indexName).Query(q => q.Term("name", name));
			});

			return esData.Documents.ToJson();
		}

        /// 
        /// 分词器
        /// 
        /// 
        public string Analyze(string body)
        {
			string str = new HttpTool().PostSendMessage("http://192.168.30.98:9200", "/_analyze", body);
            return str;
        }

6、es使用

/// 
    /// es操作
    /// 
    [Route("[controller]")]
    [StartAutoWrite]
    public class ElasticsearchController : Controller
    {
        [AutoWrite]
        ElasticsearchTool? elasticsearch;

        /// 
        /// 查询
        /// 
        /// 
        // GET: api/values
        [HttpGet("exist")]
        public string Exist([FromQuery] string name)
        {
            return elasticsearch?.GetIndex(name) ?? string.Empty;
        }

        /// 
        /// 分词器
        /// 
        /// 
        /// 
        [HttpPost("analyze")]
        public string Analyze([FromBody] EsAnalyzer esAnalyzer)
        {
            return elasticsearch?.Analyze(esAnalyzer.ToJson()) ?? string.Empty;
        }
    }

7、响应效果

.net core 6 集成 elasticsearch 并 使用分词器_第1张图片

你可能感兴趣的:(.netcore,elasticsearch)