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

Elasticsearch NEST Reuse ElasticClient for different index query

如何在 .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 个不同查询中的不同索引。

在下面的 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 依赖项注入来注入 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")
  • 上的全局规则中推断出来