Gitee项目地址:https://gitee.com/linhong-java/lindaxia-es-7.6.xapi
一、客户端学习
https://www.elastic.co/guide/en/elasticsearch/client/index.html
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/java-rest-high-getting-started-maven.html
二、新建SpringBoot工程
2.1.设置编译环境
2.2.调整Springboot版本
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.5.RELEASE</version></parent>
2.3自定义es依赖版本
<properties><java.version>1.8</java.version><elasticsearch.version>7.6.1</elasticsearch.version></properties>
三、Java测试类
3.1.es客户端工具类
@Configurationpublic class ElasticSearchClientConfig {/*** 注入高级客户端** @return RestHighLevelClient*/@Beanpublic RestHighLevelClient restHighLevelClient() {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));return client;}}
3.2.es索引的curd
/*** 7.6.1高级客户端测试* @author: lindaxia* @since : create by in 2021-09-12 18:16*/@SpringBootTestclass EsIndexApplicationTests {@Autowired@Qualifier("restHighLevelClient")private RestHighLevelClient client;/*** 1.索引的创建 PUT lindaxia_index*/@Testpublic void testCreateIndex() throws IOException {//1.创建索引请求CreateIndexRequest request = new CreateIndexRequest("lindaxia_index");//2.客户端执行请求 IndicesClient,请求后获得响应CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);System.out.println(createIndexResponse);}/*** 2.判断索引是否存在* @throws IOException*/@Testpublic void testExistIndex() throws IOException {GetIndexRequest request = new GetIndexRequest("lindaxia_index");boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);System.out.println(exists);}/*** 删除索引* @throws IOException*/@Testpublic void testDeteletIndex() throws IOException{DeleteIndexRequest request = new DeleteIndexRequest("lindaxia_index");AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);System.out.println(delete.isAcknowledged());}}
3.3.es文档的curd
/*** @author: lindaxia* @since : create by in 2021-09-12 18:16*/@SpringBootTestpublic class EsDocApplicationTests {@Autowired@Qualifier("restHighLevelClient")private RestHighLevelClient client;/*** 测试添加文档** @throws IOException*/@Testpublic void testAddDocument() throws IOException {// 创建对象User user = new User("林大侠", 25);// 创建请求IndexRequest request = new IndexRequest("lindaxia_index");// 规则 put /lindaxia_index/_doc/1request.id("1");request.timeout(TimeValue.timeValueSeconds(1));// 将数据放入到请求 jsonrequest.source(JSON.toJSONString(user), XContentType.JSON);// 客户端发送请求IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);// IndexResponse[index=lindaxia_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]System.out.println(indexResponse.toString());// CREATEDSystem.out.println(indexResponse.status());}/*** 判断文档是否存在 get /index/doc/1** @throws IOException*/@Testpublic void testIsExists() throws IOException {GetRequest getRequest = new GetRequest("lindaxia_index", "1");getRequest.fetchSourceContext(new FetchSourceContext(false));getRequest.storedFields("_none_");boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);System.out.println(exists);}/*** 获取文档信息** @throws IOException {"age":25,"name":"林大侠"}* {"_index":"lindaxia_index","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"age":25,"name":"林大侠"}}*/@Testpublic void testGetDocument() throws IOException {GetRequest getRequest = new GetRequest("lindaxia_index", "1");GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);// 打印文档的内容System.out.println(getResponse.getSourceAsString());System.out.println(getResponse);}/*** 更新文档信息** @throws IOException*/@Testpublic void testUpdateDocument() throws IOException {UpdateRequest updateRequest = new UpdateRequest("lindaxia_index", "1");updateRequest.timeout("1s");User user = new User("林大侠学java", 26);updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);// OKSystem.out.println(updateResponse.status());}/*** 删除文档信息(删除1号用户信息)** @throws IOException*/@Testpublic void testDeleteDocument() throws IOException {DeleteRequest updateRequest = new DeleteRequest("lindaxia_index", "1");updateRequest.timeout("1s");DeleteResponse updateResponse = client.delete(updateRequest, RequestOptions.DEFAULT);// OKSystem.out.println(updateResponse.status());}/*** 批量插入数据* 批量更新和批量删除** @throws IOException*/@Testpublic void testBulkDocument() throws IOException {BulkRequest bulkRequest = new BulkRequest();bulkRequest.timeout("10s");ArrayList<User> list = new ArrayList<>();list.add(new User("林大侠1", 18));list.add(new User("林大侠2", 19));list.add(new User("林大侠3", 20));list.add(new User("林大侠4", 21));list.add(new User("林大侠5", 22));for (int i = 0; i < list.size(); i++) {bulkRequest.add(new IndexRequest("lindaxia_index").id("" + (i + 1)).source(JSON.toJSONString(list.get(i)), XContentType.JSON));}BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);//是否失败 false 则批量插入成功System.out.println(bulkResponse.hasFailures());}/*** 查询* 注意:name为中文 这里无法查询到结果* name类型不是keyword,精确查询不是keyword只能查询单个汉字** SearchSourceBuilder 条件构造* HighlightBuilder 构建高亮* TermQueryBuilder 精确查询** @throws IOException*/@Testpublic void testSearch() throws IOException {SearchRequest searchRequest = new SearchRequest("lindaxia_index");//构建搜索条件SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//查询条件,可以使用QueryBuilders工具类//QueryBuilders.termQuery 精确匹配//name为中文 这里无法查询到结果TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age", "18");//MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();searchSourceBuilder.query(termQueryBuilder);searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);//{"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"林大侠1","age":18},"sourceAsString":"{\"age\":18,\"name\":\"林大侠1\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.0,"totalHits":{"relation":"EQUAL_TO","value":1}}System.out.println(JSON.toJSONString(searchResponse.getHits()));System.out.println("===========================================");SearchHit[] hits = searchResponse.getHits().getHits();for (SearchHit documentFields : hits) {//{name=林大侠1, age=18}System.out.println(documentFields.getSourceAsMap());}}}


