专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

springboot项目中使用elasticsearch文件数据库

1、安装并启动elasticsearch后,新建springboot项目

安装elasticsearch:https://my.oschina.net/lion1220/blog/3149306

2、创建项目,并导入 elasticsearch jar包

org.springframework.boot
spring-boot-starter-data-elasticsearch

3、properties文件中添加配置项

spring.data.elasticsearch.client.reactive.endpoints=127.0.0.1:9200
spring.data.elasticsearch.client.reactive.connection-timeout=100000
spring.data.elasticsearch.client.reactive.socket-timeout=5000
spring.data.elasticsearch.client.reactive.use-ssl=false
spring.data.elasticsearch.repositories.enabled=true

spring.elasticsearch.rest.uris=${spring.data.elasticsearch.client.reactive.endpoints}
spring.elasticsearch.rest.connection-timeout=${spring.data.elasticsearch.client.reactive.connection-timeout}
spring.elasticsearch.rest.read-timeout=${spring.data.elasticsearch.client.reactive.socket-timeout}

4、创建数据实体类

@ApiModel(description = "Goods实体")
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Accessors(chain = true)
@Document(indexName = "big_data_center_goods", type = "goods", shards = 1, replicas = 0)
public class Goods implements Serializable {

    @ApiModelProperty(value = "主键ID", example = "ce2e7aaf4ecd45e59967668d06441dc9")
    @Id
    private String id;
    @ApiModelProperty(value = "店铺编码", example = "123456")
    private String shopCode;
    @ApiModelProperty(value = "商品名称", example = "商品名称")
    private String goodsName;
    @ApiModelProperty(value = "商品价格", example = "123.1")
    private BigDecimal price;
    @ApiModelProperty(value = "商品描述", example = "商品描述")
    private String desc;
    @ApiModelProperty(value = "创建时间", example = "2020-03-29 15:52:11")
    private String createTime;
}

5、创建Dao类

@Repository
public interface GoodsRepository extends ElasticsearchRepository<Goods, String> {

    @Query("{\"query\":{\"match\":{\"shopName\":\"?0\"}}}")
    Page<Goods> findByGoodsName(String shopName, Pageable pageable);

    @Query("{\"query\":{\"match\":{\"shopCode\":\"?0\"}}}")
    Page<Goods> findByShopCode(String shopCode, Pageable pageable);
}

6、创建service类

public interface IGoodsService {

    Optional<Goods> findById(String id);

    Goods save(Goods blog);

    void delete(Goods blog);

    Goods update(Goods blog);

    Optional<Goods> findOne(String id);

    Iterable<Goods> findAll();

    Page<Goods> findByShopName(String shopName, Pageable pageable);

    Page<Goods> findByShopCode(String shopCode, Pageable pageable);
}
@Slf4j
@Service
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    @Qualifier("goodsRepository")
    private GoodsRepository goodsRepository;

    @Override
    public Optional<Goods> findById(String id) {
        Optional<Goods> optionalShop = null;
        try {
            optionalShop = goodsRepository.findById(id);
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
        }
        return optionalShop;
    }

    @Override
    public Goods save(Goods blog) {
        Goods shop = null;
        try {
            shop = goodsRepository.save(blog);
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
        }
        return shop;
    }

    @Override
    public void delete(Goods blog) {
        try {
            goodsRepository.delete(blog);
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
        }
    }

    @Override
    public Goods update(Goods blog) {
        Goods tmp = null;
        try {
            if (StringUtils.isBlank(blog.getId())) {
                return null;
            }
            Optional<Goods> optional = findById(blog.getId());
            if (optional != null) {
                tmp = optional.get();
            }
            if (tmp != null) {
                BeanUtils.copyProperties(blog, tmp);
                goodsRepository.save(tmp);
            }
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
        }
        return tmp;
    }

    @Override
    public Optional<Goods> findOne(String id) {
        Optional<Goods> optionalShop = null;
        try {
            optionalShop = goodsRepository.findById(id);
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
        }
        return optionalShop;
    }

    @Override
    public Iterable<Goods> findAll() {
        Iterable<Goods> shops = null;
        try {
            shops = goodsRepository.findAll();
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
        }
        return shops;
    }

    @Override
    public Page<Goods> findByShopName(String shopName, Pageable pageable) {
        Page<Goods> shopPage = null;
        try {
            shopPage = goodsRepository.findByGoodsName(shopName, pageable);
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
        }
        return shopPage;
    }

    @Override
    public Page<Goods> findByShopCode(String shopCode, Pageable pageable) {
        Page<Goods> shopPage = null;
        try {
            shopPage = goodsRepository.findByShopCode(shopCode, pageable);
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
        }
        return shopPage;
    }
}

7、创建Action 接口类

@Api(value = "商品接口")
@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    IGoodsService goodsService;

    @ApiOperation(value = "根据id查询商品信息", notes="根据id查询商品信息", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "商品id", required = true, dataType = "String", paramType = "query", example = "d63b7330b7fd443380326d78ad3966f6")
    @GetMapping(value = "/findById")
    public ResponseEntity<Optional<Goods>> findById(@RequestParam("id") String id) {
        Optional<Goods> data = goodsService.findById(id);
        return new ResponseEntity<>(data, HttpStatus.OK);
    }

    @ApiOperation(value = "根据店铺编码查询商品信息", notes="根据店铺编码查询商品信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopCode", value = "编码", required = true, dataType = "String", paramType = "query", example = "000001"),
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "int", paramType = "query", example = "10")
    })
    @GetMapping(value = "/findByShopCode")
    public ResponseEntity<Page<Goods>> findByShopCode(@RequestParam("shopCode") String shopCode,
            @RequestParam("page") int page, @RequestParam("size") int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime"));
        Page<Goods> data = goodsService.findByShopCode(shopCode, pageable);
        return new ResponseEntity<>(data, HttpStatus.OK);
    }

    @ApiOperation(value = "新增商品信息", notes="新增商品信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsName", value = "商品名称", required = true, dataType = "String", paramType = "query", example = "商品名称"),
            @ApiImplicitParam(name = "shopCode", value = "店铺编码", required = true, dataType = "String", paramType = "query", example = "000001"),
            @ApiImplicitParam(name = "price", value = "售价", required = true, dataType = "int", paramType = "query", example = "10.5"),
            @ApiImplicitParam(name = "desc", value = "描述", required = true, dataType = "String", paramType = "query", example = "描述")
    })
    @PostMapping(value = "/createGoods", produces = {"application/json"}, consumes = {"application/json"})
    public ResponseEntity<Goods> createGoods(@RequestBody Goods goods) {
        String id = UUID.randomUUID().toString().replace("-", "");
        String createTime = DateUtil.date2Str(new Date());
        goods.setId(id);
        goods.setCreateTime(createTime);
        Goods data = goodsService.save(goods);
        return new ResponseEntity<>(data, HttpStatus.OK);
    }
}

8、浏览器打开 http://localhost:8080/swagger-ui.html,测试接口,结果如下

103_1.png

9、elasticsearch简单操作工具类

@Component
public class EsRestClientUtil {

    private static RestHighLevelClient client;

    @Autowired
    public EsRestClientUtil(RestHighLevelClient client) {
        this.client = client;
    }

    //==================== 保存 ↓ ==============================

    public static IndexResponse save(String index, String type, String id, Map<String, Object> source) throws IOException {
        IndexRequest indexRequest = new IndexRequest(index, type, id);
        indexRequest.source(source);
        return client.index(indexRequest, RequestOptions.DEFAULT);
    }

    public static IndexResponse save(String index, String type, Map<String, Object> source) throws IOException {
        String id = null;
        if (source.containsKey("id")) {
            Object idObj = source.get("id");
            id = idObj == null ? UUID.randomUUID().toString().replace("-", "") : String.valueOf(idObj);
        }
        IndexRequest indexRequest = new IndexRequest(index, type, id);
        indexRequest.source(source);
        return client.index(indexRequest, RequestOptions.DEFAULT);
    }

    public static int saveBatch(String index, String type, List<Map<String, Object>> sourceList) throws IOException {
        int count = 0;
        if (!CollectionUtils.isEmpty(sourceList)) {
            String id = null;
            for (Map<String, Object> source : sourceList) {
                id = UUID.randomUUID().toString().replace("-", "");
                IndexRequest indexRequest = new IndexRequest(index, type, id);
                indexRequest.source(source);
                client.index(indexRequest, RequestOptions.DEFAULT);
            }
        }
        return count;
    }

    //==================== 更新 ↓ ==============================

    public static UpdateResponse update(String index, String type, String id, Map<String, Object> source) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(index, type, id);
        updateRequest.doc(source);
        return client.update(updateRequest, RequestOptions.DEFAULT);
    }

    public static Object saveOrUpdate(String index, String type, String id, Map<String, Object> source) throws IOException {
        Object result = null;
        if (exists(index, type, id)) {
            result = update(index, type, id, source);
        } else {
            result = save(index, type, id, source);
        }
        return result;
    }

    //==================== 判断是否存在 ↓ ==============================

    public static boolean exists(String index) throws IOException {
        return exists(index, null);
    }

    public static boolean exists(String index, String type) throws IOException {
        return exists(index, type, null);
    }

    public static boolean exists(String index, String type, String id) throws IOException {
        GetRequest getRequest = new GetRequest(index);
        if (StringUtils.isNotBlank(type)) {
            getRequest.type(type);
        }
        if (StringUtils.isNotBlank(id)) {
            getRequest.id(id);
        }
        return client.exists(getRequest, RequestOptions.DEFAULT);
    }

    //==================== 数量 ↓ ==============================

    /*public static void count(String index, String type) throws IOException {
        //CountRequest countRequest = new CountRequest(index, type);
    }*/

    //==================== 查询 ↓ ==============================

    public static GetResponse queryById(String index, String type, String id) throws IOException {
        GetRequest getRequest = new GetRequest(index, type, id);
        return client.get(getRequest, RequestOptions.DEFAULT);
    }

    private static SearchResponse queryPage(String[] index, String[] type, Page page) throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(page.getStartRow());
        sourceBuilder.size(page.getPageSize());
        if (!CollectionUtils.isEmpty(page.getTermQueryMap())) {
            Map<String, Object> conditionMap = page.getTermQueryMap();
            for (Map.Entry<String, Object> entry : conditionMap.entrySet()) {
                sourceBuilder.query(QueryBuilders.termQuery(entry.getKey(), entry.getValue()));
            }
        }
        if (!CollectionUtils.isEmpty(page.getSortMap())) {
            Map<String, SortOrder> sortMap = page.getSortMap();
            for (Map.Entry<String, SortOrder> entry : sortMap.entrySet()) {
                sourceBuilder.sort(entry.getKey(), entry.getValue());
            }
        }

        SearchRequest request = new SearchRequest(index);
        if (type != null && type.length > 0) {
            request.types(type);
        }
        request.source(sourceBuilder);
        return client.search(request, RequestOptions.DEFAULT);
    }

    public static SearchResponse queryPageByIndexAndType(String[] index, String[] type, Page page) throws IOException {
        return queryPage(index, type, page);
    }

    public static SearchResponse queryPageByIndex(String[] index, Page page) throws IOException {
        return queryPageByIndexAndType(index, null, page);
    }

    public static List<JSONObject> queryJsonByIndexAndType(String[] index, String[] type, Page page) throws IOException {
        SearchResponse response = queryPageByIndexAndType(index, type, page);
        SearchHits hits = response.getHits();

        List<JSONObject> list = new ArrayList<>();
        if (hits != null) {
            SearchHit[] hitsArr = response.getHits().getHits();
            for (SearchHit searchHit : hitsArr) {
                list.add(JSON.parseObject(JSON.toJSONString(searchHit), JSONObject.class));
            }
        }
        return list;
    }

    public static List<JSONObject> queryJsonByIndex(String[] index, Page page) throws IOException {
        return queryJsonByIndexAndType(index, null, page);
    }

    public static SearchResponse queryPageByRange(String[] index, String[] type, Page page) throws IOException {
        Map<String, Object[]> rangeMap = page.getRangeQueryMap();
        Map<String, Object> termQueryMap = page.getTermQueryMap();
        FunctionScoreQueryBuilder.FilterFunctionBuilder[] rangeBuilder = null;
        int count = 0;

        if (!CollectionUtils.isEmpty(rangeMap)) {
            rangeBuilder = new FunctionScoreQueryBuilder.FilterFunctionBuilder[rangeMap.size()];
            if (!CollectionUtils.isEmpty(rangeMap) && !CollectionUtils.isEmpty(termQueryMap)) {
                rangeBuilder = new FunctionScoreQueryBuilder.FilterFunctionBuilder[rangeMap.size() + termQueryMap.size()];
            }
            String rangeName = null;
            Object rangeValLeft = null;
            Object rangeValRight = null;

            for (Map.Entry<String, Object[]> entry : rangeMap.entrySet()) {
                rangeName = entry.getKey();
                rangeValLeft = entry.getValue()[0];
                rangeValRight = entry.getValue()[1];

                rangeBuilder[count] = new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        rangeQuery(rangeName).from(rangeValLeft).to(rangeValRight), weightFactorFunction((count + 1))
                );
                count++;
            }
        }

        if (!CollectionUtils.isEmpty(termQueryMap)) {
            String sourceName = null;
            Object sourceVal = null;
            if (count < 1) {
                rangeBuilder = new FunctionScoreQueryBuilder.FilterFunctionBuilder[termQueryMap.size()];
            }
            for (Map.Entry<String, Object> entry : termQueryMap.entrySet()) {
                sourceName = entry.getKey();
                sourceVal = entry.getValue();

                rangeBuilder[count] = new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        QueryBuilders.termQuery(sourceName, sourceVal), weightFactorFunction((count + 1))
                );
                count++;
            }
        }

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(page.getStartRow());
        sourceBuilder.size(page.getPageSize());
        if (null != rangeBuilder) {
            sourceBuilder.query(QueryBuilders.functionScoreQuery(rangeBuilder));
        }
        SearchRequest searchRequest = new SearchRequest(index);
        if (null != type && type.length > 0) {
            searchRequest.types(type);
        }
        searchRequest.source(sourceBuilder);
        return client.search(searchRequest, RequestOptions.DEFAULT);
    }

    public static SearchResponse queryPageByRange(String[] index, Page page) throws Exception {
        return queryPageByRange(index, null, page);
    }

    public static SearchResponse queryByBuilder(String[] index, SearchSourceBuilder sourceBuilder) throws Exception {
        SearchRequest searchRequest = new SearchRequest(index);
        if (null != sourceBuilder) {
            searchRequest.source(sourceBuilder);
        }
        return client.search(searchRequest, RequestOptions.DEFAULT);
    }

    public static MultiGetResponse mget(List<MultiGetRequest.Item> requests) throws Exception {
        MultiGetRequest request = new MultiGetRequest();
        if (!CollectionUtils.isEmpty(requests)) {
            requests.stream().forEach(request::add);
        }
        return client.mget(request, RequestOptions.DEFAULT);
    }

    public static MultiSearchResponse msearch(List<SearchRequest> requests) throws Exception {
        MultiSearchRequest request = new MultiSearchRequest();
        if (!CollectionUtils.isEmpty(requests)) {
            requests.stream().forEach(request::add);
        }
        return client.msearch(request, RequestOptions.DEFAULT);
    }
}

源码示例:https://gitee.com/lion123/springboot-elasticsearch-demo

文章永久链接:https://tech.souyunku.com/24949

未经允许不得转载:搜云库技术团队 » springboot项目中使用elasticsearch文件数据库

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们