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、创建需要的实体
/// <summary>/// 数据/// </summary>public class EsData{/// <summary>/// 名称/// </summary>public string name { get; set; } = string.Empty;/// <summary>/// ,密码/// </summary>public string password { get; set; } = string.Empty;}/// <summary>/// 分词器/// </summary>public class EsAnalyzer{/// <summary>/// 名称/// </summary>public string analyzer { get; set; } = string.Empty;/// <summary>/// ,密码/// </summary>public string text { get; set; } = string.Empty;}
5、创建两个使用的方法
ps:查询方法和直接使用语句一样
分词器方法没有找到现成使用方法,所有直接http调用,效果一致
GET /testparticper/_search
{"query": {"term": {"name": "名称"}}
}
/// <summary>/// 获取索引/// </summary>/// <returns></returns>public string GetIndex(string name){ISearchResponse<EsData> esData = elasticClient.Search<EsData>(x =>{return x.Index(indexName).Query(q => q.Term("name", name));});return esData.Documents.ToJson();}/// <summary>/// 分词器/// </summary>/// <returns></returns>public string Analyze(string body){string str = new HttpTool().PostSendMessage("http://192.168.30.98:9200", "/_analyze", body);return str;}
6、es使用
/// <summary>/// es操作/// </summary>[Route("[controller]")][StartAutoWrite]public class ElasticsearchController : Controller{[AutoWrite]ElasticsearchTool? elasticsearch;/// <summary>/// 查询/// </summary>/// <returns></returns>// GET: api/values[HttpGet("exist")]public string Exist([FromQuery] string name){return elasticsearch?.GetIndex(name) ?? string.Empty;}/// <summary>/// 分词器/// </summary>/// <param name="esAnalyzer"></param>/// <returns></returns>[HttpPost("analyze")]public string Analyze([FromBody] EsAnalyzer esAnalyzer){return elasticsearch?.Analyze(esAnalyzer.ToJson()) ?? string.Empty;}}
7、响应效果