'ElasticSearch.NET connection/client management lifecycle

When I set up a connection to my ElasticSearch cluster using ElasticSearch.NET, I am using a code block like the following:

var uris = settingsProvider.ElasticSearchUri.Split(';').Select(x => new Uri(x));
var sniffingConnectionPool = new SniffingConnectionPool(uris);
var connectionConfiguration =
    new ConnectionConfiguration(sniffingConnectionPool)
        .SniffOnConnectionFault()
        .SniffOnStartup();
var client = new ElasticsearchClient(settings: connectionConfiguration);

Is it recommended that I memoize/make static/make a singleton wrapper for the ElasticsearchClient, the ConnectionConfiguration, or the SniffingConnectionPool so that they don't have to be reconstructed each time I search?



Solution 1:[1]

I've not seen anything in the documentation to advise otherwise, but generally I would err on the side of caution and avoid the singleton as the docs also make no promises about thread-safety. Be sure to dispose anything IDisposable, and if you're worried about performance or memory usage use a profiler to determine where to target your efforts.

Solution 2:[2]

We noticed that when using the Sniffing takes between 800ms and 1.2s longer for the search in a 5 node cluster. We thought we'd do a singleton so that we only sniff once. and set .SniffOnConnectionFault(true) then if the Node it Sniffed goes away it will pick another if I'm understanding that correctly.

Has anyone used this pattern and is there a better way since sniffing is so slow?

Solution 3:[3]

This is an old post, but this info might help someone. The Elasticsearch documentation says:

In general we advise folks to register their ElasticClient instances as singletons. The client is thread safe so sharing an instance between threads is fine.

https://www.elastic.co/guide/en/elasticsearch/client/net-api/2.x/lifetimes.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 batwad
Solution 2 user369758
Solution 3 Csaba Kiss