springboot整合es

本文介绍了如何在SpringBoot2.3.x项目中集成Elasticsearch7.x,包括添加依赖、配置文件设置、创建实体类和使用ElasticsearchRepository进行数据操作,以及提供测试示例。
摘要由CSDN通过智能技术生成

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

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱敲代码的林先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值