springBoot整合ElasticSearch
1.依赖
ElasticSearch 7.16.0
JDK11 以上版本
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
2.配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 { @Bean public RestHighLevelClient restHighLevelClient() { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost( "127.0.0.1" , 9200 , "http" ))); return client; } } |
3.工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | package com.example.es.utils; import com.alibaba.fastjson.JSON; 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.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.core.TimeValue; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.xcontent.XContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; @Component public class EsUtils<T>{ @Autowired @Qualifier ( "restHighLevelClient" ) private RestHighLevelClient client; //*************************索引****************************************** /** * 判断索引是否存在 * @param index * @return * @throws IOException */ public boolean existsIndex(String index) throws IOException { GetIndexRequest request = new GetIndexRequest(index); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); return exists; } /** * 创建索引 * @param index * @throws IOException */ public boolean createIndex(String index) throws IOException { CreateIndexRequest request = new CreateIndexRequest(index); CreateIndexResponse createIndexResponse =client.indices().create(request,RequestOptions.DEFAULT); return createIndexResponse.isAcknowledged(); } /** * 删除索引 * @param index * @return * @throws IOException */ public boolean deleteIndex(String index) throws IOException { DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index); AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); return response.isAcknowledged(); } //***********************记录 查询********************************* /** * 判断某索引下文档id是否存在 * @param index * @param id * @return * @throws IOException */ public boolean docExists(String index, String id) throws IOException { GetRequest getRequest = new GetRequest(index,id); //只判断索引是否存在不需要获取_source getRequest.fetchSourceContext( new FetchSourceContext( false )); getRequest.storedFields( "_none_" ); boolean exists = client.exists(getRequest, RequestOptions.DEFAULT); return exists; } /** * 根据id来获取记录 * @param index * @param id * @return * @throws IOException */ public GetResponse getDoc(String index, String id) throws IOException { GetRequest getRequest = new GetRequest(index, id); GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT); return getResponse; } /** * 根据某字段来搜索 * @param index * @param field * @param key 要收搜的关键字 * @throws IOException */ public void search(String index,String field ,String key,Integer from,Integer size) throws IOException { SearchRequest searchRequest = new SearchRequest(index); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.termQuery(field, key)); //控制搜素 sourceBuilder.from(from); sourceBuilder.size(size); //最大搜索时间。 sourceBuilder.timeout( new TimeValue( 60 , TimeUnit.SECONDS)); searchRequest.source(sourceBuilder); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); System.out.println(JSON.toJSONString(searchResponse.getHits())); } //***********************记录 添加修改删除********************************* /** * 添加文档记录 * @param index * @param id * @param t 要添加的数据实体类 * @return * @throws IOException */ public boolean addDoc(String index,String id,T t) throws IOException { IndexRequest request = new IndexRequest(index); request.id(id); //timeout request.timeout(TimeValue.timeValueSeconds( 1 )); request.timeout( "1s" ); request.source(JSON.toJSONString(t), XContentType.JSON); IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); RestStatus Status = indexResponse.status(); return Status==RestStatus.OK||Status== RestStatus.CREATED; } /** * 批量添加文档记录 * 没有设置id ES会自动生成一个,如果要设置 IndexRequest的对象.id()即可 * @param index * @param list * @return * @throws IOException */ public boolean bulkAdd(String index, List<T> list) throws IOException { BulkRequest bulkRequest = new BulkRequest(); //timeout bulkRequest.timeout(TimeValue.timeValueMinutes( 2 )); bulkRequest.timeout( "2m" ); for ( int i = 0 ;i<list.size();i++){ bulkRequest.add( new IndexRequest(index) .source(JSON.toJSONString(list.get(i)))); } BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT); return !bulkResponse.hasFailures(); } /** * 更新文档记录 * @param index * @param id * @param t * @return * @throws IOException */ public boolean updateDoc(String index,String id,T t) throws IOException { UpdateRequest request = new UpdateRequest(index,id); request.doc(JSON.toJSONString(t)); request.timeout(TimeValue.timeValueSeconds( 1 )); request.timeout( "1s" ); UpdateResponse updateResponse = client.update( request, RequestOptions.DEFAULT); return updateResponse.status()==RestStatus.OK; } /** * 删除文档记录 * @param index * @param id * @return * @throws IOException */ public boolean deleteDoc(String index,String id) throws IOException { DeleteRequest request = new DeleteRequest(index,id); //timeout request.timeout(TimeValue.timeValueSeconds( 1 )); request.timeout( "1s" ); DeleteResponse deleteResponse = client.delete( request, RequestOptions.DEFAULT); return deleteResponse.status()== RestStatus.OK; } } |
4.测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | @SpringBootTest class SpringbootElasticSearchApplicationTests { @Autowired @Qualifier ( "restHighLevelClient" ) private RestHighLevelClient client; @Autowired private EsUtils esUtils; @Test void contextLoads() { String index= "test" ; String id= "10" ; try { boolean b = esUtils.existsIndex(index); if (b){ boolean b1 = esUtils.docExists(index, id); if (b1){ GetResponse getResponse = esUtils.getDoc(index, id); //字符串编码格式转换 UTF-8转GBK String value = new String (getResponse.getSourceAsString().getBytes( "UTF-8" ), "GBK" ); System.out.println(value); } else { User user = new User( "test" , 20 , "male" ); boolean flag= esUtils.addDoc( "张三" , "10" , user); System.out.println(flag); } } client.close(); } catch (Exception e){ System.out.println(e); } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2020-07-13 java-常用-发送短信