SpringBoot實戰電商項目mall(20k+star)地址: https://github.com/macrozheng/mall
本文主要講解mall整合Elasticsearch的過程,以實現商品信息在Elasticsearch中的導入、查詢、修改、刪除爲例。java
Elasticsearch 是一個分佈式、可擴展、實時的搜索與數據分析引擎。 它能從項目一開始就賦予你的數據以搜索、分析和探索的能力,可用於實現全文搜索和實時數據統計。
Spring Data Elasticsearch是Spring提供的一種以Spring Data風格來操做數據存儲的方式,它能夠避免編寫大量的樣板代碼。
//標示映射到Elasticsearch文檔上的領域對象 public @interface Document { //索引庫名次,mysql中數據庫的概念 String indexName(); //文檔類型,mysql中表的概念 String type() default ""; //默認分片數 short shards() default 5; //默認副本數量 short replicas() default 1; }
//表示是文檔的id,文檔能夠認爲是mysql中表行的概念 public @interface Id { }
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//不會進行分詞創建索引的類型 }
在接口中直接指定查詢方法名稱即可查詢,無需進行實現,如商品表中有商品名稱、標題和關鍵字,直接定義如下查詢,就能夠對這三個字段進行全文搜索。
/** * 搜索查詢 * * @param name 商品名稱 * @param subTitle 商品標題 * @param keywords 商品關鍵字 * @param page 分頁信息 * @return */ Page<EsProduct> findByNameOrSubTitleOrKeywords(String name, String subTitle, String keywords, Pageable page);
在idea中直接會提示對應字段
@Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}") Page<EsProduct> findByName(String name,Pageable pageable);
pms_product
:商品信息表pms_product_attribute
:商品屬性參數表pms_product_attribute_value
:存儲產品參數值的表<!--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集羣的名稱
不須要中文分詞的字段設置成@Field(type = FieldType.Keyword)類型,須要中文分詞的設置成@Field(analyzer = "ik_max_word",type = FieldType.Text)類型。
package com.macro.mall.tiny.nosql.elasticsearch.document; 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; /** * 搜索中的商品信息 * 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方法 }
繼承ElasticsearchRepository接口,這樣就擁有了一些基本的Elasticsearch數據操做方法,同時定義了一個衍生查詢方法。
package com.macro.mall.tiny.nosql.elasticsearch.repository; import com.macro.mall.tiny.nosql.elasticsearch.document.EsProduct; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * 商品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); }
package com.macro.mall.tiny.service; import com.macro.mall.tiny.nosql.elasticsearch.document.EsProduct; import org.springframework.data.domain.Page; import java.util.List; /** * 商品搜索管理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); }
package com.macro.mall.tiny.service.impl; import com.macro.mall.tiny.dao.EsProductDao; import com.macro.mall.tiny.nosql.elasticsearch.document.EsProduct; import com.macro.mall.tiny.nosql.elasticsearch.repository.EsProductRepository; import com.macro.mall.tiny.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 org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * 商品搜索管理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); } }
package com.macro.mall.tiny.controller; import com.macro.mall.tiny.common.api.CommonPage; import com.macro.mall.tiny.common.api.CommonResult; import com.macro.mall.tiny.nosql.elasticsearch.document.EsProduct; import com.macro.mall.tiny.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.*; import java.util.List; /** * 搜索商品管理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)); } }
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-06node
mall項目全套學習教程連載中,關注公衆號第一時間獲取。mysql