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(“cluster.name”, “<your_cluster_name_here>”).build();

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

}

public void tearDown(){
client.close();
}
/**
* @param args
*/
public static void main(String[] args) {
TestConnectES tc = new TestConnectES();
try {
tc.init();
tc.search();
tc.tearDown();
} catch (UnknownHostException e) {
e.printStackTrace();
}

}

 

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());
srb.setQuery(qb);

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());
}
}

 

}

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Categories

%d bloggers like this: