前提条件:
1、安装elasticsearch5.5.1版本,因为本示例是基于该版本上进行的
2、elasticsearch客户端的jar包对应elasticsearch版本也是5.5.1
在maven项目中添加以下配置即可:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
接下来就是java代码的演示,废话不说,直接粘代码!其他的就不讲解了,功能描述请看注解!
/**
* 实例化一个TransportClient对象
* @return
*/
public static TransportClient getTransportClient(){
//如果cluter-name不是默认的elasticsearch,则需要设置为自定义的名称
/*Settings settings = Settings.builder()
.put("cluster.name", "myClusterName").build();
TransportClient client = new PreBuiltTransportClient(settings);*/
//获取实例,连接本地es节点,可添加多个节点
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("localhost", 9300)));
return client;
}
/**
* 生成索引
*/
public static void generateIndex() {
TransportClient client = getTransportClient();
//ES仅支持json格式的数据存储和传输
Map
json = new HashMap
();
json.put("user","kimchy");
json.put("postDate", new Date());
json.put("message","trying out Elasticsearch");
IndexResponse indexResponse = client.prepareIndex("twitter", "tweet", "1")
.setSource(json).get();
// Index name
String _index = indexResponse.getIndex();
// Type name
String _type = indexResponse.getType();
// Document ID (generated or not)
String _id = indexResponse.getId();
// Version (if it's the first time you index this document, you will get: 1)
long _version = indexResponse.getVersion();
// status has stored current instance statement.
RestStatus status = indexResponse.status();
System.out.println("Index name:" + _index + " Type name:" + _type + " Document ID:" + _id + " Version:" + _version + " status:" + status);
}
/**
* 查询索引
*/
public static void getIndex() {
TransportClient client = getTransportClient();
//默认操作是异步的,可设置OperationThreaded为false
GetResponse response = client.prepareGet("twitter", "tweet", "1").setOperationThreaded(false).get();
String json = response.getSourceAsString();
System.out.println("json:" + json);
Map
rpMap = response.getSource();
if (rpMap == null) {
System.out.println("empty");
return;
}
Iterator
> rpItor = rpMap.entrySet().iterator(); while (rpItor.hasNext()) { Entry
rpEnt = rpItor.next(); System.out.println(rpEnt.getKey() + " : " + rpEnt.getValue()); } } /** * 删除索引 */ public static void delelteIndex() { TransportClient client = getTransportClient(); DeleteResponse response = client.prepareDelete("twitter", "tweet", "1").get(); } /** * 更新索引 */ public static void updateIndex() { TransportClient client = getTransportClient(); Map
json = new HashMap
(); json.put("user","hefunuan"); json.put("postDate", new Date()); json.put("message","I'm a human"); UpdateResponse response = client.prepareUpdate("twitter", "tweet", "1").setDoc(json).get(); } /** * 索引不存在则创建该索引,否则更新 * @throws ExecutionException * @throws InterruptedException */ public static void upsertIndex() throws InterruptedException, ExecutionException { TransportClient client = getTransportClient(); Map
json = new HashMap
(); json.put("user","hefunuan"); json.put("postDate", new Date()); json.put("message","I'm a human"); IndexRequest indexRequest = new IndexRequest("index", "type", "1").source(json); UpdateRequest updateRequest = new UpdateRequest("index", "type", "1").doc(json).upsert(indexRequest); client.update(updateRequest).get(); GetResponse response = client.prepareGet("index", "type", "1").get(); String s = response.getSourceAsString(); System.out.println("json:" + s); } /** * 根据所条件获取索引列表 */ public static void multiGetIndexs() { TransportClient client = getTransportClient(); MultiGetResponse multiGetItemResponses = client.prepareMultiGet() .add("twitter", "tweet") //.add("twitter", "tweet", "2", "3", "4") //.add("index", "type", "1") .get(); for (MultiGetItemResponse itemResponse : multiGetItemResponses) { GetResponse response = itemResponse.getResponse(); if (response.isExists()) { String json = response.getSourceAsString(); System.out.println("json:" + json); } } } /** * 批量操作 */ public static void batchGanerateIndex() { TransportClient client = getTransportClient(); BulkRequestBuilder bulkRequest = client.prepareBulk(); for(int i = 5 ; i < 10 ; i++){ Map
json = new HashMap
(); json.put("user",i); json.put("postDate", new Date()); json.put("message","I'm a human"); json.put("height", i + 5); bulkRequest.add(client.prepareIndex("twitter", "tweet", Integer.toString(i)).setSource(json)); } BulkResponse bulkResponse = bulkRequest.get(); if(bulkResponse.hasFailures()){//检测是否有失败的操作 System.out.println(bulkResponse.getItems().toString()); } } /** * 查询多个索引、类型 */ public static void searchIndex() { TransportClient client = getTransportClient(); SearchResponse response = client.prepareSearch("twitter") .setTypes("tweet") //.setQuery(QueryBuilders.termQuery("message", "I'm a human")) // Query //.setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18)) // Filter .setFrom(0).setSize(60).setExplain(true) .addSort("height", SortOrder.ASC) .get(); for (SearchHit hit : response.getHits()) { Iterator
> rpItor = hit.getSource().entrySet().iterator(); while (rpItor.hasNext()) { Entry
rpEnt = rpItor.next(); System.out.println(rpEnt.getKey() + " : " + rpEnt.getValue()); } } /*SearchRequestBuilder srb1 = client .prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setSize(1); SearchRequestBuilder srb2 = client .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1); MultiSearchResponse sr = client.prepareMultiSearch() .add(srb1) .add(srb2) .get(); // You will get all individual responses from MultiSearchResponse#getResponses() long nbHits = 0; for (MultiSearchResponse.Item item : sr.getResponses()) { SearchResponse response = item.getResponse(); nbHits += response.getHits().getTotalHits(); }*/ client.close(); } /** * 聚合操作 */ public static void aggregationRequest() { TransportClient client = getTransportClient(); //最小聚合、最大聚合、合计聚合、平均聚合、数值聚合、百分位、基数聚合、地理边界聚合、等 /*MinAggregationBuilder aggregation = AggregationBuilders.min("agg").field("height"); SearchResponse searchResponse = client.prepareSearch("twitter").setTypes("tweet").addAggregation(aggregation).get(); Min min = searchResponse.getAggregations().get("agg"); double minValue = min.getValue(); System.out.println(minValue);*/ //统计聚合 StatsAggregationBuilder statsAggregationBuilder = AggregationBuilders.stats("zidingyi").field("height"); SearchResponse sr = client.prepareSearch("twitter").setTypes("tweet").addAggregation(statsAggregationBuilder).execute().actionGet(); Stats zidingyi = sr.getAggregations().get("zidingyi"); double min = zidingyi.getMin(); double max = zidingyi.getMax(); double avg = zidingyi.getAvg(); double sum = zidingyi.getSum(); long count = zidingyi.getCount(); System.out.println("min->" + min + "max->" + max + "avg->" + avg + "sum->" + sum + "count->" + count); client.close(); } /** * DSL查询,支持复杂查询 */ public static void matchQuery() { TransportClient client = getTransportClient(); //SearchResponse sr = client.prepareSearch().setQuery(QueryBuilders.matchQuery("user", "hefunuan")).get(); SearchResponse sr = client.prepareSearch().setQuery(QueryBuilders.queryStringQuery("I'm a human")).get(); for (SearchHit hit : sr.getHits()) { Iterator
> rpItor = hit.getSource().entrySet().iterator(); while (rpItor.hasNext()) { Entry
rpEnt = rpItor.next(); System.out.println(rpEnt.getKey() + " : " + rpEnt.getValue()); } } }