同事偷偷塞了个链接给我
创建ElasticClient对象
public interface IEsClientProvider
{
ElasticClient GetClient(string defaultIndex);
}
public class EsClientProvider : IEsClientProvider
{
//封装的接口
private readonly IConfiguration _configuration;
private ElasticClient _client;
public EsClientProvider(IConfiguration configuration)
{
_configuration = configuration;
}
public ElasticClient GetClient(string defaultIndex)
{
if (_client != null)
return _client;
InitClient(defaultIndex);
return _client;
}
private void InitClient(string defaultIndex, string userName = "uid", string passWord = "pwd")
{
//设置节点路径
var node = new Uri(_configuration["EsUrl"]);
//设置配置参数
var settings = new ConnectionSettings(node)
//设置用户名跟密码 (没有就不需要添加此参数)
.BasicAuthentication(userName,passWord)
//设置索引
.DefaultIndex(defaultIndex)
//设置超时时间
.RequestTimeout(TimeSpan.FromSeconds(20));
}
}
public class Car
{
public long Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Type { get; set; }
public string Color { get; set; }
}
private readonly ElasticClient _client;
public ValuesController(IEsClientProvider clientProvider)
{
_client = clientProvider.GetClient();
}
方法解析
// 查找单列Match 指定列FieId 多列MultiMatch 指定多列 Fields 下查询 Query
_client.Search<Car>(s =>
s.Query(
q => q.Match(
m => m.Field(f => f.Type).Query("奥迪")
)
)
);
// Range 下 LessThan小于 LessThanOrEquals小于等于 GreaterThanOrEquals大于等于 GreaterThan大于
_client.Search<Car>(s =>
s.Query(
q => q.Range(
m => m.Field(f => f.Type).LessThanOrEquals(12)
)
)
);
//添加数据对象
_client.IndexDocument(new Car()
{
Color = "Black",
Type = "奥迪",
Id = 1,
Name = "A8",
Price = 123121
});
//删除该数据对象 根据Id删除
_client.Delete<Car>(1);