ElasticSearch之Java Api 测试
生活随笔
收集整理的這篇文章主要介紹了
ElasticSearch之Java Api 测试
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
增加Maven依賴? ? ?
<dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>5.0.0</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>transport</artifactId><version>5.0.0</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.7</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.7</version></dependency><dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.0</version> </dependency>?
?
src/main/resource下增加log4j2.properties
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
rootLogger.level = info
rootLogger.appenderRef.console.ref = console
?
package com.zns.test;import java.net.InetAddress; import java.util.Map; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Requests; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.metrics.avg.Avg; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.transport.client.PreBuiltTransportClient;public class MyTest { public static TransportClient client=null;//創(chuàng)建索引庫public static void createIndex(String index){CreateIndexResponse createIndexResponse = client.admin().indices().prepareCreate(index).get();System.out.println(createIndexResponse.isAcknowledged()); // true表示成功 }//給索引庫增加 type,mappingpublic static void addMapping(String index,String type) throws Exception{// 使用XContentBuilder創(chuàng)建MappingXContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("properties").startObject().field("user_id").startObject().field("type", "integer").endObject().field("name").startObject().field("analyzer", "standard").field("type", "text").endObject().field("age").startObject().field("type", "integer").endObject().endObject().endObject();System.out.println(builder.string()); PutMappingRequest mappingRequest = Requests.putMappingRequest(index).source(builder).type(type);client.admin().indices().putMapping(mappingRequest).actionGet();}//刪除索引庫public static void deleteIndex(String index){DeleteIndexResponse deleteIndexResponse = client.admin().indices().prepareDelete(index).get();System.out.println(deleteIndexResponse.isAcknowledged()); // true表示成功 }//創(chuàng)建文檔public static void createDoc(String index, String type) throws Exception {// 使用XContentBuilder創(chuàng)建一個doc sourceXContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("user_id", "1").field("name", "name1").field("age", "1").endObject();// setId(id) 如果沒有設(shè)置id,則ES會自動生成一個id setSource 可以是XContentBuilder,map,json,javabeans等IndexResponse indexResponse = client.prepareIndex().setIndex(index).setType(type).setId("1").setSource(builder.string()).get(); }//根據(jù)ID查詢文檔public static String getById(String index, String type, String id) {GetResponse getResponse = client.prepareGet().setIndex(index).setType(type).setId(id).get();return getResponse.getSourceAsString();}//查詢文檔public static void query(String index, String type) {SearchResponse response = client.prepareSearch(index).setTypes(type).setSearchType(SearchType.DFS_QUERY_THEN_FETCH)//.setQuery(QueryBuilders.termQuery("user_id", "1"))//.setQuery(QueryBuilders.rangeQuery("user_id").lte("100"))//.setQuery(QueryBuilders.rangeQuery("age").from(1).to(18)).setFrom(0).setSize(10).setExplain(true).get();SearchHits hits = response.getHits();System.out.println(hits.getHits().length);SearchHit[] hits1 = hits.getHits();for(SearchHit hit :hits1){// ID 為hit.getId();Map<String, Object> source = hit.getSource();for(Map.Entry<String,Object> filed :source.entrySet()){String key = filed.getKey();System.out.println("key===="+key+" value====="+filed.getValue().toString());}}}//根據(jù)ID更新文檔public static void updateById(String index, String type, String id) throws Exception { XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("user_id", "1").field("name", "name222").field("age", "1").endObject(); UpdateResponse updateResponse = client.prepareUpdate(index, type, id).setDoc(builder).get(); }//根據(jù)ID刪除文檔public static void deleteById(String index, String type, String id) {DeleteResponse deleteResponse =client.prepareDelete() .setIndex(index).setType(type).setId(id).get();System.out.println(deleteResponse.status());} //聚和函數(shù) 求平均年齡public static void juheTest(String index,String type){SearchResponse response = client.prepareSearch(index).setTypes(type).addAggregation(AggregationBuilders.avg("xxx").field("age")).get();Avg avg = response.getAggregations().get("xxx");System.out.println(avg.getValue());}//批量增加操作public static void bulkAddTest(String index,String type) throws Exception{BulkRequestBuilder bulkRequest = client.prepareBulk(); XContentBuilder builder1 = XContentFactory.jsonBuilder().startObject().field("user_id", "11").field("name", "name11").field("age", "11").endObject();bulkRequest.add(client.prepareIndex().setIndex(index).setType(type).setId("11").setSource(builder1.string()));XContentBuilder builder2 = XContentFactory.jsonBuilder().startObject().field("user_id", "22").field("name", "name22").field("age", "22").endObject();bulkRequest.add(client.prepareIndex().setIndex(index).setType(type).setId("22").setSource(builder2.string()));BulkResponse bulkResponse = bulkRequest.get(); if (bulkResponse.hasFailures()) { // process failures by iterating through each bulk response item } }//高亮public static void highlightTest(String index,String type,String keyword,Integer from,Integer size){HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.preTags("<span style=\"color:red\">");highlightBuilder.postTags("</span>");highlightBuilder.field("*");highlightBuilder.requireFieldMatch(false);SearchRequestBuilder builder = client.prepareSearch(index);builder.setTypes(type);builder.setFrom(from);builder.setSize(size);builder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); builder.setExplain(true); builder.setQuery(QueryBuilders.multiMatchQuery(keyword,"name")); builder.highlighter(highlightBuilder);SearchResponse searchResponse = builder.get(); //獲取查詢結(jié)果集SearchHits searchHits = searchResponse.getHits();System.out.println("共搜到:"+searchHits.getTotalHits()+"條結(jié)果!");SearchHit[] hits2 = searchHits.getHits();//遍歷結(jié)果for(SearchHit hit:hits2){System.out.println("String方式打印文檔搜索內(nèi)容:");System.out.println(hit.getSourceAsString());System.out.println("Map方式打印高亮內(nèi)容");System.out.println(hit.getHighlightFields());System.out.println("遍歷高亮集合,打印高亮片段:");Text[] text = hit.getHighlightFields().get("name").getFragments();for (Text str : text) {System.out.println(str.string());}}}public static void main(String[] args) throws Exception {// 設(shè)置集群名稱Settings settings = Settings.builder().put("cluster.name", "my-es").build();// 創(chuàng)建clientclient = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));String index="znsindex";String type="znstype";//createIndex(index);//addMapping(index,type);//deleteIndex(index);//createDoc(index, type);//String result=getById(index, type, "1");//System.out.println(result); //deleteById(index, type, "1");//updateById(index, type, "1");//juheTest(index, type); //bulkAddTest(index, type);//highlightTest(index, type,"name1",0,10);//query(index, type); } }?
轉(zhuǎn)載于:https://www.cnblogs.com/zengnansheng/p/10389722.html
總結(jié)
以上是生活随笔為你收集整理的ElasticSearch之Java Api 测试的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vscode安装设置go
- 下一篇: 程序员委托事件学习随笔