Settings settings = Settings.builder()
.put("cluster.name", "myClusterName").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
//Add transport addresses and do something with the client...
//client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), nodePort));
//
BulkRequestBuilder bulkRequest = client.prepareBulk();
bulkRequest.add(client.prepareIndex("index1", "type1", "id1").setSource(source);
bulkRequest.add(client.prepareIndex("index2", "type2", "id2").setSource(source);
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
BulkRequestBuilder?
允许批量提交index和delete请求
实现往ES中添加数据
public static void putEsIndex() {
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", "elasticsearch").build();
TransportClient client = null;
client = new TransportClient(settings);
try {
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.1.253"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
final BulkRequestBuilder bulkRequest = client.prepareBulk();
Map<String, Object> map = new HashMap<>();
map.put("filename", "Z_SURF_I_A5703_20170101000000_O_AWS_DAY.txt");
bulkRequest.add(client.prepareIndex("qx_file",
"qx_file",
"20170101/Z_SURF_I_A5703_20170101000000_O_AWS_DAY.txt").setSource(map));
bulkRequest.execute().actionGet();
}
实现读取ES的数据
public static void Search() {
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", "elasticsearch").build();
TransportClient client = null;
client = new TransportClient(settings);
try {
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.1.253"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.termsQuery("filename", "20170101000000"));
SearchRequestBuilder searchRequestBuilder = null;
searchRequestBuilder = client.prepareSearch("qx_file").setTypes("qx_file").setSearchType(SearchType.QUERY_THEN_FETCH);
// searchRequestBuilder.setQuery(qb);
// searchRequestBuilder.setFrom(0);
// searchRequestBuilder.setSize(size);
// searchRequestBuilder.addSort(sortBuilder);
SearchResponse searchRespons = searchRequestBuilder.execute().actionGet();
SearchHit[] hitArray = searchRespons.getHits().getHits();
for( int i = 0; i < hitArray.length; i++) {
System.out.println(hitArray[i].id());
}
}