一、概述
Elasticsearch 是一个分布式、可扩展、实时的搜索与数据分析引擎。 它能从项目一开始就赋予你的数据以搜索、分析和探索的能力,可用于实现全文搜索和实时数据统计。
二、安装Elasticsearch
- 下载Elasticsearch6.2.2的zip包,并解压到指定目录,下载地址:https://www.elastic.co/cn/downloads/past-releases/elasticsearch-6-2-2
- 安装中文分词插件,在
elasticsearch-6.2.2\bin
目录下执行以下命令:elasticsearch-plugin install [https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.2.2/elasticsearch-analysis-ik-6.2.2.zip](https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.2.2/elasticsearch-analysis-ik-6.2.2.zip)
- 运行bin目录下的
elasticsearch.bat
启动Elasticsearch - 下载Kibana,作为访问Elasticsearch的客户端,请下载6.2.2版本的zip包,并解压到指定目录,下载地址:https://artifacts.elastic.co/downloads/kibana/kibana-6.2.2-windows-x86_64.zip
- 运行bin目录下的
kibana.bat
,启动Kibana的用户界面 - 访问http://localhost:5601 即可打开Kibana的用户界面
三、Spring Data Elasticsearch
Spring Data Elasticsearch是Spring提供的一种以Spring Data风格来操作数据存储的方式,它可以避免编写大量的样板代码。
依赖
<!--Elasticsearch相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch<artifactId>
</dependency>
配置
spring:
data:
elasticsearch:
repositories:
enabled: true
cluster-nodes: 127.0.0.1:9300 # es的连接地址及端口号
cluster-name: elasticsearch # es集群的名称
四、常用注解
@Document
标示映射到Elasticsearch文档上的领域对象indexName
索引库名次,mysql中数据库的概念,String类型type
文档类型,mysql中表的概念,String类型,默认””shards
默认分片数,short类型,默认5replicas
默认副本数量,short类型,默认1
@Id
表示是文档的id,文档可以认为是mysql中表行的概念@Field
为文档自动指定元数据类型type
文档中字段的类型,FieldType类型index
是否建立倒排索引,boolean类型,默认truestore
是否进行存储,boolean类型,默认trueanalyzer
分词器名次,String类型,默认””
FieldType
包括:
public enum FieldType {
Text, // 会进行分词并建了索引的字符类型
Integer,
Long,
Date,
Float,
Double,
Boolean,
Object,
Auto, // 自动判断字段类型
Nested, // 嵌套对象类型
Ip,
Attachment,
Keyword // 不会进行分词建立索引的类型
}
五、创建Document
以下示例,假设我们要在商品表中搜索指定的商品,可以通过商品名字、商品描述、商品关键字等作为搜索条件,只要满足就搜索出结果,如果使用普通的SQL我们务必会书写大量的like语句,并且搜索效率极慢。为了达到高效率搜索,我们使用Elasticsearch作为搜索引擎,进行快速搜索。
首先需要创建一个Document,就跟MySQL中的数据表类似:
package com.example.test.nosql.elasticsearch.document;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@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;
}
六、创建Repository
继承ElasticsearchRepository
接口可以获得常用的数据操作方法,比如 findByXXX
。
在接口中直接指定查询方法名称便可查询,无需进行实现,如商品表中有商品名称、标题和关键字,直接定义以下查询,就可以对这三个字段进行全文搜索:findByNameOrSubTitleOrKeywords
。
package com.example.test.nosql.elasticsearch.repository;
import com.example.test.nosql.elasticsearch.document.EsProduct;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
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);
}
七、创建Dao
package com.example.test.dao;
import com.example.test.nosql.elasticsearch.document.EsProduct;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 搜索系统中的商品管理自定义Dao
*/
public interface EsProductDao {
List<EsProduct> getAllEsProductList(@Param("id") Long id);
}
对应的Mapper:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.test.dao.EsProductDao">
<resultMap id="esProductListMap" type="com.example.test.nosql.elasticsearch.document.EsProduct" autoMapping="true">
<id column="id" jdbcType="BIGINT" property="id" />
</resultMap>
<select id="getAllEsProductList" resultMap="esProductListMap">
select
id id,
product_sn productSn,
brand_id brandId,
brand_name brandName,
product_category_id productCategoryId,
product_category_name productCategoryName,
pic pic,
name name,
sub_title subTitle,
price price,
sale sale,
new_status newStatus,
recommand_status recommandStatus,
stock stock,
promotion_type promotionType,
keywords keywords,
sort sort,
from pms_product
where delete_status = 0 and publish_status = 1
<if test="id!=null">
and id=#{id}
</if>
</select>
</mapper>
八、创建Service
package com.example.test.service;
import com.example.test.nosql.elasticsearch.document.EsProduct;
import org.springframework.data.domain.Page;
/**
* 商品搜索管理Service
*/
public interface EsProductService {
/**
* 从数据库中导入所有商品到ES
*/
int importAll();
/**
* 根据关键字搜索名称或者副标题
*/
Page<EsProduct> search(String keyword, Integer pageNum, Integer pageSize);
}
服务的实现类:
package com.example.test.service.impl;
import com.example.test.dao.EsProductDao;
import com.example.test.nosql.elasticsearch.document.EsProduct;
import com.example.test.nosql.elasticsearch.repository.EsProductRepository;
import com.example.test.service.EsProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Iterator;
import java.util.List;
/**
* 商品搜索管理Service实现类
*/
@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 Page<EsProduct> search(String keyword, Integer pageNum, Integer pageSize) {
Pageable pageable = PageRequest.of(pageNum, pageSize);
return productRepository.findByNameOrSubTitleOrKeywords(keyword, keyword, keyword, pageable);
}
}
九、在控制器中使用
package com.example.test.controller;
import com.example.test.common.api.CommonResult;
import com.example.test.common.utils.CommonPage;
import com.example.test.nosql.elasticsearch.document.EsProduct;
import com.example.test.service.EsProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@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 = "简单搜索")
@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));
}
}
使用方式:
- 首先导入数据到Elasticsearch,访问接口
/esProduct/importAll
- 访问搜索接口,举例:
/esProduct/search/simple?keyword=小米&pageSize=2&page=1
十、错误处理
failed to map source
原因是在实体类中没有无参构造器,加上无参构造器就行了