Elastic Search.NET -NEST使用(1)
Elastic Search.NET -NEST
Object Initializer 语法去构造查询
Match All query
最简单的查询应该就是 match_all
了,这种查询会返回所有的文档,并给每份文档的 _score
统一赋值为 1.0
匹配的文档并不是都会在一次响应中全部返回,默认情况下只返回前十份。你可以使用
from
和size
来将结果分页
var searchResponse = client.Search<Project>(s => s
.Query(q => q
.MatchAll()
)
);
上面使用 Fluent API 来描述查询。
NEST 还公开了一种 Object Initializer 语法去构造查询
var searchRequest = new SearchRequest<Project>
{
Query = new MatchAllQuery()
};
searchResponse = client.Search<Project>(searchRequest);
Search request parameters
search request 有一些可用的参数,你可以参阅 search 以获得详细的信息。
以下是一个示例:
var searchRequest = new SearchRequest<Tmx2ESModel>();
searchRequest.From = page;
searchRequest.Size = size;
var list = new List<QueryContainer>();
//optional
if (!string.IsNullOrWhiteSpace(inModel.ClientGuid))
{
//精准查询使用keyword
var clientGuid = new MatchQuery() { Field = Infer.Field<Tmx2ESModel>(f => f.ClientGuid.Suffix("keyword")), Query = inModel.ClientGuid };
list.Add(clientGuid);
}
searchRequest.Query = new BoolQuery() { Must = list };
var searchResponse = ESClient.Client.SearchAsync<Tmx2ESModel>(searchRequest);
在net core 注册ES
添加ESSever
/// <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);
}
}
在startup里面在ConfigureServices下面添加如下代码即可
services.AddSingleton<IESSever, ESSever>();