ElasticSearch NEST操作(2)
基础知识
ElasticSeach 访问封装的服务类
IElasticSearch类的代码如下:
public interface IESSever
{
/// <summary>
/// Linq查询的官方Client
/// </summary>
IElasticClient ElasticLinqClient { get; set; }
/// <summary>
/// Js查询的官方Client
/// </summary>
IElasticLowLevelClient ElasticJsonClient { get; set; }
Task<Nest.CreateResponse> CreateAsync(Tmx2ESModel model);
}
ElasticSearch的方法实现
/// <summary>
/// 访问ElasticSearch服务类
/// </summary>
public class ESSever : IESSever
{
/// <summary>
/// Linq查询的官方Client
/// </summary>
public IElasticClient ElasticLinqClient { get; set; }
/// <summary>
/// Js查询的官方Client
/// </summary>
public IElasticLowLevelClient ElasticJsonClient { get; set; }
public ESSever(IConfiguration configuration)
{
var uris = configuration["ElasticSearchContext:ESUri"].Split(",").ToList().ConvertAll(x => new Uri(x));
var connectionPool = new StaticConnectionPool(uris);//配置请求池
var settings = new ConnectionSettings(connectionPool).RequestTimeout(TimeSpan.FromSeconds(30));//请求配置参数
settings.DisableDirectStreaming().DefaultIndex(configuration["ElasticSearchContext:ESIndexName"]);
this.ElasticJsonClient = new ElasticLowLevelClient(settings);//json请求客户端初始化
this.ElasticLinqClient = new ElasticClient(settings);//linq请求客户端初始化
}
/// <summary>
/// Creates the Tmx2ESModel asynchronous.
/// </summary>
/// <param name="model">The model.</param>
/// <returns></returns>
public Task<Nest.CreateResponse> CreateAsync(Tmx2ESModel model)
{
return ElasticLinqClient.CreateDocumentAsync(model);
}
/// <summary>
/// Creates the Tmx2ESModel asynchronous.
/// </summary>
/// <param name="model">The model.</param>
/// <returns></returns>
public Task<ISearchResponse<TDocument>> SearchAsync<TDocument>(Func<SearchDescriptor<TDocument>, ISearchRequest> selector = null, CancellationToken ct = default(CancellationToken)) where TDocument : class
{
return ElasticLinqClient.SearchAsync(selector);
}
}
注册服务
在startup里面在ConfigureServices下面添加如下代码即可
services.AddSingleton<IESSever, ESSever>();
账号密码
注:请求配置时,如果ElasticSearch需要账号密码时需要把settings修改为如下
var settings = new ConnectionSettings(connectionPool)
.BasicAuthentication("user", "password")
.RequestTimeout(TimeSpan.FromSeconds(30));
ElasticSearch 查询
private Task<Nest.ISearchResponse<Tmx2ESModel>> SearchAsyncStep(Tmx2ESModelInDto inModel, int page, int size)
{
var searchRequest = new SearchRequest<Tmx2ESModel>();
searchRequest.From = page;
searchRequest.Size = size;
var list = new List<QueryContainer>();
//.Suffix("keyword") 精准查询
if (!string.IsNullOrWhiteSpace(inModel.Condition.ClientGuid))
{
var clientGuid = new MatchQuery() { Field = Infer.Field<Tmx2ESModel>(f => f.ClientGuid.Suffix("keyword")), Query = inModel.Condition.ClientGuid };
list.Add(clientGuid);
}
//模糊查询
if (!string.IsNullOrWhiteSpace(inModel.Condition.SourceType))
{
var sourceType = new MatchQuery() { Field = Infer.Field<Tmx2ESModel>(f => f.SourceType), Query = inModel.Condition.SourceType };
list.Add(sourceType);
}
...
searchRequest.Query = new BoolQuery() { Must = list };
var searchResponse = _eSSever.ElasticLinqClient.SearchAsync<Tmx2ESModel>(searchRequest);
return searchResponse;
}
写入
public Task<Nest.CreateResponse> CreateAsync(Tmx2ESModel model)
{
return ElasticLinqClient.CreateDocumentAsync(model);
}
修改
var searchResponse = _eSSever.ElasticLinqClient.Search<Tmx2ESModel>(s => s
.Query(q => q
.Match(t => t
.Field(f => f.XliffSegmentGuid.Suffix("keyword")).Query(json.XliffSegmentGuid)
) && q
.Match(t => t
.Field(f => f.ServiceType.Suffix("keyword")).Query(json.ServiceType)
)
)
);
var resultData = searchResponse.Documents.ToList();
if (resultData.Count > 0)
{
//Update
foreach (var data in resultData)
{
log.Write(logKye, $"【Update】Query data, can be modified, XliffSegmentGuid:{data.XliffSegmentGuid}");
data.UpdateAt = json.UpdateAt;
data.UpdatedBy = json.UpdatedBy;
var resultUpdate = await _eSSever.ElasticLinqClient.UpdateAsync(DocumentPath<Tmx2ESModel>.Id(data.Id), selector => selector.Doc(data));
log.Write(logKye, $"【Update success】");
}
}