springboot整合es

springboot整合es

1.引入依赖(springboot2.3.x版本可以兼容elasticsearch7.x版本。)

      
        spring-boot-starter-parent
        org.springframework.boot
        2.3.6.RELEASE
      
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
    

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 {
}

解释:ElasticsearchRepository中的第一个泛型参数为索引库对应的实体类,第二个泛型为索引库关键字的类型

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);
    }

springboot整合es_第1张图片

你可能感兴趣的:(java实战学习,spring,boot,elasticsearch,后端)