【微服务】第29节: ElasticSearch的 RestClient查询&数据耦合
warning:
这篇文章距离上次修改已过262天,其中的内容可能已经有所变动。
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ElasticSearchExample
{
public class ElasticSearchService
{
private readonly ElasticClient _elasticClient;
public ElasticSearchService(ElasticClient elasticClient)
{
_elasticClient = elasticClient;
}
public async Task<IReadOnlyCollection<TDocument>> SearchAsync<TDocument>(string indexName, QueryContainer query)
where TDocument : class
{
var searchResponse = await _elasticClient.SearchAsync<TDocument>(s => s
.Index(indexName)
.Query(q => query)
);
return searchResponse.Documents;
}
}
}
这个代码示例展示了如何使用 NEST 库与 ElasticSearch 进行交互。ElasticSearchService
类中的 SearchAsync
方法接受索引名和查询对象,然后执行异步搜索操作,并返回结果。通过使用泛型,该方法可以用于搜索不同类型的文档。这种方法的好处是它解耦了服务与特定的文档模型,使得更改模型不会影响服务本身。
评论已关闭