【问题标题】:Elasticsearch NEST Reuse ElasticClient for different index queryElasticsearch NEST 重用 ElasticClient 进行不同的索引查询
【发布时间】:2019-08-04 15:11:49
【问题描述】:

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

【问题讨论】:

    标签: elasticsearch asp.net-core dependency-injection .net-core nest


    【解决方案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") 的全局规则中推断出来

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2013-04-26
      • 2022-07-02
      • 2017-12-29
      相关资源
      最近更新 更多