全文检索工具:第一章:Spring-data-elasticSearch搜索

快速上手:导入删除查询
引入依赖:

           

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  4. </dependency>

控制层:

    @Autowired
        private EsProductService esProductService;
     
        @ApiOperation(value = "简单搜索:根据关键字,品牌名称或者产品名称,产品编号,副标题搜索(字符串:Text类型最大拆分)")
        @RequestMapping(value = "/search/keyword", method = RequestMethod.GET)
        @ResponseBody
        public CommonResult<CommonPage<EsProduct>> searchKeyword(@RequestParam(required = false) String keyword,
                                                                @RequestParam(required = false, defaultValue = "0") Integer pageNum,
                                                                @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
            Page<EsProduct> esProductPage = esProductService.searchKeyword(keyword, pageNum, pageSize);
            return CommonResult.success(CommonPage.restPage(esProductPage));
        }
     
        @ApiOperation(value = "删除索引库")
        @ApiImplicitParam(name = "indexName", value = "索引库名称",
                defaultValue = "product", paramType = "query", dataType = "String")
        @RequestMapping(value = "/deleteAll", method = RequestMethod.GET)
        @ResponseBody
        public CommonResult<Object> deleteAll(String indexName) {
            int i = esProductService.deleteAll(indexName);
            return CommonResult.success(i);
        }
     
        @ApiOperation(value = "导入所有产品信息数据库中商品到ES")
        @RequestMapping(value = "/importAll", method = RequestMethod.GET)
        @ResponseBody
        public CommonResult<Integer> importAllList() {
            int count = esProductService.importAll();
            return CommonResult.success(count);
        }

service接口:

    public interface EsProductService {
        /**
         * 从数据库中导入所有商品到ES
         */
        int importAll();
        /**
         * 根据关键字,品牌名称或者产品名称搜索(字符串:Text类型最大拆分)
         * @param keyword
         * @param pageNum
         * @param pageSize
         * @return
         */
        Page<EsProduct> searchKeyword(String keyword, Integer pageNum, Integer pageSize);
     
     
        /**
         * 删除索引库
         * @return
         */
        int deleteAll(String indexName);
    }

业务实现类:

    @Service
    public class EsProductServiceImpl implements EsProductService {
     
        private static final Logger LOGGER = LoggerFactory.getLogger(EsProductServiceImpl.class);
        @Autowired
        private EsProductDao productDao;
        @Autowired
        private EsProductRepository productRepository;
        @Autowired
        private ElasticsearchTemplate elasticsearchTemplate;
     
        @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;
        }
     
        /**
         * 根据关键字,品牌名称或者产品名称,产品编号搜索(字符串:Text类型最大拆分)
         * @param keyword
         * @param pageNum
         * @param pageSize
         * @return
         */
        @Override
        public Page<EsProduct> searchKeyword(String keyword, Integer pageNum, Integer pageSize) {
            Pageable pageable = PageRequest.of(pageNum, pageSize);
            return productRepository.findByKeywordsOrProductNameOrBrandNameOrProductSnOrSubTitle(keyword,keyword,keyword,keyword,keyword,pageable);
        }
     
        /**
         * 删除索引库
         * @return
         */
        @Override
        public int deleteAll(String indexName) {
            boolean product = elasticsearchTemplate.deleteIndex(indexName);
            if(product){
                return 1;
            }
            return 0;
        }
    }

EsProductDao接口

    public interface EsProductDao {
        List<EsProduct> getAllEsProductList(@Param("id") Long id);
    }

EsProductDao.xml

   

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.macro.mall.search.dao.EsProductDao">
  4. <resultMap id="esProductListMap" type="com.macro.mall.search.domain.EsProduct">
  5. <id column="productId" jdbcType="BIGINT" property="id" />
  6. <result column="productSn" jdbcType="VARCHAR" property="productSn"/>
  7. <result column="brandId" jdbcType="BIGINT" property="brandId"/>
  8. <result column="brandName" jdbcType="VARCHAR" property="brandName"/>
  9. <result column="productCategoryId" jdbcType="BIGINT" property="productCategoryId"/>
  10. <result column="productName" jdbcType="VARCHAR" property="productName"/>
  11. <result column="sale" jdbcType="BIGINT" property="sale"/>
  12. <result column="subTitle" jdbcType="VARCHAR" property="subTitle"/>
  13. <result column="price" jdbcType="DECIMAL" property="price"/>
  14. <result column="keywords" jdbcType="VARCHAR" property="keywords"/>
  15. <association property="productCategorie" columnPrefix="pc"
  16. javaType="com.macro.mall.search.domain.EsProductCategory">
  17. <id column="productCategoryId" property="id" jdbcType="BIGINT"/>
  18. <result column="productCategoryName" property="productCategoryName" jdbcType="VARCHAR"/>
  19. </association>
  20. <collection property="attributeList" ofType="com.macro.mall.search.domain.EsProductAttribute"
    javaType="java.util.ArrayList">
  21. <id column="paProductAttributeId" property="paProductAttributeId" jdbcType="BIGINT"/>
  22. <result column="paProductAttributeName" property="paProductAttributeName" jdbcType="VARCHAR"/>
  23. <collection property="attributeValues" ofType="com.macro.mall.search.domain.EsProductAttributeValue"
  24. javaType="java.util.ArrayList">
  25. <id column="pavProductAttributeValueId" property="pavProductAttributeValueId" jdbcType="BIGINT"/>
  26. <result column="pavProductAttributeValue" property="pavProductAttributeValue" jdbcType="VARCHAR"/>
  27. </collection>
  28. </collection>
  29. </resultMap>
  30. <select id="getAllEsProductList" resultMap="esProductListMap">
  31. SELECT
  32. p.id productId,
  33. p.product_sn productSn,
  34. p.brand_id brandId,
  35. p.brand_name brandName,
  36. p.product_category_id productCategoryId,
  37. p.name productName,
  38. p.sale sale,
  39. p.sub_title subTitle,
  40. p.price price,
  41. p.keywords keywords,
  42. pav.id pavProductAttributeValueId,
  43. pav.`value` pavProductAttributeValue,
  44. pa.id paProductAttributeId,
  45. pa.`name` paProductAttributeName,
  46. pc.id pcProductCategoryId,
  47. pc.`name` pcProductCategoryName
  48. FROM pms_product p
  49. LEFT JOIN pms_product_attribute_value pav ON p.id = pav.product_id
  50. LEFT JOIN pms_product_attribute pa ON pav.product_attribute_id= pa.id
  51. LEFT JOIN pms_product_category pc ON p.`product_category_id` = pc.`id`
  52. WHERE delete_status = 0 AND publish_status = 1
  53. <if test="id!=null">
  54. and p.id=#{id}
  55. </if>
  56. </select>
  57. </mapper>

EsProductRepository接口

    public interface EsProductRepository extends ElasticsearchRepository<EsProduct, Long> {
     
     
        /**
         * 根据关键字,产品名称,品牌名称,产品编号搜索
         * @param keywords
         * @param productName
         * @param brandName
         * @param page
         * @return
         */
        Page<EsProduct> findByKeywordsOrProductNameOrBrandNameOrProductSnOrSubTitle(String keywords,String productName,String brandName,String productSn,String subTitle,Pageable page);
    }

EsProduct实体类:

    @Document(indexName = "product", type = "productInfo",shards = 2,replicas = 1,refreshInterval = "-1")
    public class EsProduct implements Serializable {
     
        private static final long serialVersionUID = 2372551074091780419L;
        @Id
        private Long id;
        @Field(analyzer = "ik_max_word",type = FieldType.Text)
        private String productSn;
        private Long brandId;
        @Field(analyzer = "ik_max_word",type = FieldType.Text)
        private String brandName;
        private Long productCategoryId;
        @Field(analyzer = "ik_max_word",type = FieldType.Text)
        private String productName;
        private Long sale;
        @Field(analyzer = "ik_max_word",type = FieldType.Text)
        private String subTitle;
        private BigDecimal price;
        @Field(analyzer = "ik_max_word",type = FieldType.Text)
        private String keywords;
     
        private List<EsProductAttribute> attributeList;
     
        private EsProductCategory productCategorie;
        //提供一下get和set方法,我就不写了
    }

EsProductAttribute实体类:

    public class EsProductAttribute implements Serializable {
     
        private static final long serialVersionUID = 4965902919813623705L;
     
        private Long paProductAttributeId;
        @Field(analyzer = "ik_max_word",type = FieldType.Text)
        private String paProductAttributeName;//属性名称
     
     
        private List<EsProductAttributeValue> attributeValues;
        //提供get和set方法
     
    }

EsProductAttributeValue实体类:

    public class EsProductAttributeValue implements Serializable {
        private static final long serialVersionUID = 6713756365860464751L;
     
        private Long pavProductAttributeValueId;
        @Field(analyzer = "ik_max_word",type = FieldType.Text)
        private String pavProductAttributeValue;
        //提供get 和set方法
    }

测试一下:

删除测试

 

导入数据到es测试

 

无条件全部搜索测试

 

有条件搜索测试

 

如果启动报错,可以将原来的

@Document(indexName = "search", type = "article",shards = 1,replicas = 0)

改一下索引库的名称

@Document(indexName = "search11", type = "article",shards = 1,replicas = 0)

再次启动删除索引库再重新导入,之后就不会报错了。