赞
踩
引入pom依赖
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.0</version>
</dependency>
测试类
package com.elasticsearch.utils; import com.alibaba.fastjson.JSON; import com.configserver.uitis.StringUtils; import com.elasticsearch.pojo.Lexer; import org.apache.http.HttpHost; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.*; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.search.sort.SortOrder; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; /** * Elasticserach RestClient示例 * @author liudean * */ public class ESTest { // 初始化api客户端 public static RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("192.XXX.XX.XX",9200, "http") )); /** * 封装查询条件,可以直接调用 * @throws Exception */ public static BoolQueryBuilder queryBuilderData(String name,String text){ BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery(); //filter 效率比 must高的多 // if (StringUtils.isNull(aa)) { // queryBuilder.filter(QueryBuilders.termQuery("routerDatabaseNo", aa)); // } if(!StringUtils.isNull(name)) { boolBuilder.must(QueryBuilders.matchPhraseQuery("createName", name)); } if(!StringUtils.isNull(text)) { boolBuilder.must(QueryBuilders.matchPhraseQuery("text", text)); } return boolBuilder; } public static void main(String[] args) throws Exception{ //findUserName("liu","3"); CreateDocument(); //ExistIndex(); //DeleteIndex(); //IsExists(); //getDocument(); //updateDocument(); //deleteDocument(); } /** * 判断索引是否存在 * @throws Exception */ public static void ExistIndex()throws Exception{ GetIndexRequest request = new GetIndexRequest("test"); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists); } /** * 删除索引 * @throws Exception */ public static void DeleteIndex()throws Exception{ DeleteIndexRequest request = new DeleteIndexRequest("test"); AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT); System.out.println(delete.isAcknowledged()); //为true表示删除成功 } /** * 添加文档 * @throws Exception */ public static void CreateDocument()throws Exception{ //Lexer是实体类 对应的就是es的字段名 Lexer Bean = new Lexer(); Bean.setCreateName("liu"); Bean.setCreateDate(StringUtils.getDateSecond()); Bean.setText("ceshi"); Bean.setJsonData("json"); Bean.setLoginfo("log"); Bean.setProcedureInfo("pro"); //test指的是你的索引名 IndexRequest request = new IndexRequest("test"); //设置规则 例如相当于 PUT /test/_doc/1 命令 request.id("1").timeout(TimeValue.timeValueSeconds(1));//设置id,1秒超时 request.timeout("1s"); // 数据转换成json 放入请求 request.source(JSON.toJSONString(Bean), XContentType.JSON); //将请求发出去,获取响应结果 IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); System.out.println(indexResponse.status()); // 返回当前操作的类型:CREATE System.out.println(indexResponse.toString()); //响应内容 } /** * 判断文档是否存在 * @throws Exception */ public static void IsExists()throws Exception{ GetRequest getRequest = new GetRequest("test", "1"); // 不获取返回的_source 的上下文,会提高速度 getRequest.fetchSourceContext(new FetchSourceContext(false)); getRequest.storedFields("_none_"); boolean exists = client.exists(getRequest, RequestOptions.DEFAULT); System.out.println(exists); } /** * 获取文档的信息 相当于GET /test/_doc/1 * @throws Exception */ public static void getDocument()throws Exception{ GetRequest getRequest = new GetRequest("lexer", "1"); GetResponse response = client.get(getRequest, RequestOptions.DEFAULT); System.out.println(response.getSourceAsString()); //获取文档的内容 } /** * 根据条件获取文档 * @throws Exception */ public static void findUserName(String name,String text){ RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder(); //设置连接的库名 即_index 你的索引名是啥 SearchRequest searchRequest = new SearchRequest("lexer"); /// 搜索源构建对象 SearchSourceBuilder search = new SearchSourceBuilder(); //多条件查询 BoolQueryBuilder boolBuilder=QueryBuilders.boolQuery(); //区间查询 //boolBuilder.must(QueryBuilders.rangeQuery("timestamp.keyword").gte(user.getStarttime()).lte(user.getEndtime())); //精确查询 //boolBuilder.must(QueryBuilders.termQuery("fraction", user.getFraction)); //模糊查询 //boolBuilder.must(QueryBuilders.matchPhraseQuery("userName", user.getUsername())); //查询createName if(!StringUtils.isNull(name)) { boolBuilder.must(QueryBuilders.matchPhraseQuery("createName", name)); } //根据text wildcardQuery 这个是模糊查询 字符串+"*" //StringUtils.isNull 这个是我自己封装验证字符串为空的方法 if(!StringUtils.isNull(text)) { boolBuilder.must(QueryBuilders.matchPhraseQuery("text", text)); } String keyword = ".keyword";//使用 term 查询,然后通过 .keyword 取消分词就可做到完全匹配查询 //根据text if(!StringUtils.isNull(text)) { boolBuilder.must(QueryBuilders.termQuery("text"+keyword, text)); } //按照日期排序,如果不需要排序可以删掉 search.sort("createDate.keyword", SortOrder.DESC); search.query(boolBuilder); searchRequest.source(search); SearchResponse response = null; try { //RequestOptions.DEFAULT response = client.search(searchRequest, options.build()); } catch (IOException e) { } SearchHits hits = response.getHits(); String totalNumber =String.valueOf(hits.getTotalHits()); System.out.println(totalNumber); Map<String, Object> sourceAsMap= null; for (SearchHit hit :hits.getHits()) { sourceAsMap = hit.getSourceAsMap(); System.out.println(sourceAsMap); } } /** * 更新文档信息 * @throws Exception */ public static void updateDocument()throws Exception{ UpdateRequest request = new UpdateRequest("test", "1"); request.timeout("1s"); Lexer Bean = new Lexer(); Bean.setCreateDate(String.valueOf(System.currentTimeMillis())); Bean.setText("setText"); Bean.setJsonData("setJsonData"); Bean.setLoginfo("setLoginfo"); Bean.setProcedureInfo("setProcedureInfo"); request.doc(JSON.toJSONString(Bean), XContentType.JSON); UpdateResponse response = client.update(request, RequestOptions.DEFAULT); System.out.println(response.status()); //成功返回 OK System.out.println(response.toString()); } /** * 删除文档信息 * @throws Exception */ public static void deleteDocument()throws Exception{ DeleteRequest request = new DeleteRequest("lexer", "1"); request.timeout("1s"); DeleteResponse response = client.delete(request, RequestOptions.DEFAULT); System.out.println(response.status()); //成功返回 OK System.out.println(response.toString()); } /** * 批量操作 * @throws Exception */ public static void BulkRequest()throws Exception{ BulkRequest request = new BulkRequest(); request.timeout("10s"); ArrayList<Object> list = new ArrayList<>(); Lexer Bean1 = new Lexer(); Lexer Bean2 = new Lexer(); Lexer Bean3 = new Lexer(); list.add(Bean1); list.add(Bean2); list.add(Bean3); //批量请求,批量更新,删除都差不多!!!不设置id就会自动生成随机id,演示为批量插入 for (int i = 0; i < list.size(); i++) { request.add(new IndexRequest("test") .id("" + (i + 1)) .source(JSON.toJSONString(list.get(i)), XContentType.JSON)); } BulkResponse response = client.bulk(request, RequestOptions.DEFAULT); System.out.println(response.hasFailures());//是否失败,false表示成功,true表示失败 } /** * 搜索查询+高亮 * @throws Exception */ public static void Query()throws Exception{ SearchRequest request = new SearchRequest(); //创建查询条件 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); // 使用QueryBuilders工具,精确查询term //QueryBuilders.matchAllQuery() 匹配所有 TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "hcode"); //配置高亮 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.field("name"); //绑定属性 highlightBuilder.requireFieldMatch(false); //关闭多个高亮,只显示一个高亮 highlightBuilder.preTags(" "); //设置前缀 highlightBuilder.postTags(" "); //设置后缀 sourceBuilder.highlighter(highlightBuilder); sourceBuilder.query(termQuery); sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); //获取结果对象 SearchHits hits = response.getHits(); System.out.println(JSON.toJSONString(hits)); for (SearchHit searchHit : hits) { //获取高亮的html Map<String, HighlightField> highlightFields = searchHit.getHighlightFields(); HighlightField name = highlightFields.get("name"); //替换原有的字段 Map<String, Object> sourceAsMap = searchHit.getSourceAsMap(); if (name != null) { Text[] fragments = name.fragments(); String light_name = ""; for (Text fragment : fragments) { light_name += fragment; } sourceAsMap.put("name", light_name); //进行替换 } System.out.println(searchHit.getSourceAsMap()); } } }
如果需要结合项目中,也可以这样写
package com.elasticsearch.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ElasticSearchClientConfig { // 初始化api客户端 @Bean public RestHighLevelClient restHighLevelClient(){ return new RestHighLevelClient( RestClient.builder( //有几个集群写几个!! new HttpHost("192.XXX.XX.XX",9200, "http"), new HttpHost("192.XXX.XX.XX",9201, "http") ) ); } }
需要用的话直接注入就好了
@Autowired
private RestHighLevelClient restHighLevelClient;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。