本项目代码已发布在https://gitee.com/lucyliang01/esapi.git
NEST客户端在WebApi项目中的使用
NEST客户端在WebApi项目中的使用
NEST是elastic search为.net 提供的高级客户端依赖组件。
这里我们会建一个web api2项目,进行演示在.net中使用NEST实现文档的增删改查和全文检索
创建web api项目
创建web api2项目,并且修改属性目标框架为.net framework 4.6.1
在nuget中找到NEST依赖,并且安装目前版本7.10.1
创建 ESHelper帮助类文件
配置链接
这里因为对es的连接设置成private static只在创建的时候初始化一次
//单机连接的方式,默认使用articles索引
private static ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200")).DefaultIndex("articles");
//创建client
private static ElasticClient client = new ElasticClient(settings);
使用attribute自动映射
根据映射的字段创建类Article,并且使用attribute规定映射规则。
1)Number 表示字段类型为数字
2)Text 表示字段类型为字符串,可以进行索引
Analyzer 可以规定索引时的分词工具
Index 为true表示建立索引,并且可以被检索
3)Keyword 表示字段类型为字符串,但是不可以进行索引
4)Date 表示字段类型为日期
[ElasticsearchType(RelationName = "articles")]
public class Article
{
/// <summary>
/// id
/// </summary>
[Number]
public long Id { get; set; }
/// <summary>
/// 标题
/// </summary>
[Text(Analyzer = "ik_max_word", Index = true)]
public string Title { get; set; }
/// <summary>
/// 类型 新闻还是招聘
/// </summary>
[Keyword]
public string Type { get; set; }
/// <summary>
/// 内容
/// </summary>
[Text(Analyzer = "ik_max_word", Index = true)]
public string Content { get; set; }
/// <summary>
/// 新闻作者
/// </summary>
[Keyword]
public string Author { get; set; }
/// <summary>
/// 招聘公司
/// </summary>
[Text(Analyzer = "ik_max_word", Index = true)]
public string Company { get; set; }
/// <summary>
/// 招聘公司地址
/// </summary>
[Text(Analyzer = "ik_max_word", Index = true)]
public string CompanyAddress { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[Date]
public DateTime CreateTime { get; set; }
/// <summary>
/// 访问路径
/// </summary>
[Keyword]
public string WebPath { get; set; }
}
创建映射
在ESHelper中创建映射的方法
/// <summary>
/// 创建映射
/// </summary>
/// <returns></returns>
public static bool CreateMapping()
{
try
{
//映射
CreateIndexResponse createIndexResponse = client.Indices.Create("articles", c => c.Map<Article>(m => m.AutoMap()));
return true;
}
catch (Exception ex)
{
return false;
}
}
在ESController中创建webapi对创建索引的请求
/// <summary>
/// 创建映射
/// </summary>
/// <returns></returns>
[HttpPost, Route("mapping")]
public IHttpActionResult Mapping()
{
return Ok(ESHelper.CreateMapping());
}
创建或者修改单个文档
在ESHelper中创建文档,并且在ESController中创建添加文档的接口,使用postman进行测试
/// <summary>
/// 创建单个文档
/// </summary>
/// <param name="client"></param>
/// <param name="article"></param>
/// <returns></returns>
public static dynamic CreateArticle(Art