package cn.hsa.csc.query.config; import cn.hsa.hsaf.core.framework.web.exception.BusinessException; import cn.hsa.utils.elasticsearch.Assert; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.elasticsearch.common.xcontent.DeprecationHandler; import java.util.Arrays; import java.util.Objects; @Configuration @ConfigurationProperties(prefix = "es") @Slf4j @Data public class ElasticsearchConfig { private String hosts; private String username; private String password; private int connectTimeout; private int socketTimeout; private int connectionRequestTimeout; @Bean public RestHighLevelClient client() { log.info("elasticsearch init start "); Assert.hasLength(hosts, "elasticsearch host is null"); HttpHost[] httpHosts = Arrays.stream(hosts.split(",")).map(host -> { Assert.hasLength(host, "elasticsearch host is null"); String[] h = host.split(":"); if (h.length != 2) throw new BusinessException("host ip or port formate is error"); return new HttpHost(h[0], Integer.parseInt(h[1])); }).filter(Objects::nonNull).toArray(HttpHost[]::new); RestClientBuilder builder = RestClient.builder(httpHosts); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider)) .setRequestConfigCallback(r -> { r.setConnectTimeout(connectTimeout); r.setSocketTimeout(socketTimeout); r.setConnectionRequestTimeout(connectionRequestTimeout); return r; }); return new RestHighLevelClient(builder); } }
配置
es: hosts: 127.0.0.1:19200,127.0.0.1:19201,127.0.0.1:19202 username: elastic password: ylz@123 connectTimeout: 30000 socketTimeout: 30000 connectionRequestTimeout: 30000二、对应工具类
package cn.hsa.utils.elasticsearch; import cn.hsa.hsaf.core.framework.web.exception.BusinessException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.lucene.search.TotalHits; import org.elasticsearch.action.DocWriteResponse; 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.WriteRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.IndicesClient; 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.common.unit.Fuzziness; import org.elasticsearch.common.unit.Timevalue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.reindex.BulkByScrollResponse; import org.elasticsearch.index.reindex.DeleteByQueryRequest; import org.elasticsearch.index.reindex.UpdateByQueryRequest; import org.elasticsearch.script.script; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Component @Slf4j public class ElasticsearchUtils { @Autowired private RestHighLevelClient restHighLevelClient; public boolean addIndex(String indexName) { Assert.hasLength(indexName, "Elasticsearch exception indexName null"); CreateIndexResponse createIndexResponse = null; try { //1.使用client获取 *** 作索引对象 IndicesClient indices = restHighLevelClient.indices(); //2.具体 *** 作获取返回值 //2.1 设置索引名称 CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName); createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT); } catch (Exception e) { // e.printStackTrace(); log.error("elasticsearch addindex error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch addindex error , meassage=" + e.getMessage()); } //3.根据返回值判断结果 return createIndexResponse.isAcknowledged(); } public boolean deleteIndex(String indexName) { Assert.hasLength(indexName, "Elasticsearch exception indexName null"); AcknowledgedResponse deleteRespone = null; try { //1.使用client获取 *** 作索引对象 IndicesClient indices = restHighLevelClient.indices(); //2.具体 *** 作获取返回值 //2.1 设置索引名称 DeleteIndexRequest request = new DeleteIndexRequest("twitter_two");//指定要删除的索引名称 deleteRespone = indices.delete(request, RequestOptions.DEFAULT); } catch (Exception e) { // e.printStackTrace(); log.error("elasticsearch deleteIndex error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch deleteIndex error , meassage=" + e.getMessage()); } //3.根据返回值判断结果 return deleteRespone.isAcknowledged(); } public boolean addData(String indexName, String id, Object data) { Assert.notNull(data, "Elasticsearch exception data null"); Assert.hasLength(indexName, "Elasticsearch exception indexName null"); IndexResponse indexResponse = null; try { //准备文档 String jsonString = JSONObject.toJSonString(data); Map jsonMap = JSONObject.parseObject(jsonString, Map.class); //创建请求 IndexRequest indexRequest = new IndexRequest(indexName).id(id); //指定文档内容 indexRequest.source(jsonMap); //true 当存在相同的_id时,插入会出现异常; false 当存在相同_id时,插入会进行覆盖; indexRequest.create(true); //通过client进行http请求 indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); } catch (Exception e) { log.error("elasticsearch addOrUpdateDoc error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch addOrUpdateDoc error , meassage=" + e.getMessage()); } return indexResponse.getResult().equals(DocWriteResponse.Result.CREATED); } public boolean addOrUpdateData(String indexName, String id, Object data) { Assert.notNull(data, "Elasticsearch exception data null"); Assert.hasLength(indexName, "Elasticsearch exception indexName null"); IndexResponse indexResponse = null; try { //准备文档 String jsonString = JSONObject.toJSonString(data); Map jsonMap = JSONObject.parseObject(jsonString, Map.class); //创建请求 IndexRequest indexRequest = new IndexRequest(indexName).id(id); //指定文档内容 indexRequest.source(jsonMap); //通过client进行http请求 indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); } catch (Exception e) { log.error("elasticsearch addOrUpdateDoc error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch addOrUpdateDoc error , meassage=" + e.getMessage()); } return indexResponse.getResult().equals(DocWriteResponse.Result.CREATED); } public boolean updateData(String indexName, String id, Object data) throws IOException { UpdateRequest updateRequest = new UpdateRequest(indexName, id); //准备文档 String jsonString = JSONObject.toJSonString(data); Map jsonMap = JSONObject.parseObject(jsonString, Map.class); updateRequest.doc(jsonMap); updateRequest.timeout(Timevalue.timevalueSeconds(1)); updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); //数据为存储而不是更新 UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT); return update.getGetResult().equals(DocWriteResponse.Result.UPDATED); } public boolean addBatchData(String index, List extends EsbaseData> datas) { Assert.hasLength(index, "Elasticsearch exception indexName null"); Assert.notEmpty(datas, "addBatchData elastaicsearch exception datas is null"); if (datas.size() > 100000) { log.error("es add batch data too large{}", datas.size()); throw new BusinessException("es add batch data too large" + datas.size()); } BulkResponse bulk = null; try { BulkRequest request = new BulkRequest(); datas.forEach(data -> { String source = JSON.toJSonString(data); request.add(new IndexRequest(data.getIndexName()).id(data.esId).source(source, XContentType.JSON)); }); bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT); } catch (Exception e) { log.error("elasticsearch addBatchData error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch addBatchData error , meassage=" + e.getMessage()); } return !bulk.hasFailures(); } public boolean deleteDataById(String indexName, String id) { DeleteRequest deleteRequest = new DeleteRequest(indexName, id); DeleteResponse response = null; try { response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT); } catch (IOException e) { log.error("elasticsearch deleteDocById error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch deleteDataById error , meassage=" + e.getMessage()); } return response.getResult().equals(DocWriteResponse.Result.DELETED); } public boolean deleteDataByCondition(String indexName, List其他辅助嘞 Es基础对象conditionFileds) { Assert.hasLength(indexName, "Elasticsearch exception indexName null"); Assert.notEmpty(conditionFileds, "Elasticsearch exception conditionFileds null"); BulkByScrollResponse resp = null; try { DeleteByQueryRequest request = new DeleteByQueryRequest(indexName); // SearchSourceBuilder searchSourceBuilder = buildSearchSourceBuilder(conditionFileds); // request.getSearchRequest().source(searchSourceBuilder); // 更新时版本冲突 request.setConflicts("proceed"); //构建条件 setDeletCondition(conditionFileds, request); // 刷新索引 request.setRefresh(true); resp = restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT); } catch (Exception e) { log.error("elasticsearch deleteDataByCondition error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch deleteDataByCondition error , meassage=" + e.getMessage()); } return resp.getStatus().getDeleted() > 0; } public boolean updateDataByCondition(String indexName, List conditionFileds, Object data) { Assert.hasLength(indexName, "Elasticsearch exception indexName null"); Assert.notEmpty(conditionFileds, "Elasticsearch exception conditionFileds null"); Assert.notNull(data, "elasticsearch updateDataByCondition data is null "); BulkByScrollResponse resp = null; try { UpdateByQueryRequest request = new UpdateByQueryRequest(indexName); //设置分片并行 request.setSlices(2); //设置版本冲突时继续执行 request.setConflicts("proceed"); //构建条件 setUpdateConfition(conditionFileds, request); //设置更新完成后刷新索引 ps很重要如果不加可能数据不会实时刷新 request.setRefresh(true); StringBuffer scriptContext = buildscriptContext(data); //设置要修改的内容可以多个值多个用;隔开 request.setscript(new script(scriptContext.toString())); resp = restHighLevelClient.updateByQuery(request, RequestOptions.DEFAULT); } catch (Exception e) { log.error("elasticsearch updateDataByCondition error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch updateDataByCondition error , meassage=" + e.getMessage()); } return resp.getStatus().getUpdated() > 0; } public T selectDataById(String indexName, String id, Class c) { Assert.hasLength(indexName, "Elasticsearch exception indexName null"); Assert.hasLength(id, "Elasticsearch exception id null"); GetResponse response = null; try { //设置查询的索引、文档 GetRequest indexRequest = new GetRequest(indexName, id); response = restHighLevelClient.get(indexRequest, RequestOptions.DEFAULT); } catch (Exception e) { log.error("elasticsearch selectDataById error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch selectDataById error , meassage=" + e.getMessage()); } String res = response.getSourceAsString(); return JSONObject.parseObject(res, c); } public List selectDataList(String indexName, List conditionFileds, Class c) { Assert.hasLength(indexName, "Elasticsearch exception indexName null"); Assert.notNull(c, "Class is null "); List res = null; try { // 创建检索请求 SearchRequest searchRequest = new SearchRequest(); // 指定索引 searchRequest.indices(indexName); SearchSourceBuilder searchSourceBuilder = buildSearchSourceBuilder(conditionFileds); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); //分析结果 SearchHit[] hits = searchResponse.getHits().getHits(); res = new ArrayList<>(); for (SearchHit hit : hits ) { String data = hit.getSourceAsString(); T t = JSONObject.parseObject(data, c); log.info("data={}", data); res.add(t); } } catch (Exception e) { log.error("elasticsearch selectDataList error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch selectDataList error , meassage=" + e.getMessage()); } return res; } public EsPage selectDataPage(String indexName, Integer pageNum, Integer pageSize, List conditionFileds, Class c) { Assert.hasLength(indexName, "Elasticsearch exception indexName null"); Assert.notNull(c, "Class is null "); List res = null; //总记录数 Integer total = 0; try { // 创建检索请求 SearchRequest searchRequest = new SearchRequest(); // 指定索引 searchRequest.indices(indexName); SearchSourceBuilder searchSourceBuilder = buildSearchSourceBuilder(conditionFileds); //设置分页 searchSourceBuilder.from((pageNum - 1) * pageSize).size(pageSize); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); //分析结果 SearchHit[] hits = searchResponse.getHits().getHits(); total = new Long(searchResponse.getHits().getTotalHits().value).intValue(); res = new ArrayList<>(); for (SearchHit hit : hits ) { String data = hit.getSourceAsString(); T t = JSONObject.parseObject(data, c); log.info("data={}", data); res.add(t); } } catch (Exception e) { log.error("elasticsearch selectDataPage error , meassage = {}", e.getMessage()); //打印轨迹 log.error(e.getMessage(), e); throw new BusinessException("elasticsearch selectDataPage error , meassage=" + e.getMessage()); } return new EsPage<>(pageNum, pageSize, total, res); } private static SearchSourceBuilder buildSearchSourceBuilder(List conditionFileds) { // 指定DSL SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //构建条件 if (!CollectionUtils.isEmpty(conditionFileds)) { for (EsField condFiled : conditionFileds) { switch (condFiled.getFieldTypeEnum()) { case ORDER_ASC: //升序 searchSourceBuilder.sort(condFiled.getField(), SortOrder.ASC); break; case ORDER_ESC: //降序 searchSourceBuilder.sort(condFiled.getField(), SortOrder.DESC); break; case VAGUE_QUERY: // 模糊查询 searchSourceBuilder.query(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()).fuzziness(Fuzziness.AUTO)); break; case PRECISE_QUERY: searchSourceBuilder.query(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue())); break; default: //默认精准查询 searchSourceBuilder.query(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue())); break; } } } return searchSourceBuilder; } private void setDeletCondition(List conditionFileds, DeleteByQueryRequest request) { if (!CollectionUtils.isEmpty(conditionFileds)) { for (EsField condFiled : conditionFileds) { switch (condFiled.getFieldTypeEnum()) { case VAGUE_QUERY: // 模糊查询 request.setQuery(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()).fuzziness(Fuzziness.AUTO)); break; case PRECISE_QUERY: request.setQuery(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue())); break; default: log.error("field type error ,only supprt VAGUE_QUERY and PRECISE_QUERY"); throw new BusinessException(" field type error ,only supprt VAGUE_QUERY and PRECISE_QUERY"); } } } } private void setUpdateConfition(List conditionFileds, UpdateByQueryRequest request) { if (!CollectionUtils.isEmpty(conditionFileds)) { for (EsField condFiled : conditionFileds) { switch (condFiled.getFieldTypeEnum()) { case VAGUE_QUERY: // 模糊查询 request.setQuery(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()).fuzziness(Fuzziness.AUTO)); break; case PRECISE_QUERY: request.setQuery(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue())); break; default: log.error("field type error ,only supprt VAGUE_QUERY and PRECISE_QUERY"); throw new BusinessException(" field type error ,only supprt VAGUE_QUERY and PRECISE_QUERY"); } } } } private StringBuffer buildscriptContext(Object data) { //准备文档 String jsonString = JSONObject.toJSonString(data); Map jsonMap = JSONObject.parseObject(jsonString, Map.class); String tem = "ctx._source['key']='value'"; StringBuffer scriptContext = new StringBuffer(); for (String key : jsonMap.keySet()) { String value = jsonMap.get(key); scriptContext.append(tem.replace("key", key).replace("value", value)) .append(";"); } return scriptContext; } }
package cn.hsa.utils.elasticsearch; import lombok.Data; @Data public class EsbaseData { //索引 public String indexName; //id public String esId; }查询条件对象
package cn.hsa.utils.elasticsearch; import lombok.Data; @Data public class EsField { //字段对应 *** 作功能 private FieldTypeEnum fieldTypeEnum; //字段名称 private String field; //字段对应的值 private String value; public EsField(){ } public EsField(String field ,String value , FieldTypeEnum fieldTypeEnum){ this.value = value; this.field = field; this.fieldTypeEnum = fieldTypeEnum; } }分页对象
package cn.hsa.utils.elasticsearch; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Map; public class EsPage{ //当前页的数量 private int size; private int pageNum; private int pageSize; private int total; private List list; private int pages; private int beginPageIndex; private int endPageIndex; public EsPage(int pageNum, int pageSize, int total, List list) { this.pageNum = pageNum; this.pageSize = pageSize; this.total = total; this.list = list; this.size = CollectionUtils.isEmpty(list)?0:list.size(); // 计算总页码 pages =pageSize==0?0:(total + pageSize - 1) / pageSize; // 计算 beginPageIndex 和 endPageIndex // >> 总页数不多于10页,则全部显示 if (pages <= 10) { beginPageIndex = 1; endPageIndex = pages; } // >> 总页数多于10页,则显示当前页附近的共10个页码 else { // 当前页附近的共10个页码(前4个 + 当前页 + 后5个) beginPageIndex = pageNum - 4; endPageIndex = pageNum + 5; // 当前面的页码不足4个时,则显示前10个页码 if (beginPageIndex < 1) { beginPageIndex = 1; endPageIndex = 10; } // 当后面的页码不足5个时,则显示后10个页码 if (endPageIndex > pages) { endPageIndex = pages; beginPageIndex = pages - 10 + 1; } } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public int getBeginPageIndex() { return beginPageIndex; } public void setBeginPageIndex(int beginPageIndex) { this.beginPageIndex = beginPageIndex; } public int getEndPageIndex() { return endPageIndex; } public void setEndPageIndex(int endPageIndex) { this.endPageIndex = endPageIndex; } public List getList() { return list; } public void setList(List list) { this.list = list; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } }
条件数据类型枚举
package cn.hsa.utils.elasticsearch; public enum FieldTypeEnum { //精准查询 PRECISE_QUERY, //模糊查询 VAGUE_QUERY, //排序_升序 ORDER_ASC, //排序_降序 ORDER_ESC ; }父maven依赖
7.2.0 org.elasticsearch elasticsearch${elasticsearch.version} org.elasticsearch.client elasticsearch-rest-high-level-client${elasticsearch.version} org.elasticsearch.client elasticsearch-rest-client${elasticsearch.version}
子maven依赖
测试类org.elasticsearch.client elasticsearch-rest-high-level-clientorg.elasticsearch elasticsearchorg.elasticsearch.client elasticsearch-rest-clientorg.elasticsearch elasticsearch
package cn.hsa.csc.query.service.es; import cn.hsa.csc.query.dto.PageDTO; import cn.hsa.hsaf.core.framework.web.HsafRestPath; import cn.hsa.hsaf.core.framework.web.WrapperResponse; import cn.hsa.utils.elasticsearch.*; import com.alibaba.fastjson.JSONObject; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.poi.ss.formula.functions.T; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestMethod; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; @Slf4j @HsafRestPath(value = "/api/Es") @Service public class EsTestService { @Autowired ElasticsearchUtils elasticsearchUtils; @HsafRestPath(value = "/add", method = RequestMethod.POST) public WrapperResponse add(EsObj esObj) { // MapjsonMap = new HashMap<>(); // jsonMap.put("name", "spring cloud实战"); // jsonMap.put("description", "本课程主要从四个章节进行讲解:1.微服务架构入门。2.spring cloud 实战。3.实战spring。4.。。"); // jsonMap.put("studymodel", "201001"); // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // jsonMap.put("timestamp", dateFormat.format(new Date())); // jsonMap.put("price", 5.6f); boolean b = elasticsearchUtils.addData(esObj.getIndexName(), UUID.randomUUID().toString(), esObj.getDta()); return WrapperResponse.success(b); } @HsafRestPath(value = "/getDataById", method = RequestMethod.POST) public WrapperResponse getDataById(EsObj esObj) { EsTestRes doc = elasticsearchUtils.selectDataById(esObj.getIndexName(), esObj.getId(), EsTestRes.class); return WrapperResponse.success(doc); } @HsafRestPath(value = "/getDataByCondition", method = RequestMethod.POST) public WrapperResponse getDataByCondition(EsObj esObj) { List conditionFileds = new ArrayList<>(); if (esObj.getDta() != null) { String s = JSONObject.toJSonString(esObj.getDta()); EsTestRes esTestRes = JSONObject.parseObject(s, EsTestRes.class); conditionFileds.add(new EsField("name", esTestRes.getName(), FieldTypeEnum.VAGUE_QUERY)); } EsPage list = elasticsearchUtils.selectDataPage(esObj.getIndexName(),esObj.getPageNo(),esObj.getPageSize(), conditionFileds, EsTestRes.class); return WrapperResponse.success(list); } @HsafRestPath(value = "/addOrUpdateData", method = RequestMethod.POST) public WrapperResponse addOrUpdateData(EsObj esObj) { boolean b = elasticsearchUtils.addOrUpdateData(esObj.getIndexName(), esObj.getId(), esObj.getDta()); return WrapperResponse.success(b); } @HsafRestPath(value = "/addBatchData", method = RequestMethod.POST) public WrapperResponse addBatchData(EsObj esObj) { List datas = new ArrayList<>(); datas.add(new EsTestRes(UUID.randomUUID().toString(), esObj.getIndexName(), "5.5", "201001", "张三", "你说啥就是啥1")); datas.add(new EsTestRes(UUID.randomUUID().toString(), esObj.getIndexName(), "6.5", "201002", "张三", "你说啥就是啥2")); datas.add(new EsTestRes(UUID.randomUUID().toString(), esObj.getIndexName(), "7.5", "201003", "张三", "你说啥就是啥3")); datas.add(new EsTestRes(UUID.randomUUID().toString(), esObj.getIndexName(), "8.5", "201004", "张三", "你说啥就是啥4")); boolean b = elasticsearchUtils.addBatchData(esObj.getIndexName(), datas); return WrapperResponse.success(b); } @HsafRestPath(value = "/deleteDataByCondition", method = RequestMethod.POST) public WrapperResponse deleteDataByCondition(EsObj esObj) { List conditionFileds = new ArrayList<>(); if (esObj.getDta() != null) { String s = JSONObject.toJSonString(esObj.getDta()); EsTestRes esTestRes = JSONObject.parseObject(s, EsTestRes.class); conditionFileds.add(new EsField("name", esTestRes.getName(), FieldTypeEnum.VAGUE_QUERY)); } boolean b = elasticsearchUtils.deleteDataByCondition(esObj.getIndexName(), conditionFileds); return WrapperResponse.success(b); } @HsafRestPath(value = "/updateDataByCondition", method = RequestMethod.POST) public WrapperResponse updateDataByCondition(EsObj esObj) { List conditionFileds = new ArrayList<>(); if (esObj.getDta() != null) { String s = JSONObject.toJSonString(esObj.getDta()); EsTestRes esTestRes = JSONObject.parseObject(s, EsTestRes.class); conditionFileds.add(new EsField("name", esTestRes.getName(), FieldTypeEnum.VAGUE_QUERY)); } boolean b = elasticsearchUtils.updateDataByCondition(esObj.getIndexName(), conditionFileds,new EsTestRes("1","2","王五","4")); return WrapperResponse.success(b); } @HsafRestPath(value = "/deleteDataById", method = RequestMethod.POST) public WrapperResponse deleteDataById(EsObj esObj) { boolean b = elasticsearchUtils.deleteDataById(esObj.getIndexName(), esObj.getId()); return WrapperResponse.success(b); } @Data public static class EsObj extends PageDTO { private String indexName; private String typeName; private String id; private Object dta; } @Data public static class EsTestRes extends EsbaseData { private String price; private String studymodel; private String name; private String description; public EsTestRes() { } public EsTestRes(String esId, String idexName, String price, String studymodel, String name, String description) { this.esId = esId; this.indexName = idexName; this.price = price; this.studymodel = studymodel; this.name = name; this.description = description; } public EsTestRes(String price, String studymodel, String name, String description) { this.price = price; this.studymodel = studymodel; this.name = name; this.description = description; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)