springboot集成es7(基于high level client)
环境:
ES: 7.12.0
1、springboot工程引入es相关jar
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.12.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.12.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>reindex-client</artifactId>
<version>7.12.0</version>
</dependency>
<!-- Java High Level REST Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.0</version>
</dependency>
2、增加es自定义配置
elasticsearch:
configs:
sport: #索引配置
userName: 1
password: 2
host: 127.0.0.1
port: 9200
indexName: sport #索引名称
timeOut: 1000 #请求超时时间,单位秒
study:
indexName: study
help: sssssssssssssssssssss
3、JAVA代码
package com.example.elasticSearch; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import java.util.Map; @Configuration @ConfigurationProperties(prefix = "elasticsearch") public class ESConfig { Map<String, Config> configs; String help; public String getHelp() { return help; } public void setHelp(String help) { this.help = help; } public Map<String, Config> getConfigs() { return configs; } public void setConfigs(Map<String, Config> configs) { this.configs = configs; } static class Config { private String userName; private String password; private String host; private Integer port; private String indexName; private long timeout; public long getTimeout() { return timeout; } public void setTimeout(long timeout) { this.timeout = timeout; } public String getIndexName() { return indexName; } public void setIndexName(String indexName) { this.indexName = indexName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } } }
package com.example.elasticSearch; import com.alibaba.fastjson.JSON; import org.apache.http.HttpHost; 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.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.ScoreSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.RequestBody; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class ESClient { RestHighLevelClient restHighLevelClient; ESConfig.Config config; /** * 获取连接 * @param config */ public ESClient(ESConfig.Config config) { this.config = config; String[] hosts = config.getHost().split(","); String[] ports = config.getPort().split(","); HttpHost[] httpHostList = new HttpHost[hosts.length]; for (int i = 0; i < hosts.length; i++) { httpHostList[i] = new HttpHost(hosts[i],Integer.parseInt(ports[i]),"http"); } RestHighLevelClient restHighLevelClient=new RestHighLevelClient( RestClient.builder(httpHostList)); this.restHighLevelClient = restHighLevelClient; } /** * 新建索引 * @param sport */ public void saveIndex(Sport sport){ try { boolean exists = restHighLevelClient.indices().exists(new GetIndexRequest(config.getIndexName()), RequestOptions.DEFAULT); if (!exists) { CreateIndexRequest qyf = new CreateIndexRequest(config.getIndexName()); restHighLevelClient.indices().create(qyf, RequestOptions.DEFAULT); } } catch (Exception e) { e.printStackTrace(); } } /** * 保存文档 * @param sport */ public void saveDocument(Sport sport) { IndexRequest request = new IndexRequest(config.getIndexName()); request.source(JSON.toJSONString(sport), XContentType.JSON); request.id(sport.getTitle()); request.timeout(TimeValue.timeValueSeconds(config.getTimeout())); try { IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } } /** * 根据ID获取文档 * @param sport * @return */ public String getDocument(Sport sport) { GetRequest getRequest = new GetRequest(config.getIndexName(), sport.getId()); GetResponse getResponse1 = null; try { getResponse1 = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } return getResponse1.toString(); } /** * @param index * @param from * @param size * @param where * @param sortFieldsToAsc * @param includeFields * @param excludeFields * @param timeOut * @return */ public List<Map<String, Object>> searchIndex(String index, int from, int size, Map<String, Object> where, Map<String, Boolean> sortFieldsToAsc, String[] includeFields, String[] excludeFields, int timeOut) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); try { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //条件 if (where != null && !where.isEmpty()) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); where.forEach((k, v) -> { if (v instanceof Map) { //范围选择map 暂定时间 Map<String, Date> mapV = (Map<String, Date>) v; if (mapV != null) { boolQueryBuilder.must( QueryBuilders.rangeQuery(k). gte(format.format(mapV.get("start"))). lt(format.format(mapV.get("end")))); } } else { //普通模糊匹配 boolQueryBuilder.must(QueryBuilders.wildcardQuery(k, v.toString())); } }); sourceBuilder.query(boolQueryBuilder); } //分页 from = from <= -1 ? 0 : from; size = size >= 1000 ? 1000 : size; size = size <= 0 ? 15 : size; sourceBuilder.from(from); sourceBuilder.size(size); //超时 sourceBuilder.timeout(new TimeValue(timeOut, TimeUnit.SECONDS)); //排序 if (sortFieldsToAsc != null && !sortFieldsToAsc.isEmpty()) { sortFieldsToAsc.forEach((k, v) -> { sourceBuilder.sort(new FieldSortBuilder(k).order(v ? SortOrder.ASC : SortOrder.DESC)); }); } else { sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC)); } //返回和排除列 if ((includeFields != null && includeFields.length != 0) || (excludeFields != null && excludeFields.length != 0)) { sourceBuilder.fetchSource(includeFields, excludeFields); } SearchRequest rq = new SearchRequest(); //索引 rq.indices(index); //各种组合条件 rq.source(sourceBuilder); //请求 System.out.println(rq.source().toString()); SearchResponse rp = restHighLevelClient.search(rq, null); //解析返回 if (rp.status() != RestStatus.OK || rp.getHits().getTotalHits().value <= 0) { return Collections.emptyList(); } //获取source return Arrays.stream(rp.getHits().getHits()).map(b -> { return b.getSourceAsMap(); }).collect(Collectors.toList()); } catch (Exception ex) { ex.printStackTrace(); } return Collections.emptyList(); } /** * 搜索 * @param keyword * @param pageNo * @param pageSize * @return * @throws IOException */ public List<Map<String ,Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException { SearchRequest searchRequest = new SearchRequest(config.getIndexName()); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); pageNo = pageNo * pageSize; pageSize = pageSize == 0 ? 10 : pageSize; searchSourceBuilder.from(pageNo); searchSourceBuilder.size(pageSize); //输入的关键字匹配的字段 QueryBuilder termQueryBuilder = QueryBuilders.matchQuery("content", keyword); searchSourceBuilder.query(termQueryBuilder); searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); //执行 searchRequest.source(searchSourceBuilder); SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); ArrayList<Map<String,Object>> list = new ArrayList<>(); if (search.getHits().getHits().length!=0){ for (SearchHit documentFields : search.getHits().getHits()) { list.add(documentFields.getSourceAsMap()); } return list; }else { HashMap<String, Object> map = new HashMap<>(); map.put("code",404); map.put("msg","没有相关数据"); list.add(map); return list; } } }
package com.example.elasticSearch; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ESClientFactory { @Autowired ESConfig esConfig; public ESClient getClient(String type){ ESConfig.Config config = esConfig.configs.get(type); return new ESClient(config); } }
package com.example.elasticSearch; public class Sport{ String id; String title; String content; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package com.example.elasticSearch; import com.alibaba.fastjson.JSON; 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.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.common.xcontent.XContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController @RequestMapping("/es") public class ESController { @Autowired ESClientFactory esClientFactory; @RequestMapping("/saveIndex") public void saveIndex(@RequestBody Sport sport){ ESClient esClient = esClientFactory.getClient("sport"); esClient.saveIndex(sport); } @RequestMapping("/saveDocument") public void saveDocument(@RequestBody Sport sport) { ESClient esClient = esClientFactory.getClient("sport"); esClient.saveDocument(sport); } @RequestMapping("/getDocument") public String getDocument(@RequestBody Sport sport) { ESClient esClient = esClientFactory.getClient("sport"); return esClient.getDocument(sport); } }