springboot整合es
1.引入依赖(springboot2.3.x版本可以兼容elasticsearch7.x版本。)
<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>
2.修改配置文件
spring:
elasticsearch:
rest:
uris: http://localhost:9200
3.编写实体类document
@Data
@Document(indexName = "goods") //indexName 为索引库名称
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;
}
4.编写dao数据访问
@Repository
public interface GoodsDao extends ElasticsearchRepository<Goods, String> {
}
解释:ElasticsearchRepository<Goods, String>中的第一个泛型参数为索引库对应的实体类,第二个泛型为索引库关键字的类型
5.测试
@Autowired
private GoodsDao goodsDao;
/**
* 添加文档
* */
@Test
public void saveTest(){
Goods goods = new Goods();
goods.setId("1");
goods.setGoodsName("华为手机");
goods.setStore(100);
goods.setPrice(5000);
goodsDao.save(goods);
System.out.println("添加成功...");
}
/**
* 根据ID查询文档
* */
@Test
public void findById(){
Goods goods = goodsDao.findById("1").get();
System.out.println(goods);
}