赞
踩
此文适合了解了es相关概念以及基础知识的同学阅读
提示:以下是本篇文章正文内容,下面案例可供参考
Elasticsearch 是一个实时的分布式存储、搜索、分析的引擎。(全文引擎)
系统:windows 10
elasticsearch官网下载地址
下载好对应的windows版本,解压到任意工作目录,es的安装非常方便,解压即用。
刚下载的es默认的分词器只能分解英文,对于中文不太友好。所以我们需要为es下载安装IK分词器
IK分词器下载:
Ik分词器下载地址,分词器下载跟es版本对应的就行。下载好后解压zip包
在你下载的es安装路径下的plugins文件夹下创建一个ik的文件夹,然后将上面解压出来的分词器内容复制到创建的ik文件夹下面。下面图ik分词器官方安装说明
ik分词器的安装就完成了,而后回答es根目录下的bin目录里,双击启动es
当es正常启动,且启动过程出现下面情况时,说明ik分词器已经正常安装好可以使用了
这里用的elasticsearch 6.8 版本 导入
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<!--springboot帮我们自动集成了es,所以只需要引入下面这一个依赖即可-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
server:
port: 9007
spring:
data:
elasticsearch:
cluster-name: my-application
cluster-nodes: 127.0.0.1:9300
@Document(indexName = "shop") @Data public class Goods { /** * 商品id */ @Field(type = FieldType.Integer)//type表示存到es当中的数据类型 private Integer id; /** * 商品名字 */ @Field(type = FieldType.Text,analyzer = "ik-max-word") private String productName; /** * 商品描述 */ @Field(type = FieldType.Text,analyzer = "ik-max-word") private String productDescription; /** * 商品价格 */ @Field(type = FieldType.Double) private Double productPrice; /** * 商品分类id */ @Field(type = FieldType.Integer) private Integer categoryId; /** * 商品图片 */ @Field(type = FieldType.Text) private String productImage; /** * 商品创建时间 */ @Field(type = FieldType.Date,format = DateFormat.basic_date_time) private Date productCreateTime; /** * 商品修改时间 */ @Field(type = FieldType.Date,format = DateFormat.basic_date_time) private Date productUpdateTime; /** * 商品状态(0:在销售,1:售空,2:下架) */ @Field(type = FieldType.Date,format = DateFormat.basic_date_time) private String productStatus; }
由于spring官方对es的高度封装,我们已经可以做到像操作数据库一样操作es了
package org.springframework.data.elasticsearch.repository; import org.elasticsearch.index.query.QueryBuilder; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.lang.Nullable; @NoRepositoryBean public interface ElasticsearchRepository<T, ID> extends PagingAndSortingRepository<T, ID> { /** @deprecated */ @Deprecated default <S extends T> S index(S entity) { return this.save(entity); } /** @deprecated */ @Deprecated <S extends T> S indexWithoutRefresh(S entity); /** @deprecated */ @Deprecated Iterable<T> search(QueryBuilder query); /** @deprecated */ @Deprecated Page<T> search(QueryBuilder query, Pageable pageable); /** @deprecated */ Page<T> search(Query searchQuery); Page<T> searchSimilar(T entity, @Nullable String[] fields, Pageable pageable); /** @deprecated */ @Deprecated void refresh(); }
以上面的Goods对象举例,创建接口EsGoodsRepository,继承Spring封装的ElasticsearchRepository,ElasticsearchRepository提供了一些简单的操作es方法
创建EsGoodsRepository接口:
package com.buba.service;
import com.buba.pojo.Goods;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface EsGoodsRepository extends ElasticsearchRepository<Goods,Integer> {
}
保存或者更新时,先存db后操作es(增删改查+批量删除)。.
@RequestMapping("/goods") @RestController public class GoodsControoler{ @Autowired private GoodService goodService; @Autowired private EsGoodsRepository esGoodsRepository; @Autowired private EsGoodsService esGoodsService; @PostMapping("/add") @ApiOperation(value = "添加商品") public Result<Goods> save(@RequestBody Goods goods) { goods.setProductCreateTime(new Date()); int i = goodService.insert(goods); if (i==1){ // 调用EsGoodsRepository save 方法 Goods save=esGoodsRepository.save(goods); return new Result(true, StatusCode.OK,"添加成功"); }else { return new Result(true, StatusCode.ERROR,"添加失败"); } } // 引用pagehelper写分页查询 @GetMapping("/list") @ApiOperation(value = "查询商品列表") public Result list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) { PageInfo<Goods> page = goodService.findAllUserByPageS(pageNum,pageSize); return new Result(true, StatusCode.OK, "查询成功", page); } @GetMapping("/searchGoods") @ApiOperation(value = "查询检索功能") public Result searchProduct(@RequestParam("productName") String productName,@RequestParam(value = "pageNum", defaultValue = "0") int pageNum, @RequestParam(value = "pageSize", defaultValue = "1") int pageSize){ QueryBuilder queryBuilder = QueryBuilders.matchQuery("productName", productName); PageRequest pageRequest = PageRequest.of(pageNum, pageSize); Page<Goods> search = esGoodsRepository.search(queryBuilder, pageRequest); if (search != null){ return new Result(true,StatusCode.OK,"商品展示成功",search); } return new Result(false,StatusCode.ERROR,"查询失败"); } //根据id 删除商品 @DeleteMapping("/delete") @ApiOperation(value = "删除商品") public Result delete(@RequestParam( "list") List<Integer> ids) { int i = goodService.deleteByPrimaryKey(ids); if (i >= 1) { esGoodsService.deleteByIds(ids); return new Result(true, StatusCode.OK, "删除成功"); } else { return new Result(true, StatusCode.ERROR, "删除失败"); } } //根据id修改商品 @PutMapping("/update") @ApiOperation(value = "修改商品") public Result update(@RequestBody Goods goods) { int i = goodService.updateByPrimaryKeySelective(goods); if (i == 1) { esGoodsRepository.save(goods); return new Result(true, StatusCode.OK, "修改成功"); } return new Result(true, StatusCode.ERROR, "修改失败"); }
这里只测试了添加 其余自己测
提示:这里对文章遇到报错总结:
原因是我们application.yaml配置文件出现了问题:
配置文件正确写法:
spring:
data:
elasticsearch:
cluster-name: my-application
cluster-nodes: 127.0.0.1:9300
可以看到这其中有两个配置:
cluster-name: my-application
cluster-nodes: 127.0.0.1:9300
① cluster-name
SpringDataElasticsearch底层使用的不是Elasticsearch提供的RestHighLevelClient,而是TransportClient,并不采用Http协议通信,而是访问elasticsearch对外开放的tcp端口
cluster-name的名字,在elasticsearch安装的config目录下的elasticsearch.yml文件中可以查看到,如果注释,则需要放开注释
②cluster-nodes
SpringDataElasticsearch底层使用的不是Elasticsearch提供的RestHighLevelClient,而是TransportClient,并不采用Http协议通信,而是访问elasticsearch对外开放的tcp端口
默认配置的9300才是对外开放的tcp端口,当然我们也可以通过配置去改变这个端口号。
Error creating bean with name ‘esGoodsRepository’: Invocation of init
method failed; nested exception is
org.springframework.data.mapping.PropertyReferenceException: No
property ids found for type Goods! Did you mean ‘id’?
创建一个service 类
package com.buba.service;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface EsGoodsService {
void deleteByIds(List<Integer> ids);
}
在这里插入代码片
创建一个实现类(实现批量删除方法)
package com.buba.service; import com.buba.pojo.Goods; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; @Service public class EsGoodsRepositoryImpl implements EsGoodsService { @Autowired private EsGoodsRepository esGoodsRepository; @Override public void deleteByIds(List<Integer> ids) { if (!CollectionUtils.isEmpty(ids)) { List<Goods> esProductList = new ArrayList<>(); for (Integer id : ids) { Goods goods = new Goods(); goods.setId(id); esProductList.add(goods); } esGoodsRepository.deleteAll(esProductList); } } }
controller 调用 service 方法来实现批量删除
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。