springboot2如何集成ElasticSearch6.4.3
springboot2集成ElasticSearch6.4.3
- springboot版本:2.0.0
- ES版本:6.4.3
es的服務(wù)器部署過程不再贅述,網(wǎng)上資源很多。
(1)pom文件
<dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>6.4.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>6.4.3</version> <exclusions> <exclusion> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> </exclusion> </exclusions> </dependency>
(2)yml文件
spring: data: elasticsearch: cluster-name: es ip: 10.10.77.142 port : 9300 pool : 1 logPath : 1 # 選擇日志存入的方式,1 將日志存入ElasticSearch;2存入數(shù)據(jù)庫
(3)創(chuàng)建ElasticsearchConfig類
進(jìn)行ES的初始化連接
import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.net.InetAddress; /** * Created by dell on 2019/5/30. */ @Configuration public class ElasticsearchConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchConfig.class); /** * elk集群地址 */ @Value("${spring.data.elasticsearch.ip}") private String hostName; /** * 端口 */ @Value("${spring.data.elasticsearch.port}") private String port; /** * 集群名稱 */ @Value("${spring.data.elasticsearch.cluster-name}") private String clusterName; /** * 連接池 */ @Value("${spring.data.elasticsearch.pool}") private String poolSize; /** * Bean name default 函數(shù)名字 * * @return */ @Bean(name = "transportClient") public TransportClient transportClient() { LOGGER.info("Elasticsearch初始化開始。。。。。"); TransportClient transportClient = null; try { // 配置信息 Settings esSetting = Settings.builder() .put("cluster.name", clusterName) //集群名字 .put("client.transport.sniff", true)//增加嗅探機(jī)制,找到ES集群 .put("thread_pool.search.size", Integer.parseInt(poolSize))//增加線程池個(gè)數(shù),暫時(shí)設(shè)為5 .build(); //配置信息Settings自定義 transportClient = new PreBuiltTransportClient(esSetting); TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port)); transportClient.addTransportAddresses(transportAddress); } catch (Exception e) { LOGGER.error("elasticsearch TransportClient create error!!", e); } return transportClient; } }
(4)創(chuàng)建ES分頁工具
import java.util.List; import java.util.Map; /** * Created by dell on 2019/5/30. */ public class EsPage { /** * 當(dāng)前頁 */ private int currentPage; /** * 每頁顯示多少條 */ private int pageSize; /** * 總記錄數(shù) */ private int recordCount; /** * 本頁的數(shù)據(jù)列表 */ private List<Map<String, Object>> recordList; /** * 總頁數(shù) */ private int pageCount; /** * 頁碼列表的開始索引(包含) */ private int beginPageIndex; /** * 頁碼列表的結(jié)束索引(包含) */ private int endPageIndex; /** * 只接受前4個(gè)必要的屬性,會(huì)自動(dòng)的計(jì)算出其他3個(gè)屬性的值 * * @param currentPage * @param pageSize * @param recordCount * @param recordList */ public EsPage(int currentPage, int pageSize, int recordCount, List<Map<String, Object>> recordList) { this.currentPage = currentPage; this.pageSize = pageSize; this.recordCount = recordCount; this.recordList = recordList; // 計(jì)算總頁碼 pageCount = (recordCount + pageSize - 1) / pageSize; // 計(jì)算 beginPageIndex 和 endPageIndex // >> 總頁數(shù)不多于10頁,則全部顯示 if (pageCount <= 10) { beginPageIndex = 1; endPageIndex = pageCount; } // 總頁數(shù)多于10頁,則顯示當(dāng)前頁附近的共10個(gè)頁碼 else { // 當(dāng)前頁附近的共10個(gè)頁碼(前4個(gè) + 當(dāng)前頁 + 后5個(gè)) beginPageIndex = currentPage - 4; endPageIndex = currentPage + 5; // 當(dāng)前面的頁碼不足4個(gè)時(shí),則顯示前10個(gè)頁碼 if (beginPageIndex < 1) { beginPageIndex = 1; endPageIndex = 10; } // 當(dāng)后面的頁碼不足5個(gè)時(shí),則顯示后10個(gè)頁碼 if (endPageIndex > pageCount) { endPageIndex = pageCount; beginPageIndex = pageCount - 10 + 1; } } } }
(5)創(chuàng)建ES工具類ElasticsearchUtil
import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang.StringUtils; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequestBuilder; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.metrics.max.Max; import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.sort.SortOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; /** * Created by dell on 2019/5/30. */ @Component public class ElasticsearchUtil { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchUtil.class); @Autowired private TransportClient transportClient; private static TransportClient client; /** * @PostContruct是spring框架的注解 spring容器初始化的時(shí)候執(zhí)行該方法 */ @PostConstruct public void init() { client = this.transportClient; } /** * 創(chuàng)建索引 * * @param index * @return */ public static boolean createIndex(String index) { if (!isIndexExist(index)) { LOGGER.info("Index is not exits!"); } CreateIndexResponse indexresponse = client.admin().indices().prepareCreate(index).execute().actionGet(); LOGGER.info("執(zhí)行建立成功?" + indexresponse.isAcknowledged()); return indexresponse.isAcknowledged(); } /** * 刪除索引 * * @param index * @return */ public static boolean deleteIndex(String index) { if (!isIndexExist(index)) { LOGGER.info("Index is not exits!"); } DeleteIndexResponse dResponse = client.admin().indices().prepareDelete(index).execute().actionGet(); if (dResponse.isAcknowledged()) { LOGGER.info("delete index " + index + " successfully!"); } else { LOGGER.info("Fail to delete index " + index); } return dResponse.isAcknowledged(); } /** * 判斷索引是否存在 * * @param index * @return */ public static boolean isIndexExist(String index) { IndicesExistsResponse inExistsResponse = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet(); if (inExistsResponse.isExists()) { LOGGER.info("Index [" + index + "] is exist!"); } else { LOGGER.info("Index [" + index + "] is not exist!"); } return inExistsResponse.isExists(); } /** * @Author: LX * @Description: 判斷inde下指定type是否存在 * @Date: 2018/11/6 14:46 * @Modified by: */ public boolean isTypeExist(String index, String type) { return isIndexExist(index) ? client.admin().indices().prepareTypesExists(index).setTypes(type).execute().actionGet().isExists() : false; } /** * 數(shù)據(jù)添加,正定ID * * @param jsonObject 要增加的數(shù)據(jù) * @param index 索引,類似數(shù)據(jù)庫 * @param type 類型,類似表 * @param id 數(shù)據(jù)ID * @return */ public static String addData(JSONObject jsonObject, String index, String type, String id) { IndexResponse response = client.prepareIndex(index, type, id).setSource(jsonObject).get(); LOGGER.info("addData response status:{},id:{}", response.status().getStatus(), response.getId()); return response.getId(); } /** * 數(shù)據(jù)添加 * * @param jsonObject 要增加的數(shù)據(jù) * @param index 索引,類似數(shù)據(jù)庫 * @param type 類型,類似表 * @return */ public static String addData(JSONObject jsonObject, String index, String type) { return addData(jsonObject, index, type, UUID.randomUUID().toString().replaceAll("-", "").toUpperCase()); } /** * 通過ID刪除數(shù)據(jù) * @param * @param * @param */ public static SearchHits getDataByFiledList(QueryBuilder builder,String index,String type) { SearchRequestBuilder srb=client.prepareSearch(index).setTypes(type); if (null != builder ){ SearchResponse sr = srb.setQuery(builder).execute().actionGet(); SearchHits hits = sr.getHits(); return hits; }else { LOGGER.info("filedMapList length is 0!"); } return null; } /** * 通過ID刪除數(shù)據(jù) * * @param index 索引,類似數(shù)據(jù)庫 * @param type 類型,類似表 * @param id 數(shù)據(jù)ID */ public static void deleteDataById(String index, String type, String id) { DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet(); LOGGER.info("deleteDataById response status:{},id:{}", response.status().getStatus(), response.getId()); } /** * 聚合查詢某個(gè)字段最大值 * * @param index 索引,類似數(shù)據(jù)庫 * @param type 類型,類似表 * @param */ public static int max(String index, String type, String file) { //指定分組求最大值 MaxAggregationBuilder maxAgg = AggregationBuilders.max("max_value").field(file); SearchResponse response = client.prepareSearch(index).setTypes(type).addAggregation(maxAgg).get(); Max max = response.getAggregations().get("max_value"); System.out.println(max.getValue()); return (int) max.getValue(); } /** * 通過ID 更新數(shù)據(jù) * * @param jsonObject 要增加的數(shù)據(jù) * @param index 索引,類似數(shù)據(jù)庫 * @param type 類型,類似表 * @param id 數(shù)據(jù)ID * @return */ public static void updateDataById(JSONObject jsonObject, String index, String type, String id) { UpdateRequest updateRequest = new UpdateRequest(); updateRequest.index(index).type(type).id(id).doc(jsonObject); client.update(updateRequest); } /** * 通過ID獲取數(shù)據(jù) * * @param index 索引,類似數(shù)據(jù)庫 * @param type 類型,類似表 * @param id 數(shù)據(jù)ID * @param fields 需要顯示的字段,逗號(hào)分隔(缺省為全部字段) * @return */ public static Map<String, Object> searchDataById(String index, String type, String id, String fields) { GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id); if (StringUtils.isNotEmpty(fields)) { getRequestBuilder.setFetchSource(fields.split(","), null); } GetResponse getResponse = getRequestBuilder.execute().actionGet(); return getResponse.getSource(); } /** * 使用分詞查詢,并分頁 * * @param index 索引名稱 * @param type 類型名稱,可傳入多個(gè)type逗號(hào)分隔 * @param startPage 當(dāng)前頁 * @param pageSize 每頁顯示條數(shù) * @param query 查詢條件 * @param fields 需要顯示的字段,逗號(hào)分隔(缺省為全部字段) * @param sortField 排序字段 * @param highlightField 高亮字段 * @return */ public static EsPage searchDataPage(String index, String type, int startPage, int pageSize, QueryBuilder query, String fields, String sortField, String highlightField) { SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index); if (StringUtils.isNotEmpty(type)) { searchRequestBuilder.setTypes(type.split(",")); } searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH); // 需要顯示的字段,逗號(hào)分隔(缺省為全部字段) if (StringUtils.isNotEmpty(fields)) { searchRequestBuilder.setFetchSource(fields.split(","), null); } //排序字段 if (StringUtils.isNotEmpty(sortField)) { searchRequestBuilder.addSort(sortField, SortOrder.DESC); } // 高亮(xxx=111,aaa=222) if (StringUtils.isNotEmpty(highlightField)) { HighlightBuilder highlightBuilder = new HighlightBuilder(); //highlightBuilder.preTags("<span style='color:red' >");//設(shè)置前綴 //highlightBuilder.postTags("</span>");//設(shè)置后綴 // 設(shè)置高亮字段 highlightBuilder.field(highlightField); searchRequestBuilder.highlighter(highlightBuilder); } //searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); searchRequestBuilder.setQuery(query); // 分頁應(yīng)用 searchRequestBuilder.setFrom(startPage).setSize(pageSize); // 設(shè)置是否按查詢匹配度排序 searchRequestBuilder.setExplain(true); //打印的內(nèi)容 可以在 Elasticsearch head 和 Kibana 上執(zhí)行查詢 LOGGER.info("\n{}", searchRequestBuilder); // 執(zhí)行搜索,返回搜索響應(yīng)信息 SearchResponse searchResponse = searchRequestBuilder.execute().actionGet(); long totalHits = searchResponse.getHits().totalHits; long length = searchResponse.getHits().getHits().length; LOGGER.debug("共查詢到[{}]條數(shù)據(jù),處理數(shù)據(jù)條數(shù)[{}]", totalHits, length); if (searchResponse.status().getStatus() == 200) { // 解析對象 List<Map<String, Object>> sourceList = setSearchResponse(searchResponse, highlightField); return new EsPage(startPage, pageSize, (int) totalHits, sourceList); } return null; } /** * 使用分詞查詢 * * @param index 索引名稱 * @param type 類型名稱,可傳入多個(gè)type逗號(hào)分隔 * @param query 查詢條件 * @param size 文檔大小限制 * @param fields 需要顯示的字段,逗號(hào)分隔(缺省為全部字段) * @param sortField 排序字段 * @param highlightField 高亮字段 * @return */ public static List<Map<String, Object>> searchListData( String index, String type, QueryBuilder query, Integer size, String fields, String sortField, String highlightField) { SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index); if (StringUtils.isNotEmpty(type)) { searchRequestBuilder.setTypes(type.split(",")); } if (StringUtils.isNotEmpty(highlightField)) { HighlightBuilder highlightBuilder = new HighlightBuilder(); // 設(shè)置高亮字段 highlightBuilder.field(highlightField); searchRequestBuilder.highlighter(highlightBuilder); } searchRequestBuilder.setQuery(query); if (StringUtils.isNotEmpty(fields)) { searchRequestBuilder.setFetchSource(fields.split(","), null); } searchRequestBuilder.setFetchSource(true); if (StringUtils.isNotEmpty(sortField)) { searchRequestBuilder.addSort(sortField, SortOrder.DESC); } if (size != null && size > 0) { searchRequestBuilder.setSize(size); } //打印的內(nèi)容 可以在 Elasticsearch head 和 Kibana 上執(zhí)行查詢 LOGGER.info("\n{}", searchRequestBuilder); SearchResponse searchResponse = searchRequestBuilder.execute().actionGet(); long totalHits = searchResponse.getHits().totalHits; long length = searchResponse.getHits().getHits().length; LOGGER.info("共查詢到[{}]條數(shù)據(jù),處理數(shù)據(jù)條數(shù)[{}]", totalHits, length); if (searchResponse.status().getStatus() == 200) { // 解析對象 return setSearchResponse(searchResponse, highlightField); } return null; } /** * 高亮結(jié)果集 特殊處理 * * @param searchResponse * @param highlightField */ private static List<Map<String, Object>> setSearchResponse(SearchResponse searchResponse, String highlightField) { List<Map<String, Object>> sourceList = new ArrayList<Map<String, Object>>(); StringBuffer stringBuffer = new StringBuffer(); for (SearchHit searchHit : searchResponse.getHits().getHits()) { searchHit.getSourceAsMap().put("id", searchHit.getId()); if (StringUtils.isNotEmpty(highlightField)) { System.out.println("遍歷 高亮結(jié)果集,覆蓋 正常結(jié)果集" + searchHit.getSourceAsMap()); Text[] text = searchHit.getHighlightFields().get(highlightField).getFragments(); if (text != null) { for (Text str : text) { stringBuffer.append(str.string()); } //遍歷 高亮結(jié)果集,覆蓋 正常結(jié)果集 searchHit.getSourceAsMap().put(highlightField, stringBuffer.toString()); } } sourceList.add(searchHit.getSourceAsMap()); } return sourceList; } }
(6)測試controller
package com.supconit.data.algorithm.platform.executor.controller; import com.alibaba.fastjson.JSONObject; import com.supconit.data.algorithm.platform.common.entity.scheme.execution.ExecutionModule; import com.supconit.data.algorithm.platform.common.entity.scheme.execution.ExecutionScheme; import com.supconit.data.algorithm.platform.executor.ElasticSearch.ElasticsearchUtil; import com.supconit.data.algorithm.platform.executor.ElasticSearch.EsPage; import org.apache.commons.lang.StringUtils; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Random; /** * Created by dell on 2019/5/29. */ @RestController @RequestMapping("/es") public class esTestDemo { /** * 測試索引 */ private String indexName = "execution_module"; /** * 類型 */ private String esType = "module"; /** * http://127.0.0.1:8080/es/createIndex * 創(chuàng)建索引 * * @param request * @param response * @return */ @RequestMapping("/createIndex") public String createIndex(HttpServletRequest request, HttpServletResponse response) { if (!ElasticsearchUtil.isIndexExist(indexName)) { ElasticsearchUtil.createIndex(indexName); } else { return "索引已經(jīng)存在"; } return "索引創(chuàng)建成功"; } /** * http://127.0.0.1:8080/es/createIndex * 刪除索引 * * @param request * @param response * @return */ @RequestMapping("/deleteIndex") public String deleteIndex(HttpServletRequest request, HttpServletResponse response) { ElasticsearchUtil.deleteIndex(indexName); return "索引創(chuàng)建成功"; } /** * 插入記錄 * * @return */ @RequestMapping("/insertJson") public String insertJson() { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", 1); jsonObject.put("age", 25); jsonObject.put("name", "j-" + new Random(100).nextInt()); jsonObject.put("date", new Date()); String id = ElasticsearchUtil.addData(jsonObject, indexName, esType, jsonObject.getString("id")); return id; } /** * 插入記錄 * * @return */ @RequestMapping("/insertModel") public String insertModel() { ExecutionModule executionModule = new ExecutionModule(); executionModule.setExecId(4); executionModule.setEndTime(123124124); executionModule.setInstanceId(1); executionModule.setModuleId(1); executionModule.setModuleName("123321"); executionModule.setOrders(4); executionModule.setProgress(100); executionModule.setRetryTime(2); executionModule.setStatus(1); executionModule.setSchemeId(2); // ExecutionScheme executionScheme = new ExecutionScheme(); // executionScheme.setExecId(2); // executionScheme.setExecutorId(1); // executionScheme.setEndTime(1233132131); // executionScheme.setRetryTime(2); // executionScheme.setSchemeName("測試"); JSONObject jsonObject = (JSONObject) JSONObject.toJSON(executionModule); // jsonObject.put("id",executionScheme.getExecId()); String id = ElasticsearchUtil.addData(jsonObject, indexName, esType, jsonObject.getString("id")); return id; } /** * 刪除記錄 * * @return */ @RequestMapping("/delete") public String delete(String id) { if (StringUtils.isNotBlank(id)) { ElasticsearchUtil.deleteDataById(indexName, esType, id); return "刪除id=" + id; } else { return "id為空"; } } /** * 更新數(shù)據(jù) * * @return */ @RequestMapping("/update") public String update(String id) { if (StringUtils.isNotBlank(id)) { ExecutionScheme executionScheme = new ExecutionScheme(); executionScheme.setExecId(1); executionScheme.setExecutorId(1); executionScheme.setEndTime(1233132131); executionScheme.setRetryTime(2); executionScheme.setSchemeName("測試123"); JSONObject jsonObject = (JSONObject) JSONObject.toJSON(executionScheme); ElasticsearchUtil.updateDataById(jsonObject, indexName, esType, id); return "id=" + id; } else { return "id為空"; } } /** * 獲取數(shù)據(jù) * http://127.0.0.1:8080/es/getData?id=2018-04-25%2016:33:44 * * @param id * @return */ @RequestMapping("/getData") public String getData(String id) { if (StringUtils.isNotBlank(id)) { Map<String, Object> map = ElasticsearchUtil.searchDataById(indexName, esType, id, null); return JSONObject.toJSONString(map); } else { return "id為空"; } } /** * 多條件查詢 * http://127.0.0.1:8080/es/getData?id=2018-04-25%2016:33:44 * * @param * @return */ @RequestMapping("/getDataByFiled") public SearchHits getDataByFiled() { ExecutionModule executionModule = new ExecutionModule(); executionModule.setExecId(4); executionModule.setEndTime(123124124); executionModule.setInstanceId(1); executionModule.setModuleId(1); executionModule.setModuleName("123 321 123 321"); executionModule.setOrders(4); executionModule.setProgress(100); executionModule.setRetryTime(2); executionModule.setStatus(1); executionModule.setSchemeId(2); QueryBuilder queryBuilder1 = QueryBuilders.matchPhraseQuery("instanceId","1"); QueryBuilder queryBuilder2 = QueryBuilders.matchPhraseQuery("schemeId","1"); QueryBuilder queryBuilder3 = QueryBuilders.matchPhraseQuery("execId","4"); QueryBuilder queryBuilder4 = QueryBuilders.boolQuery().must(queryBuilder1).must(queryBuilder2).must(queryBuilder3); //ExecutionModule 是我自己項(xiàng)目的類,測試換成你自己的類;上面一頓操作QueryBuilder 的意思是根據(jù)instanceId、execId、schemeId這三個(gè)字段來篩選數(shù)據(jù) SearchHits hits = ElasticsearchUtil.getDataByFiledList(queryBuilder4,indexName, esType); for(SearchHit hit:hits) { System.out.println(hit.getSourceAsString()); } return hits; } /** * 查詢數(shù)據(jù) * 模糊查詢 * * @return */ @RequestMapping("/queryMatchData") public String queryMatchData() { BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolean matchPhrase = false; if (matchPhrase == Boolean.TRUE) { //不進(jìn)行分詞搜索 boolQuery.must(QueryBuilders.matchPhraseQuery("name", "m")); } else { boolQuery.must(QueryBuilders.matchQuery("name", "m-m")); } List<Map<String, Object>> list = ElasticsearchUtil. searchListData(indexName, esType, boolQuery, 10, "name", null, "name"); return JSONObject.toJSONString(list); } /** * 通配符查詢數(shù)據(jù) * 通配符查詢 ?用來匹配1個(gè)任意字符,*用來匹配零個(gè)或者多個(gè)字符 * * @return */ @RequestMapping("/queryWildcardData") public String queryWildcardData() { QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("name.keyword", "j-?466"); List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null); return JSONObject.toJSONString(list); } /** * 正則查詢 * * @return */ @RequestMapping("/queryRegexpData") public String queryRegexpData() { QueryBuilder queryBuilder = QueryBuilders.regexpQuery("name.keyword", "m--[0-9]{1,11}"); List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null); return JSONObject.toJSONString(list); } /** * 查詢數(shù)字范圍數(shù)據(jù) * * @return */ @RequestMapping("/queryIntRangeData") public String queryIntRangeData() { BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.must(QueryBuilders.rangeQuery("age").from(21) .to(25)); List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null); return JSONObject.toJSONString(list); } /** * 查詢?nèi)掌诜秶鷶?shù)據(jù) * * @return */ @RequestMapping("/queryDateRangeData") public String queryDateRangeData() { BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.must(QueryBuilders.rangeQuery("date").from("2018-04-25T08:33:44.840Z") .to("2019-04-25T10:03:08.081Z")); List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null); return JSONObject.toJSONString(list); } /** * 查詢分頁 * * @param startPage 第幾條記錄開始 * 從0開始 * 第1頁 :http://127.0.0.1:8080/es/queryPage?startPage=0&pageSize=2 * 第2頁 :http://127.0.0.1:8080/es/queryPage?startPage=2&pageSize=2 * @param pageSize 每頁大小 * @return */ @RequestMapping("/queryPage") public String queryPage(String startPage, String pageSize) { if (StringUtils.isNotBlank(startPage) && StringUtils.isNotBlank(pageSize)) { BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.must(QueryBuilders.rangeQuery("date").from("2018-04-25T08:33:44.840Z") .to("2019-04-25T10:03:08.081Z")); EsPage list = ElasticsearchUtil.searchDataPage(indexName, esType, Integer.parseInt(startPage), Integer.parseInt(pageSize), boolQuery, null, null, null); return JSONObject.toJSONString(list); } else { return "startPage或者pageSize缺失"; } } @RequestMapping("/queryMax") public int queryMaxId(String file) { if (StringUtils.isNotBlank(file) ) { AggregationBuilder aggregationBuilder = AggregationBuilders.max("max_value").field(file); int d = (int)ElasticsearchUtil.max(indexName, esType,file); return d; } else { return 0; } } }
總結(jié)
OK~大功告成!
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- SpringBoot結(jié)合ElasticSearch實(shí)現(xiàn)模糊查詢的項(xiàng)目實(shí)踐
- SpringBoot集成ElasticSearch(ES)實(shí)現(xiàn)全文搜索功能
- SpringBoot中Elasticsearch的連接配置原理與使用詳解
- SpringBoot3集成ElasticSearch的方法詳解
- springboot?ElasticSearch如何配置自定義轉(zhuǎn)換器ElasticsearchCustomConversions
- SpringBoot2如何集成Elasticsearch6.x(TransportClient方式)
相關(guān)文章
利用Java設(shè)置Word文本框中的文字旋轉(zhuǎn)方向的實(shí)現(xiàn)方法
Word文檔中可添加文本框,并設(shè)置文本框?yàn)闄M向文本排列或是縱向文本排列,或者設(shè)置文本框中的文字旋轉(zhuǎn)方向等.通過Java程序代碼,也可以實(shí)現(xiàn)以上文本框的操作.下面以Java代碼示例展示具體的實(shí)現(xiàn)步驟.另外,可參考C#及VB.NET代碼的實(shí)現(xiàn)方法,需要的朋友可以參考下2021-06-06maven下mybatis-plus和pagehelp沖突問題的解決方法
這篇文章主要介紹了maven下mybatis-plus和pagehelp沖突的解決方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08Java向上轉(zhuǎn)型與向下轉(zhuǎn)型超詳細(xì)圖解
我們在Java編程中經(jīng)常碰到類型轉(zhuǎn)換,對象類型轉(zhuǎn)換主要包括向上轉(zhuǎn)型和向下轉(zhuǎn)型,這篇文章主要介紹了Java向上轉(zhuǎn)型與向下轉(zhuǎn)型的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-04-04SpringBoot actuator 健康檢查不通過的解決方案
這篇文章主要介紹了SpringBoot actuator 健康檢查不通過的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Java 實(shí)現(xiàn)滑動(dòng)時(shí)間窗口限流算法的代碼
這篇文章主要介紹了Java 實(shí)現(xiàn)滑動(dòng)時(shí)間窗口限流算法的代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11Java構(gòu)造函數(shù)與普通函數(shù)用法詳解
本篇文章給大家詳細(xì)講述了Java構(gòu)造函數(shù)與普通函數(shù)用法以及相關(guān)知識(shí)點(diǎn),對此有興趣的朋友可以參考學(xué)習(xí)下。2018-03-03Java實(shí)現(xiàn)局域網(wǎng)聊天小程序
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)局域網(wǎng)聊天小程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05實(shí)例講解Java中random.nextInt()與Math.random()的基礎(chǔ)用法
今天小編就為大家分享一篇關(guān)于實(shí)例講解Java中random.nextInt()與Math.random()的基礎(chǔ)用法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02SpringHateoas超媒體API之資源表示與鏈接關(guān)系詳解
本文將深入探討Spring HATEOAS的核心概念、資源表示方式以及如何構(gòu)建豐富的超媒體API,幫助開發(fā)者創(chuàng)建更具自描述性和可發(fā)現(xiàn)性的Web服務(wù),具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-04-04