Springboot结合Elasticsearch

文章目录


前言

        本文使用的es版本为7.4.2,仍然是使用es的transportClient,但是在es8开始就因为效率低下而废弃transportClient了,目前推荐使用restClient进行增删改查。本文只作学习过程记录,如需要学习最新的restClient请绕道!!!!!!!


以下是本篇文章正文内容

一、对于版本关系

二、使用步骤

1.pom文件(springboot版本2.7.0)

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
   </dependency>

2.yml配置

代码如下(示例):

spring:
    elasticsearch:
        rest:
            uri: ip地址:9200

3.编写实体类

/**
 * @Author: l
 * @Date: 2022/07/11/15:51
 *
 * Spring Data通过注解来声明字段的映射属性,有下面的三个注解:
 *
 * - `@Document` 作用在类,标记实体类为文档对象,一般有四个属性
 *   - indexName:对应索引库名称
 *   - type:对应在索引库中的类型 but在ElasticSearch7.x中取消了type的概念
 *   - shards:分片数量,默认5
 *   - replicas:副本数量,默认1

- `@Id` 作用在成员变量,标记一个字段作为id主键
- `@Field` 作用在成员变量,标记为文档的字段,并指定字段映射属性:
    - type:字段类型,取值是枚举:FieldType
    - index:是否索引,布尔类型,默认是true
    - store:是否存储,布尔类型,默认是false
    - analyzer:分词器名称:ik_max_word    ik分词器内容,看另外一个随笔:
 */

@Document(indexName = "product")
public class Book {
    @Id//注意此处的@Id必须为springframework包下面的id   import org.springframework.data.annotation.Id;
    String id;
    String name;
    String message;
    String type;

  getter/setter方法省略
}

4.实现ElasticsearchRepository接口


/**
 * @Author: 
 * @Date: 2022/07/11/16:37
 *
 * 继承es接口封装了很多内容
 */

public interface EsBookRepository extends ElasticsearchRepository<Book,Integer> {//,Integer指的是findbyid时的id类型
}

5.测试类使用API进行增删改查操作

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootChat01Application.class)//springboot启动类
public class ESTest {

    @Autowired
    private EsBookRepository esBookRepository;

    @Test
    public void insert() {
        Book book = new Book();
        for (int i = 0; i < 10; i++) {
            book.setId(new Random().nextInt() + "");
            book.setMessage("书信息");
            book.setName("书名");
            this.esBookRepository.save(book);
        }
    }

    @Test
    public void select() {
        System.out.println(this.esBookRepository.findById(1).get().getMessage());
    }


}

6.结果查询


总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值