Posted by: bgopi | May 6, 2016

ElasticSearch using Java

Here is how to access ElasticSearch cluster from a java program:

public class TestConnectES{

public void init(){

Settings settings = Settings.settingsBuilder()
.put(“client.transport.sniff”, true)
.put(“”, “<your_cluster_name_here>”).build();

client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(“”), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(“”), 9300));


public void tearDown(){
* @param args
public static void main(String[] args) {
TestConnectES tc = new TestConnectES();
try {
} catch (UnknownHostException e) {



public void search(){

SearchRequestBuilder srb = client.prepareSearch(“<your_index_name_here>”);
String userQuery=”corporation”;
QueryBuilder qb = QueryBuilders.queryStringQuery(“_all:”+userQuery);//.defaultOperator(Operator.AND)
System.out.println(“Q: “+qb.toString());

SearchResponse searchResponse = srb.execute().actionGet();
SearchHit[] hits = searchResponse.getHits().getHits();

System.out.println(“Total hits: “+searchResponse.getHits().totalHits());
int showResults = hits.length > 10 ? 10:hits.length;

for(int i=0;i<showResults;i++){
System.out.println(“score: “+hits[i].getScore());
System.out.println(“source: “+hits[i].getSourceAsString());




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: