Skip to content

Instantly share code, notes, and snippets.

Created November 14, 2011 18:48
Show Gist options
  • Save thesurlydev/1364734 to your computer and use it in GitHub Desktop.
Save thesurlydev/1364734 to your computer and use it in GitHub Desktop.
factory for getting ES client
import org.apache.log4j.Logger;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.collect.ImmutableList;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import java.util.Map;
public class TransportClientFactory {
private static final Logger log = Logger.getLogger(TransportClientFactory.class);
private Map<String, String> settings;
private String clientTransportHost;
private Integer clientTransportPort;
private boolean disabled = false;
public TransportClientFactory(Map<String, String> settings,
String clientTransportHost,
Integer clientTransportPort,
boolean disabled) {
this.settings = settings;
this.clientTransportHost = clientTransportHost;
this.clientTransportPort = clientTransportPort;
this.disabled = disabled;
public TransportClient getClient() throws ElasticSearchUnavailableException {
if (this.disabled) {
throw new ElasticSearchUnavailableException("ES is disabled. Check 'es.disable' property");
}"getting client");
Settings s = ImmutableSettings.settingsBuilder()
TransportClient client = new TransportClient(s);
client.addTransportAddress(new InetSocketTransportAddress(
return client;
private void verifyConnection(TransportClient client) {
ImmutableList<DiscoveryNode> nodes = client.connectedNodes();
if (nodes.isEmpty()) {
throw new ElasticSearchUnavailableException("No nodes available. Verify ES is running!");
} else {"connected to nodes: " + nodes.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment