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

问题描述 投票:0回答:1

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

从下面的代码我想从一个名为“橙色”的索引查询

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个不同索引进行查询?

elasticsearch asp.net-core dependency-injection .net-core nest
1个回答
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")的全球规则中推断出来
© www.soinside.com 2019 - 2024. All rights reserved.