Connectin to ElasticSearch with JavaApi in production

Hi,

Let's look at this class:

 public class ESConnector
{ 
private Client client;
public Client getClient()
{
    if(client == null)
    {
        client = createClient();
    }
    
    return client;
}
 
protected Client createClient()
{
    if(client == null)
    {
        
        try
        {
            Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "test").build();
            
            TransportClient transportClient = new TransportClient(settings);
            transportClient = transportClient.addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
             
            client = transportClient;
        }
        catch(Exception ex)
        { 
            logger.error(ex, ex);
        }
    }
    return client;

}

This class is from some example. It is a singleton, so every time I want to search something in realtime I don't need to connecto to the ElasticSearch server. I wonder if it can be used in real production environment?

What if:

  • There is restart of ElasticSearch server? Would this connection be able to search something after the restart?
  • There are many threads using this connection - would they wait for each other and how to cope with this?
  • There are couple of nodes in cluster

How good connector class would look like? Maybe you could share some example basing on your code that is proven on production?

Guys, nobody has any example on how you connect to ES in real production code using Java API?

This is a one of the possible ways to create a single TransportClient instance, but do note that if multiple threads call getClient concurrently, you may end up with more than one transport client instance created, as getClient and createClient are not thread-safe. In a lot of cases people let their dependency injection framework create the instance at startup I guess.

If you create an instance of the transport client that connects to the cluster, it will return no node available error when there are no nodes to connect to, in case you are restarting the cluster, but it will go back to work once there is some node to talk to in the cluster.

About many threads, TransportClient is thread-safe, just worry about making the creation of the singleton instance thread-safe.