新建SpringBoot项目啥的我就不说了,都是基础,不会的自己就要学习一下了
一、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
二、配置application.yml
spring:
profiles:
active: dev
elasticsearch:
rest:
uris: localhost:9200
三、新建EsEntity实体类
@Document(indexName = “goods”):创建索引
@Field(type = FieldType.Text, analyzer = “ik_max_word”):
package com.cqw.es.domain;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.math.BigDecimal;
import java.util.Date;
/**
* @CreateTime: 2021-07-20 14:33
* @Description: Es实体
*/
@Data
@NoArgsConstructor
@Document(indexName = "goods")
public class EsEntity {
@Id
private Long id;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String goodsName;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private BigDecimal price;
@Field(type = FieldType.Date, analyzer = "ik_max_word", format = DateFormat.basic_date_time)
private Date createTime;
}
四、新建Mapper文件
继承ElasticsearchRepository类
package com.cqw.es.mapper;
import com.cqw.es.domain.EsEntity;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
*
* @CreateTime: 2021-07-20 14:54
* @Description:
*/
@Mapper
public interface EsMapper extends ElasticsearchRepository<EsEntity, Long> {
}
五、简单使用:全量导入
package com.cqw.es.service;
import com.cqw.es.domain.EsEntity;
import com.cqw.es.mapper.EsMapper;
import com.cqw.order.domain.Spu;
import com.cqw.order.mapper.SpuMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Author: caoqingwen
* @CreateTime: 2021-07-20 15:12
* @Description: 导入es
*/
@Service
@Slf4j
public class EsImportService {
@Resource
private EsMapper esMapper;
@Resource
private SpuMapper spuMapper;
@PostConstruct
public void init() {
importAll();
}
/**
* 全量导入
*/
public void importAll() {
log.info("全量导入开始=======================================");
List<Spu> spuList = spuMapper.selectBySelective(null);
if (CollectionUtils.isEmpty(spuList)) {
log.info("无数据需要导入");
}
List<EsEntity> collect = spuList.stream().map(spu -> {
EsEntity esEntity = new EsEntity();
esEntity.setId(spu.getId());
esEntity.setGoodsName(spu.getSpuName());
esEntity.setPrice(new BigDecimal(spu.getShopId()));
return esEntity;
}).collect(Collectors.toList());
esMapper.saveAll(collect);
log.info("全量导入结束=======================================");
}
}