es中的一些api使用
Posted 曹军
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了es中的一些api使用相关的知识,希望对你有一定的参考价值。
尽量写一些通用的service。还能再抽象的,暂时先不继续了。
1.新建测试用的mapping
PUT /nba { "mappings": { "properties": { "jerseNo" : { "type" : "keyword" }, "name" : { "type" : "text" }, "playYear" : { "type" : "long" }, "position" : { "type" : "text" }, "teamName" : { "type" : "text" } } } }
2.程序结构
3.controller
package com.jun.fastpro.controller; import com.jun.fastpro.business.EsOperateBusiness; import com.jun.fastpro.common.domain.response.BaseResponse; import com.jun.fastpro.dto.EsDto; import com.jun.fastpro.dto.NbaDto; import com.jun.fastpro.service.EsCurdService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import jdk.nashorn.internal.objects.annotations.Getter; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.io.IOException; import java.util.List; import java.util.Map; @RestController @Api(value = "es主方法", tags = "es的control") public class EsOperateController { @Resource private EsCurdService esCurdService; @Resource private EsOperateBusiness esOperateBusiness; private static final String INDEX = "nba"; @ApiOperation("ping es服务器") @GetMapping("/ping") public boolean ping(){ boolean ping = esCurdService.ping(); return ping; } // ================================文档的操作================== @ApiOperation("新增文档") @PostMapping("/add") public BaseResponse<Boolean> add(@RequestBody EsDto<NbaDto> esDto){ boolean add = esOperateBusiness.add(esDto, INDEX, "1"); return BaseResponse.createSuccessResult(add); } @ApiOperation("查询文档") @PostMapping("/get") public BaseResponse<Map> get(){ Map map = esOperateBusiness.get(INDEX, "1"); return BaseResponse.createSuccessResult(map); } @ApiOperation("更新文档") @PostMapping("/update") public BaseResponse<Boolean> update(@RequestBody EsDto<NbaDto> esDto){ boolean update = esOperateBusiness.update(esDto, INDEX, "1"); return BaseResponse.createSuccessResult(update); } @ApiOperation("删除文档") @PostMapping("/delete") public BaseResponse<Boolean> delete(){ boolean delete = esOperateBusiness.delete(INDEX, "1"); return BaseResponse.createSuccessResult(delete); } // =====================================查询====================== @ApiOperation("match查詢") @PostMapping("/match") public BaseResponse<List<NbaDto>> searchMatch(){ String key = "name"; String value = "tom"; List<NbaDto> esDtos = esOperateBusiness.searchMatch(INDEX, key, value); return BaseResponse.createSuccessResult(esDtos); } @ApiOperation("term查詢") @PostMapping("/term") public BaseResponse<List<NbaDto>> searchTerm(){ String key = "playYear"; String value = "20"; List<NbaDto> esDtos = esOperateBusiness.searchTerm(INDEX, key, value); return BaseResponse.createSuccessResult(esDtos); } }
4.bussiness
package com.jun.fastpro.business; import com.jun.fastpro.common.domain.response.BaseResponse; import com.jun.fastpro.dto.EsDto; import com.jun.fastpro.dto.NbaDto; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; import java.util.Map; /** * 用于业务将service分开 */ public interface EsOperateBusiness { /** * 新增文档 */ public boolean add(EsDto<NbaDto> esDto, String index, String id); /** * 查询文档 */ public Map get(String index, String id); /** * 更新文档 */ public boolean update(EsDto<NbaDto> esDto, String index, String id); /** * 删除文档 */ public boolean delete(String index, String id); /** * match查询 */ public List<NbaDto> searchMatch(String index, String key, String value); /** * term查询 */ public List<NbaDto> searchTerm(String index, String key, String value); }
5.businessImpl
package com.jun.fastpro.business.impl; import com.jun.fastpro.business.EsOperateBusiness; import com.jun.fastpro.common.utils.BeanToMapUtils; import com.jun.fastpro.dto.EsDto; import com.jun.fastpro.dto.NbaDto; import com.jun.fastpro.service.EsCurdService; import org.dozer.Mapper; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Component public class EsOperateBusinessImpl implements EsOperateBusiness { @Resource private EsCurdService esCurdService; @Override public boolean add(EsDto<NbaDto> esDto, String index, String id) { // 将DTO转为map NbaDto model = esDto.getModel(); Map<String, Object> stringObjectMap = BeanToMapUtils.beanToMap(model); return esCurdService.add(stringObjectMap, index, id); } /** * 查询文档 */ @Override public Map get(String index, String id){ return esCurdService.get(index, id); } /** * 更新文档 */ @Override public boolean update(EsDto<NbaDto> esDto, String index, String id) { // 将DTO转为map NbaDto model = esDto.getModel(); Map<String, Object> stringObjectMap = BeanToMapUtils.beanToMap(model); return esCurdService.update(stringObjectMap, index, id); } /** * 删除文档 */ public boolean delete(String index, String id){ return esCurdService.delete(index, id); } /** * match查询 */ public List<NbaDto> searchMatch(String index, String key, String value){ return esCurdService.searchMatch(index, key, value); } /** * term查询 */ public List<NbaDto> searchTerm(String index, String key, String value){ return esCurdService.searchTerm(index, key, value); } }
6.service
package com.jun.fastpro.service; import com.jun.fastpro.dto.EsDto; import com.jun.fastpro.dto.NbaDto; import java.io.IOException; import java.util.List; import java.util.Map; /** * @Descrotion 这里是一个通用的es功能service */ public interface EsCurdService { /** * 检查集群是否可用 */ public boolean ping(); /** * 增加文档 */ public boolean add(Map map, String index, String id); /** * 查询文档 */ public Map get(String index, String id); /** * 更新文档 */ public boolean update(Map map, String index, String id); /** * 删除文档 */ public boolean delete(String index, String id); /** * match查询 */ public List<NbaDto> searchMatch(String index, String key, String value); /** * term查询 */ public List<NbaDto> searchTerm(String index, String key, String value); }
7.serviceImpl
package com.jun.fastpro.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.jun.fastpro.dto.EsDto; import com.jun.fastpro.dto.NbaDto; import com.jun.fastpro.service.EsCurdService; import lombok.extern.slf4j.Slf4j; 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.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.springframework.cglib.beans.BeanMap; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; import java.util.*; /** * @Descrotion 这里是一个通用的es功能service */ @Service @Slf4j public class EsCurdServiceImpl implements EsCurdService { @Resource private RestHighLevelClient highLevelClient; /** * 检查集群是否可用 * 虽然es不可用了,但是不会起阻断性的结果,程序是依然进行运行的 */ public boolean ping(){ try { boolean pin = highLevelClient.ping(RequestOptions.DEFAULT); return pin; } catch (IOException e) { e.printStackTrace(); log.info("继续运行"); } return false; } /** * 增加 */ public boolean add(Map stringObjectMap, String index, String id){ if(Objects.isNull(stringObjectMap)){ return false; } // 执行 IndexRequest indexRequest = new IndexRequest(index).id(id).source(stringObjectMap); try { IndexResponse response = highLevelClient.index(indexRequest, RequestOptions.DEFAULT); log.info("增加返回结果:{}", JSONObject.toJSON(response)); } catch (IOException e) { e.printStackTrace(); } return true; } /** * 查询文档 */ public Map get(String index, String id){ GetRequest getRequest = new GetRequest(index, id); try { GetResponse response = highLevelClient.get(getRequest, RequestOptions.DEFAULT); return response.getSource(); } catch (IOException e) { e.printStackTrace(); } return Maps.newHashMap(); } /** * 更新文档 */ public boolean update(Map map, String index, String id){ UpdateRequest updateRequest = new UpdateRequest(index, id).doc(map); try { UpdateResponse response = highLevelClient.update(updateRequest, RequestOptions.DEFAULT); log.info("更新文档返回结果:{}", JSONObject.toJSON(response)); return true; } catch (IOException e) { e.printStackTrace(); } return false; } /** * 删除文档 */ public boolean delete(String index, String id){ DeleteRequest deleteRequest = new DeleteRequest(index, id); try { DeleteResponse response = highLevelClient.delete(deleteRequest, RequestOptions.DEFAULT); log.info("删除文档返回结果:{}", JSONObject.toJSON(response)); return true; } catch (IOException e) { e.printStackTrace(); } return false; } /** * match查询 */ public List<NbaDto> searchMatch(String index, String key, String value){ // 组装 MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(key, value); // 公共查询 SearchResponse searchResponse = commonQuery(index, matchQueryBuilder, 0, 10); if(Objects.nonNull(searchResponse)){ // 解析 return commonParseResponse(searchResponse, NbaDto.class); } return null; } /** * term查询 */ public List<NbaDto> searchTerm(String index, String key, String value){ // 组装 TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(key, value); // 公共查询 SearchResponse searchResponse = commonQuery(index, termQueryBuilder, 0, 10); if(Objects.nonNull(searchResponse)){ // 解析 return commonParseResponse(searchResponse, NbaDto.class); } return null; } /** * 公共的查询 */ private SearchResponse commonQuery(String index, QueryBuilder queryBuilder, int from, int size){ SearchRequest searchRequest = new SearchRequest(index); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(queryBuilder); searchSourceBuilder.from(from); searchSourceBuilder.size(size); searchRequest.source(searchSourceBuilder); try { return highLevelClient.search(searchRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 公共的解析 */ private <T> List<T> commonParseResponse(SearchResponse response, Class<T> esDto){ SearchHit[] hits = response.getHits().getHits(); List resultList = Lists.newArrayList(); for (SearchHit hit : hits){ T t = JSONObject.parseObject(hit.getSourceAsString(), esDto); resultList.add(t); } return resultList; } }
8.BeanToMapUtils
package com.jun.fastpro.common.utils; import org.springframework.cglib.beans.BeanMap; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class BeanToMapUtils { /** * 将bean转为map */ public static <T> Map<String,Object> beanToMap(T model){ Map<String, Object> map = new HashMap<>(); if(Objects.nonNull(model)){ BeanMap beanMap = BeanMap.create(model); for (Object key : beanMap.keySet()){ if (Objects.nonNull(beanMap.get(key))){ map.put(key+"", beanMap.get(key)); } } } return map; } }
9.application.properties
spring.elasticsearch.rest.uris=http://10.1.1.4:9200 server.port=9092
以上是关于es中的一些api使用的主要内容,如果未能解决你的问题,请参考以下文章