增加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; //创建索引库 public static void createIndex(String index){ CreateIndexResponse createIndexResponse = client.admin().indices().prepareCreate(index).get(); System.out.println(createIndexResponse.isAcknowledged()); // true表示成功 } //给索引库增加 type,mapping public static void addMapping(String index,String type) throws Exception{ // 使用XContentBuilder创建Mapping XContentBuilder 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表示成功 } //创建文档 public static void createDoc(String index, String type) throws Exception { // 使用XContentBuilder创建一个doc source XContentBuilder builder = XContentFactory.jsonBuilder() .startObject() .field("user_id", "1") .field("name", "name1") .field("age", "1") .endObject(); // setId(id) 如果没有设置id,则ES会自动生成一个id setSource 可以是XContentBuilder,map,json,javabeans等 IndexResponse indexResponse = client.prepareIndex().setIndex(index).setType(type).setId("1").setSource(builder.string()).get(); } //根据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()); } } } //根据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(); } //根据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()); } //聚和函数 求平均年龄 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(); //获取查询结果集 SearchHits searchHits = searchResponse.getHits(); System.out.println("共搜到:"+searchHits.getTotalHits()+"条结果!"); SearchHit[] hits2 = searchHits.getHits(); //遍历结果 for(SearchHit hit:hits2){ System.out.println("String方式打印文档搜索内容:"); System.out.println(hit.getSourceAsString()); System.out.println("Map方式打印高亮内容"); 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 { // 设置集群名称 Settings settings = Settings.builder().put("cluster.name", "my-es").build(); // 创建client client = 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); } }
原文地址:https://www.cnblogs.com/zengnansheng/p/10389722.html
时间: 2024-10-09 00:08:59