springboot整合elasticsearch

本地环境(windows)安装elasticsearch及kibana。

添加elasticsearch依赖


<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-data-elasticsearch
<artifactId>
</dependency>

修改application.yml文件,在spring节点下添加Elasticsearch相关配置。
data:
elasticsearch:
repositories:
enabled:true
cluster-nodes:127.0.0.1:9300 # es的连接地址及端口号
cluster-name:elasticsearch # es集群的名称

添加domain文档对象
不需要中文分词的字段设置成@Field(type = FieldType.Keyword)类型,需要中文分词的设置成@Field(analyzer = "ikmaxword",type = FieldType.Text)类型。

/**

  • 搜索中的商品信息
  • Created by macro on 2018/6/19.
    */

@Document(indexName ="pms", type ="product",shards =1,replicas =0)
public class EsProduct implements Serializable{
private static final long serialVersionUID =-1L;
@Id
private Long id;
@Field(type =FieldType.Keyword)
private String productSn;
private Long brandId;
@Field(type =FieldType.Keyword)
private String brandName;
private Long productCategoryId;
@Field(type =FieldType.Keyword)
private String productCategoryName;
private String pic;
@Field(analyzer ="ik_max_word",type =FieldType.Text)
private String name;
@Field(analyzer ="ik_max_word",type =FieldType.Text)
private String subTitle;
@Field(analyzer ="ik_max_word",type =FieldType.Text)
private String keywords;
private BigDecimal price;
private Integer sale;
private Integer newStatus;
private Integer recommandStatus;
private Integer stock;
private Integer promotionType;
private Integer sort;
@Field(type =FieldType.Nested)
private List<EsProductAttributeValue> attrValueList;
//省略了所有getter和setter方法
}

添加EsProductRepository接口用于操作Elasticsearch
继承ElasticsearchRepository接口,这样就拥有了一些基本的Elasticsearch数据操作方法,同时定义了一个衍生查询方法。
/**

  • 商品ES操作类
  • Created by macro on 2018/6/19.
    /
    public interface EsProductRepository extends ElasticsearchRepository<EsProduct,Long>{
    /
    *
    • 搜索查询
    • @param name 商品名称
    • @param subTitle 商品标题
    • @param keywords 商品关键字
    • @param page 分页信息
    • @return
      */
      Page<EsProduct> findByNameOrSubTitleOrKeywords( String name, String subTitle, String keywords,Pageable page);
      }

添加xxxService接口
/**

  • 商品搜索管理Service
  • Created by macro on 2018/6/19.
    /
    public interface EsProductService{
    /
    *
  • 从数据库中导入所有商品到ES
    /
    int importAll();
    /
    *
  • 根据id删除商品
    /
    void delete( Long id);
    /
    *
  • 根据id创建商品
    /
    EsProduct create( Long id);
    /
    *
  • 批量删除商品
    /
    void delete(List<Long> ids);
    /
    *
  • 根据关键字搜索名称或者副标题
    */
    Page<EsProduct> search(String keyword,Integer pageNum,Integer pageSize);
    }

添加Service接口的实现类xxxServiceImpl
/**

  • 商品搜索管理Service实现类
  • Created by macro on 2018/6/19.
    */
    @Service
    public class EsProductServiceImpl implements EsProductService{
    private static final Logger LOGGER = LoggerFactory.getLogger(EsProductServiceImpl.class);
    @Autowired
    private EsProductDao productDao;
    @Autowired
    private EsProductRepository productRepository;

@Override
public int importAll(){
List<EsProduct> esProductList = productDao. getAllEsProductList(null);
Iterable<EsProduct> esProductIterable = productRepository.saveAll(esProductList);
Iterator<EsProduct> iterator = esProductIterable.iterator();
int result =0;
while(iterator.hasNext()){
result++;
iterator.next();
}
return result;
}

@Override
public void delete(Long id){
productRepository.deleteById(id);
}

@Override
public EsProduct create(Long id){
EsProduct result =null;
List<EsProduct> esProductList = productDao.getAllEsProductList(id);
if(esProductList.size()>0){
EsProduct esProduct = esProductList.get(0);
result = productRepository.save(esProduct);
}
return result;
}

@Override
public void delete(List<Long> ids){
if(!CollectionUtils.isEmpty(ids)){
List<EsProduct> esProductList = new ArrayList<>();
for(Long id : ids){
EsProduct esProduct =new EsProduct();
esProduct.setId(id);
esProductList.add(esProduct);
}
productRepository.deleteAll(
esProductList
);
}
}

@Override
public Page<EsProduct> search(String keyword,Integer pageNum,Integer pageSize){
Pageable pageable =PageRequest.of(pageNum, pageSize);
return productRepository.findByNameOrSubTitleOrKeywords(keyword, keyword, keyword, pageable);
}
}

添加Controller定义接口
/**

  • 搜索商品管理Controller
  • Created by macro on 2018/6/19.
    */
    @Controller @Api(tags ="EsProductController", description ="搜索商品管理")
    @RequestMapping("/esProduct")
    public class EsProductController{

@Autowired
private EsProductService esProductService;

@ApiOperation(value = "导入所有数据库中商品到ES")
@RequestMapping(value ="/importAll", method =RequestMethod.POST)
@ResponseBody
public CommonResult<Integer> importAllList(){
int count = esProductService.importAll();
return CommonResult.success(count);
}

@ApiOperation(value ="根据id删除商品")
@RequestMapping(value ="/delete/{id}", method =RequestMethod.GET)
@ResponseBody
public CommonResult< Object> delete(@PathVariable Long id){
esProductService.delete(id);
return CommonResult.success(null);
}

@ApiOperation(value = "根据id批量删除商品")
@RequestMapping(value ="/delete/batch", method =RequestMethod.POST)
@ResponseBody
public CommonResult<Object> delete(@RequestParam("ids") List<Long> ids){
esProductService.delete(ids);
return CommonResult.success(null);
}

@ApiOperation(value ="根据id创建商品")
@RequestMapping(value ="/create/{id}", method =RequestMethod.POST)
@ResponseBody
public CommonResult<EsProduct> create(@PathVariable Long id){
EsProduct esProduct = esProductService.create(id);
if(esProduct !=null){
return CommonResult.success(esProduct);
}else{
return CommonResult.failed();
}
}

@ApiOperation(value ="简单搜索")
@RequestMapping(value ="/search/simple", method =RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required =false) String keyword,@RequestParam(required =false, defaultValue ="0") Integer pageNum,@RequestParam(required =false, defaultValue="5") Integer pageSize){
Page<EsProduct> esProductPage = esProductService.search(keyword, pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(esProductPage));
}
}

常用注解
@Document
//标示映射到Elasticsearch文档上的领域对象
public @interface Document{
//索引库名次,mysql中数据库的概念
String indexName();

//文档类型,mysql中表的概念
String type() default "";

//默认分片数
short shards() default 5;

//默认副本数量
short replicas() default 1;
}

@Id
//表示是文档的id,文档可以认为是mysql中表行的概念
public @interface Id{}

@Field
public @interface Field{
//文档中字段的类型
FieldType type() default FieldType.Auto;

//是否建立倒排索引
boolean index() default true;

//是否进行存储
boolean store() default false;

//分词器名次
String analyzer() default "";
}

//为文档自动指定元数据类型
public enum FieldType{
Text,//会进行分词并建了索引的字符类型
Integer,
Long,
Date,
Float,
Double,
Boolean,
Object,
Auto,//自动判断字段类型
Nested,//嵌套对象类型
Ip,
Attachment,
Keyword //不会进行分词建立索引的类型
}

参考项目:https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-06

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容