1

How can I register ElasticClient as singleton in a .NET Core application but still able to specify the different index during the query?

For example:

In Startup.cs I register an elastic client object as singleton, by only mentioning the URL without specifying the index.

public void ConfigureServices(IServiceCollection services)
{
    ....
    var connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200"));
    var client = new ElasticClient(connectionSettings);
    services.AddSingleton<IElasticClient>(client);
    ....
}

Then when injecting ElasticClient singleton object above, I would like to use it for different indices in 2 different queries.

In the class below, I want to query from an index called "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
    }
}

From code below I want to query from an index called "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
    }
}

How can I do this? If it's not possible, can you suggest other approach that will allow me to inject ElasticClient through .NET Core dependency injection and at the same time also allow me to query from 2 different indices of the same ES instance?

1 Answer 1

3

Just need to specify the index on the request

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")
        )
    )
);

Here the search request would be

POST http://localhost:9200/foo_bar/_doc/_search
{
  "query": {
    "match": {
      "some_field": {
        "query": "match query"
      }
    }
  }
}
  • foo_bar index has been defined in the search request
  • _doc type has been inferred from the global rule on DefaultTypeName("_doc")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.