SpringBoot——整合ElasticSearch实现对es文档的基本操作

本文详细介绍了如何在SpringBoot项目中集成并使用Elasticsearch,包括创建项目、添加依赖、定义实体类、实现DAO层、配置设置及进行各种查询操作的测试。示例代码展示了完整的流程,适合初学者参考。
摘要由CSDN通过智能技术生成

一、创建springboot项目

这里不做演示

二、导入es依赖坐标

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

三、创建实体类

package com.example.springboot_es.user;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * @Author: Ljx
 * @Date: 2021/12/3 13:14
 * @role:
 */
//indexName 指定索引名称
@Document(indexName = "lx-sd")
@Data
public class Article {
    @Id
    @Field(index = false,type = FieldType.Integer)
    private Integer id;
    /**
     * index:是否设置分词  默认为true
     * analyzer:储存时使用的分词器
     * searchAnalyze:搜索时使用的分词器
     * store:是否存储  默认为false
     * type:数据类型  默认值是FieldType.Auto
     *
     */
    @Field(analyzer = "ik_smart",searchAnalyzer = "ik_smart",store = true,type = FieldType.Text)
    private String title;
    @Field(analyzer = "ik_smart",searchAnalyzer = "ik_smart",store = true,type = FieldType.Text)
    private String context;
    @Field(store = true,type = FieldType.Integer)
    private Integer hits;
}

四、创建dao层

package com.example.springboot_es.dao;

import com.example.springboot_es.user.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: Ljx
 * @Date: 2021/12/3 13:29
 * @role:
 */

/**
 * 自定义接口需要继承ElasticsearchRepository<实体类型,主键类型>  基本的crud 分页
 */
@Component
public interface ArticleDao extends ElasticsearchRepository<Article,Integer> {

    /**
     * 根据标题查询
     * @param title
     * @return
     */
    List<Article> findByTitle(String title);

    /**
     * 根据标题或内容查询
     * @param title
     * @param context
     * @return
     */
    List<Article> findByTitleOrContext(String title,String context);

    /**
     * 根据标题或内容查询(含分页)
     * @param title
     * @param context
     * @param pageable
     * @return
     */
    List<Article> findByTitleOrContext(String title, String context, Pageable pageable);
}

五、添加配置类

spring:
  elasticsearch:
    rest:
      uris: localhost:9200
      read-timeout: 30s
      connection-timeout: 5s

六、测试

package com.example.springboot_es;

import com.example.springboot_es.dao.ArticleDao;
import com.example.springboot_es.user.Article;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import java.util.List;
import java.util.Optional;

@SpringBootTest
public class Estest {

    @Autowired
    private ElasticsearchRestTemplate template;

    @Autowired
    private ArticleDao articleDao;


    //通过springboot es向elasticsearch数据库储存一条数据
    @Test
    public void testSave() {
        //创建文档
        Article article = new Article();
        article.setId(1);
        article.setTitle("es搜索");
        article.setContext("成功了吗");
        //保存文档
        articleDao.save(article);
    }

    //修改
    @Test
    public void testUpdate() {
        //判断数据库中是否有你指定的id的文档,如果没有。就进行保存,如果有,就进行更新
        //创建文档
        Article article = new Article();
        article.setId(1);
        article.setTitle("es搜索1");
        article.setContext("成功了吗1");
        //保存文档
        articleDao.save(article);
    }

    //删除
    @Test
    public void testDelete() {
//        根据主键删除
        articleDao.deleteById(1);
    }


    //重新构建数据
    @Test
    public void makeData(){
        for (int i = 1; i <= 10; i++) {
            //创建文档
            Article article = new Article();
            article.setId(i);
            article.setTitle("es搜索"+i);
            article.setContext("成功了吗"+i);
            article.setHits(100+i);
            //保存数据
            articleDao.save(article);
        }
    }

    //查询所有
    @Test
    public void findAll(){
        Iterable<Article> all = articleDao.findAll();
        for (Article article : all) {
            System.out.println(article);
        }
    }

    //主键查询
    @Test
    public void testFindById(){
        Optional<Article> id = articleDao.findById(1);
        System.out.println(id.get());
    }

    //分页查询
    @Test
    public void testFindAllWithPage(){
        //设置分页条件
        //page代表页码,从0开始
        PageRequest pageRequest = PageRequest.of(1, 3);

        Page<Article> all = articleDao.findAll(pageRequest);
        for (Article article : all) {
            System.out.println(article);
        }
    }

    //排序查询
    @Test
    public void testFindWithSort(){
        //设置排序条件
        Sort sort = Sort.by(Sort.Order.desc("hits"));
        Iterable<Article> all = articleDao.findAll(sort);
        for (Article article : all) {
            System.out.println(article);
        }
    }

    //分页加排序查询
    @Test
    public void testFindAllWithPageAndSort(){
        //设置排序条件
        Sort sort = Sort.by(Sort.Order.desc("hits"));
        //设置分页条件
        PageRequest pageable = PageRequest.of(1, 3, sort);

        Page<Article> page = articleDao.findAll(pageable);

        for (Article article : page.getContent()) {
            System.out.println(article);
        }
    }


    //根据标题查询
    @Test
    public void testFindByTitle(){
        List<Article> es = articleDao.findByTitle("es");
        for (Article e : es) {
            System.out.println(e);
        }
    }

    //根据标题或内容查询
    @Test
    public void testFindByTitleOrContext(){
        List<Article> es = articleDao.findByTitleOrContext("es", "1");
        for (Article e : es) {
            System.out.println(e);
        }

    }

    //根据标题和内容查询(含分页)
    @Test
    public void testFindByTitleOrContextWithPage(){
        //设置排序条件
        Sort sort = Sort.by(Sort.Order.desc("hits"));

        //设置分页条件
        PageRequest pageRequest = PageRequest.of(1, 3, sort);

        List<Article> es = articleDao.findByTitleOrContext("es", "1", pageRequest);
        for (Article e : es) {
            System.out.println(e);
        }
    }

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值