gpt4 book ai didi

Elasticsearch NEST 重用 ElasticClient 进行不同的索引查询

转载 作者:行者123 更新时间:2023-12-03 01:32:09 26 4
gpt4 key购买 nike

如何在 .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);
....
}

然后在上面注入(inject) ElasticClient 单例对象时,我想将它用于 2 个不同查询中的不同索引。

在下面的类(class)中,我想从一个名为“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 依赖注入(inject)注入(inject) ElasticClient,同时还允许我从同一个 ES 实例的 2 个不同索引进行查询?

最佳答案

只需要在请求上指定索引

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") 上的全局规则中推断出来
  • 关于Elasticsearch NEST 重用 ElasticClient 进行不同的索引查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55150412/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com