springboot整合elasticsearch

本地環(huán)境(windows)安裝elasticsearch及kibana。

添加elasticsearch依賴


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

修改application.yml文件,在spring節(jié)點下添加Elasticsearch相關(guān)配置。
data:
elasticsearch:
repositories:
enabled:true
cluster-nodes:127.0.0.1:9300 # es的連接地址及端口號
cluster-name:elasticsearch # es集群的名稱

添加domain文檔對象
不需要中文分詞的字段設(shè)置成@Field(type = FieldType.Keyword)類型,需要中文分詞的設(shè)置成@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;
//省略了所有g(shù)etter和setter方法
}

添加EsProductRepository接口用于操作Elasticsearch
繼承ElasticsearchRepository接口,這樣就擁有了一些基本的Elasticsearch數(shù)據(jù)操作方法,同時定義了一個衍生查詢方法。
/**

  • 商品ES操作類
  • Created by macro on 2018/6/19.
    /
    public interface EsProductRepository extends ElasticsearchRepository<EsProduct,Long>{
    /
    *
    • 搜索查詢
    • @param name 商品名稱
    • @param subTitle 商品標(biāo)題
    • @param keywords 商品關(guān)鍵字
    • @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{
    /
    *
  • 從數(shù)據(jù)庫中導(dǎo)入所有商品到ES
    /
    int importAll();
    /
    *
  • 根據(jù)id刪除商品
    /
    void delete( Long id);
    /
    *
  • 根據(jù)id創(chuàng)建商品
    /
    EsProduct create( Long id);
    /
    *
  • 批量刪除商品
    /
    void delete(List<Long> ids);
    /
    *
  • 根據(jù)關(guān)鍵字搜索名稱或者副標(biāo)題
    */
    Page<EsProduct> search(String keyword,Integer pageNum,Integer pageSize);
    }

添加Service接口的實現(xiàn)類xxxServiceImpl
/**

  • 商品搜索管理Service實現(xiàn)類
  • 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 = "導(dǎo)入所有數(shù)據(jù)庫中商品到ES")
@RequestMapping(value ="/importAll", method =RequestMethod.POST)
@ResponseBody
public CommonResult<Integer> importAllList(){
int count = esProductService.importAll();
return CommonResult.success(count);
}

@ApiOperation(value ="根據(jù)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 = "根據(jù)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 ="根據(jù)id創(chuàng)建商品")
@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
//標(biāo)示映射到Elasticsearch文檔上的領(lǐng)域?qū)ο?br> public @interface Document{
//索引庫名次,mysql中數(shù)據(jù)庫的概念
String indexName();

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

//默認(rèn)分片數(shù)
short shards() default 5;

//默認(rèn)副本數(shù)量
short replicas() default 1;
}

@Id
//表示是文檔的id,文檔可以認(rèn)為是mysql中表行的概念
public @interface Id{}

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

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

//是否進(jìn)行存儲
boolean store() default false;

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

//為文檔自動指定元數(shù)據(jù)類型
public enum FieldType{
Text,//會進(jìn)行分詞并建了索引的字符類型
Integer,
Long,
Date,
Float,
Double,
Boolean,
Object,
Auto,//自動判斷字段類型
Nested,//嵌套對象類型
Ip,
Attachment,
Keyword //不會進(jìn)行分詞建立索引的類型
}

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容