Elasticsearch--SpringBoot 整合 Elasticsearch

作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO

联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬

学习必须往深处挖,挖的越深,基础越扎实!

阶段1、深入多线程

阶段2、深入多线程设计模式

阶段3、深入juc源码解析


阶段4、深入jdk其余源码解析


阶段5、深入jvm源码解析

码哥源码部分

码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】

码哥讲源码【炸雷啦!炸雷啦!黄光头他终于跑路啦!】

码哥讲源码-【jvm课程前置知识及c/c++调试环境搭建】

​​​​​​码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】

码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】

码哥讲源码【你水不是你的错,但是你胡说八道就是你不对了!】

码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!

打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】

引入依赖
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.0.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>pers.zhang</groupId>
        <artifactId>sb_elasticsearch</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>sb_elasticsearch</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
配置

application.yml

    spring:
      data:
        elasticsearch:
          cluster-name: elasticsearch
          cluster-nodes: 127.0.0.1:9300
          repositories:
            enabled: true
启动类
    @SpringBootApplication
    @EnableElasticsearchRepositories(basePackages = "pers.zhang")
    public class SbElasticsearchApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SbElasticsearchApplication.class, args);
        }
    
    }
实体类
    package pers.zhang.sb_elasticsearch.entity;
    
    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;
    
   
    @Document(indexName = "index-article", type = "article")
    public class Article {
    
        @Id
        @Field(type = FieldType.Long, store = true)
        private Long id;
    
        @Field(type = FieldType.text, store = true, analyzer = "ik_smart")
        private String title;
    
        @Field(type = FieldType.text, store = true, analyzer = "ik_smart")
        private String content;
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        @Override
        public String toString() {
            return "Article{" +
                    "id=" + id +
                    ", title='" + title + '\'' +
                    ", content='" + content + '\'' +
                    '}';
        }
    }
Repository
    public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
    
        //根据标题进行查询
        List<Article> findByTitle(String title);
    
        List<Article> findByTitleOrContent(String title, String context);
    
        List<Article> findByTitleOrContent(String title, String context, Pageable pageable);
    }
测试
    @SpringBootTest(classes = SbElasticsearchApplication.class)
    @RunWith(SpringJUnit4ClassRunner.class)
    public class SbElasticsearchApplicationTests {
    
        @Autowired
        ArticleRepository articleRepository;
    
        @Autowired
        ElasticsearchTemplate elasticsearchTemplate;
    
        @Test
        public void createIndex() {
            elasticsearchTemplate.createIndex(Article.class);
        }
    
        @Test
        public void addDocument () {
            Article article = new Article();
            article.setId(3l);
            article.setTitle("Maven对象模型");
            article.setContent("佛教圣地六块腹肌塑料袋放假了撒");
            articleRepository.save(article);
        }
    
        @Test
        //查询所有
        public void findAll () {
            Iterable<Article> all = articleRepository.findAll();
            all.forEach( a -> System.out.println(a));
        }
    
        @Test
        //根据id查询
        public void findById () {
            Optional<Article> byId = articleRepository.findById(1l);
            System.out.println(byId.get());
        }
    
        @Test
        public void findByTitle () {
            List<Article> list = articleRepository.findByTitle("对象");
            list.forEach( a -> System.out.println(a));
        }
    
        @Test
        //多条件查询
        public void findByTitleOrContent () {
            List<Article> list = articleRepository.findByTitleOrContent("ddd", "放假");
            list.forEach( a -> System.out.println(a));
        }
    
        @Test
        //分页查询
        public void findByPage () {
            Pageable pageable = PageRequest.of(0, 2);
            List<Article> list = articleRepository.findByTitleOrContent("ddd", "放假", pageable);
            list.forEach( a -> System.out.println(a));
        }
    
        //原生查询
        @Test
        public void testNativeSearchQuery () {
            NativeSearchQuery query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.queryStringQuery("佛放假").defaultField("content"))
                    .withPageable(PageRequest.of(0, 5))
                    .build();
            List<Article> articles = elasticsearchTemplate.queryForList(query, Article.class);
            articles.forEach(a -> System.out.println(a));
        }
    
        @Test
        public void deleteById () {
            articleRepository.deleteById(1l);
        }
    }
  • 11
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于 Spring Boot Starter Data 整合 Elasticsearch,可以按照以下步骤进行: 1. 在 pom.xml 文件中添加 Elasticsearch 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 在 application.properties 文件中配置 Elasticsearch 的连接信息: ```properties spring.data.elasticsearch.cluster-nodes=localhost:9300 spring.data.elasticsearch.cluster-name=my-application ``` 其中,cluster-nodes 是 Elasticsearch 集群节点的地址,cluster-name 是集群名称。 3. 创建一个 ElasticsearchRepository 接口来定义 Elasticsearch 的操作: ```java public interface BookRepository extends ElasticsearchRepository<Book, String> { } ``` 其中,Book 是实体类,String 是实体类主键的数据类型。 4. 在需要使用 Elasticsearch 的地方注入 ElasticsearchRepository 接口,并使用它进行数据操作: ```java @Autowired private BookRepository bookRepository; public void saveBook(Book book) { bookRepository.save(book); } public List<Book> findBooksByAuthor(String author) { return bookRepository.findByAuthor(author); } ``` 这里的 save 方法是保存数据,findByAuthor 方法是按照作者查询数据。 以上就是 Spring Boot Starter Data 整合 Elasticsearch 的基本步骤。需要注意的是,这里使用的是 ElasticsearchRepository 接口,它提供了一些常用的操作方法,如果需要更多的操作,可以使用 ElasticsearchTemplate 类来进行操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值