如何在.NET Core应用程序中将ElasticClient注册为单例,但仍然能够在查询期间指定其他索引?
例如:
在Startup.cs中,我仅通过提及URL而未指定索引来将弹性客户端对象注册为单例。
public void ConfigureServices(IServiceCollection services)
{
....
var connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200"));
var client = new ElasticClient(connectionSettings);
services.AddSingleton<IElasticClient>(client);
....
}
然后当在上面注入ElasticClient单例对象时,我想将其用于2个不同查询中的不同索引。
在下面的类中,我想从名为“ Apple”的索引进行查询
public class GetAppleHandler
{
private readonly IElasticClient _elasticClient;
public GetAppleHandler(IElasticClient elasticClient)
{
_elasticClient = elasticClient;
}
public async Task<GetAppleResponse> Handle()
{
// I want to query (_elasticClient.SearchAsync<>) using an index called "Apple" here
}
}
从下面的代码中,我想从名为“ Orange”的索引中进行查询
public class GetOrangeHandler
{
private readonly IElasticClient _elasticClient;
public GetOrangeHandler(IElasticClient elasticClient)
{
_elasticClient = elasticClient;
}
public async Task<GetOrangeResponse> Handle()
{
// I want to query (_elasticClient.SearchAsync<>) using an index called "Orange" here
}
}
我该怎么做?如果不可能,您是否可以建议其他方法允许我通过.NET Core依赖项注入来注入ElasticClient,同时还允许我从同一ES实例的2个不同索引中进行查询?
答案 0 :(得分:1)
只需在请求上指定索引
var defaultIndex = "person";
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(pool)
.DefaultIndex(defaultIndex)
.DefaultTypeName("_doc");
var client = new ElasticClient(settings);
var searchResponse = client.Search<Person>(s => s
.Index("foo_bar")
.Query(q => q
.Match(m => m
.Field("some_field")
.Query("match query")
)
)
);
此处的搜索请求为
POST http://localhost:9200/foo_bar/_doc/_search
{
"query": {
"match": {
"some_field": {
"query": "match query"
}
}
}
}
foo_bar
索引已在搜索请求中定义_doc
的全局规则推断出DefaultTypeName("_doc")
类型