SpringBoot整合elasticsearch
springboot2.3.x版本可以兼容elasticsearch7.x版本。
1.新建maven项目
2.创建好相关的包
包含:基本包,启动类,yml文件,单元测试包和类
pom.xml:
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.3.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</dependencies>
yml配置
application.yml
spring:
elasticsearch:
rest:
uris: http://localhost:9200
document映射
@Data
@Document(indexName = "goods")
public class Goods implements Serializable {
@Field(type = FieldType.Keyword)
private String id;
@Field(type = FieldType.Text)
private String goodsName;
@Field(type = FieldType.Integer)
private Integer store;
@Field(type = FieldType.Double)
private double price;
}
dao数据访问
// Goods:为索引库名(表名),String:主键id的类型
@Repository
public interface GoodsDao extends ElasticsearchRepository<Goods, String> {
}
springboot启动类
@SpringBootApplication
public class SpringDataEsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataEsApplication.class,args);
System.out.println("****** 项目启动成功!******");
}
}
3.接口测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes= SpringDataEsApplication.class)
public class GoodsRepositoryTest {
@Resource
private GoodsDao goodsDao;
/**
* 添加文档
* */
@Test
public void saveTest(){
Goods goods = new Goods();
goods.setId("2");
goods.setGoodsName("三星手机");
goods.setStore(100);
goods.setPrice(6600);
goodsDao.save(goods);
System.out.println("添加成功...");
}
/**
* 更新文档
* */
@Test
public void updateTest(){
Goods goods = new Goods();
goods.setId("3");
goods.setGoodsName("不存在华为手机");
goods.setStore(100);
goods.setPrice(5000);
goodsDao.save(goods);
System.out.println("修改成功...");
}
/**
* 查询所有文档
* */
@Test
public void findTest(){
Iterable<Goods> all = goodsDao.findAll();
for (Goods goods : all) {
System.out.println(goods);
}
System.out.println("查询所有文档成功...");
}
/**
* 查询文档根据id
* */
@Test
public void findByIdTest(){
Optional<Goods> byId = goodsDao.findById("1");
System.out.println(byId);
System.out.println("查询所有文档成功...");
}
}