1 开发步骤
1)创建空项目,新建mudule,项目jdk设置成1.8
2 )创建ElasticSearchClientConfig配置类
package com.kuang.kuangshenesapi.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; /** * @author yulin * @create 2021-07-29-14:31 */ @Configuration public class ElasticSearchClientConfig { // @Bean public RestHighLevelClient restHighLevelClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"))); return client; } }
3 )创建User实体类
package com.kuang.kuangshenesapi.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; /** * @author yulin * @create 2021-07-29-16:43 */ @Component public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User() { } public User(String name, int age) { this.name = name; this.age = age; } }
4 )开始写测试类
package com.kuang.kuangshenesapi; import ch.qos.logback.core.net.SyslogOutputStream; import com.alibaba.fastjson.JSON; import com.kuang.kuangshenesapi.entity.User; import jdk.nashorn.internal.ir.RuntimeNode; 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.Client; import org.elasticsearch.client.Request; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.MatchAllQueryBuilder; 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.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import javax.naming.directory.SearchResult; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @SpringBootTest class KuangshenEsApiApplicationTests { @Autowired @Qualifier("restHighLevelClient") private RestHighLevelClient client; //测试索引的创建 @Test void testCreateIndex() throws IOException { //创建索引请求 CreateIndexRequest request = new CreateIndexRequest("zhangsan"); //执行请求,获取相应 CreateIndexResponse createIndexResponse = client.indices().create(request,RequestOptions.DEFAULT); System.out.println(createIndexResponse); } //测试索引的获取 @Test void testIndexExist() throws IOException { GetIndexRequest request = new GetIndexRequest("zhangsan"); boolean exist = client.indices().exists(request,RequestOptions.DEFAULT); System.out.println(exist); } //测试索引的删除 @Test void testIndexDelete() throws IOException { DeleteIndexRequest request = new DeleteIndexRequest("zhangsan"); AcknowledgedResponse delete = client.indices().delete(request,RequestOptions.DEFAULT); System.out.println(delete); } //测试索引的更新 //添加文档 @Test void testAddDocument() throws IOException { //创建对象 User user = new User("张三",23); //创建请求 IndexRequest request = new IndexRequest("kuang_index"); //规则 put /kuang_index/_doc/1 request.id("1"); request.timeout("1s"); //将我们的数据放入请求 json request.source(JSON.toJSONString(user), XContentType.JSON); //客户端发送请求,获取响应结果 IndexResponse responce = client.index(request,RequestOptions.DEFAULT); System.out.println(responce.toString()); System.out.println(responce.status()); } //获取文档 @Test void testIsExistDocument() throws IOException { GetRequest getRequest = new GetRequest("kuang_index","1"); boolean exist = client.exists(getRequest,RequestOptions.DEFAULT); System.out.println(exist); } //获取文档的信息 @Test void testGetDocumentMessage() throws IOException { GetRequest getRequest = new GetRequest("kuang_index","1"); GetResponse getResponse = client.get(getRequest,RequestOptions.DEFAULT); System.out.println(getResponse.getSourceAsString());//打印文档内容 System.out.println(getResponse);//返回的全部内容和命令一样 } //更新文档信息 @Test void testupdateDocumentMessage() throws IOException { UpdateRequest updateRequest = new UpdateRequest("kuang_index","1"); updateRequest.timeout("1s"); User user = new User("张纪晓岚",23); updateRequest.doc(JSON.toJSONString(user),XContentType.JSON); UpdateResponse updateResponse = client.update(updateRequest,RequestOptions.DEFAULT); System.out.println(updateResponse.status());//返回的全部内容和命令一样 } //删除文档信息 @Test void testdeleteDocument() throws IOException { DeleteRequest request = new DeleteRequest("kuang_index","1"); request.timeout("1s"); DeleteResponse deleteResponse = client.delete(request,RequestOptions.DEFAULT); System.out.println(deleteResponse.status()); } //批量插入数据 @Test void testBulkRequest() throws IOException { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.timeout("10s"); ArrayList<User> userList = new ArrayList<>(); userList.add(new User("铁臂阿童木",32)); userList.add(new User("海绵宝宝",26)); userList.add(new User("拇指姑娘",12)); userList.add(new User("童话王国",12)); userList.add(new User("竹篮子",25)); userList.add(new User("派大星",12)); //批处理请求 for (int i = 0;i<userList.size();i++ ){ bulkRequest.add(new IndexRequest("kuang_index").id(""+(i+1)).source(JSON.toJSONString(userList.get(i)),XContentType.JSON)); } BulkResponse bulkResponse = client.bulk(bulkRequest,RequestOptions.DEFAULT); System.out.println(bulkResponse.hasFailures());//是否失败 } @Test void testSearch() throws IOException { SearchRequest searchRequest = new SearchRequest("kuang_index"); //构建搜索条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //查询条件,使用QueryBuilders工具类 //QueryBuilders.termQuery 精确 //QueryBuilders.matchAllQuery() 匹配所有 TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name","阿童木"); //MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery(); searchSourceBuilder.query(termQueryBuilder); searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); searchRequest.source(searchSourceBuilder); SearchResponse response = client.search(searchRequest,RequestOptions.DEFAULT); SearchHits hits = response.getHits(); System.out.println(JSON.toJSONString(response.getHits())); System.out.println(JSON.toJSONString(hits)); System.out.println("=========================="); for(SearchHit ducumentfields : hits.getHits()){ System.out.println(ducumentfields.getSourceAsMap()); } } }
最后附上项目结构