Spring整合Elasticsearch

这篇具有很好参考价值的文章主要介绍了Spring整合Elasticsearch。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

        启动Elasticsearch的集群,如果不会搭建集群可以看我以前的文章

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

         进入到head的扩展应用,连接后面的健康值为green就表示集群没问题

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

 

Spring Data Elasticsearch  

特征:    Spring配置支持使用基于Java的 @Configuration 类或ES客户端实例的XML命名空间。
            ElasticsearchTemplate 帮助类,它可以提高执行常见ES操作的效率。包括文档和POJO之间的集成对象映射。
            与Spring的转换服务集成的功能丰富的对象映射。
            基于注释的映射元数据,但可扩展以支持其他元数据格式。
            自动实现 Repository 接口,包括对自定义查找器方法的支持
            对存储库的CDI支持

        1.导入pom的依赖

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

        2.配置核心配置文件

# 集群的名称
spring.data.elasticsearch.cluster-name=xm
# 集群的ES服务器Node节点信息
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303

        注意:如果配置文件报红是因为springboot版本太高不兼容,需要调低版本                                      建议调为 <version>2.1.16.RELEASE</version>,在低版本中,没有总的运行测试类,需要将测试类注解的包重新导一下, import org.junit.Test;

        注解: 

            @Document
                indexName:索引库名称          type:类型名称,默认是"docs"
                shards:分⽚数量,默认5        replicas:副本数量,默认1
            @Id          声明实体类的id
            @Field         type:字段的数据类型             analyzer:指定分词器类型
                                index:是否创建索引

        3.创建实体类Producter

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; 
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;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "leq",type = "product",shards = 3,replicas = 1)
public class Producter {
    @Id
    private Long id; // 主键
    @Field(type = FieldType.Text,analyzer = "ik_max_word")
    private String title; // 标题
    @Field(type = FieldType.Keyword)
    private String category; // 分类
    @Field(type = FieldType.Keyword)
    private String brand; // 品牌
    @Field(type = FieldType.Double)
    private Double price; // 价格
    @Field(type = FieldType.Keyword,index = false)
    private String images; // 图片地址
}

        4.测试集群有没有连通

import com.esclient.es.pojo.Producter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)//低版本的单元测试添加的注解
@SpringBootTest
public class SpringDataESTests {
    @Autowired
    private ElasticsearchTemplate template; 

    @Test
    public void check(){
        System.out.println(template);
    } 
}

 控制台打印org.springframework.data.elasticsearch.core.ElasticsearchTemplate@6c6379c就表示连接成功Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

        创建索引,索引创建后可以在head插件中看到刚刚创建的索引,索引在实例类中定义的 

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

        加载映射

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

         创建mapper层,定义一个接口继承ElasticsearchRepository类,第一个参数为映射的实体类,第二个为主键id的类型

import com.esclient.es.pojo.Producter;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface ProducterRepository extends ElasticsearchRepository<Producter,Long> {

}

        新增,新增的数据可以在head插件中查看到 

 @Test//新增
    public void addDocument(){
        Producter producter = new Producter(1l, "荣耀", "手机", "小米", 2999d, "1.img");
        Producter save = producterRepository.save(producter);
        System.err.println(save);
    }

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎        批量新增

    @Test//批量新增
    public void batchAddDocument(){
        Producter p1 = new Producter(2l, "华为荣耀", "手机", "鸿蒙", 2999d, "1.img");
        Producter p2 = new Producter(3l, "小米荣耀", "手机", "黑米", 2899d, "1.img");
        Producter p3 = new Producter(4l, "王者荣耀", "手机", "白米", 2969d, "1.img");
        Producter p4 = new Producter(5l, "小满荣耀", "手机", "红米", 2109d, "1.img");

        List<Producter> l =new ArrayList<>();
       l.add(p1);
       l.add(p2);
       l.add(p3);
       l.add(p4);

       Iterable<Producter> producters = producterRepository.saveAll(l);
        System.err.println(producters.toString());
    }

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

 

        查询

        1.通过id查询

  @Test//通过id查询
    public void findById(){
        Optional<Producter> option = producterRepository.findById(1l);

        Producter defaultbean = new Producter();
        defaultbean.setTitle("这是一个默认的数据");

        Producter producter = option.orElse(defaultbean);//如果option为空把defaultbean返回给用户,不为空把查询出来的数据返回给用户
        System.err.println(producter);
    }

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

         2.查询所有

     @Test//查询所有
    public void findAll(){
        Iterable<Producter> all = producterRepository.findAll();
        all.forEach(System.err::println);
    }

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎        3.自定义方法查询 根据区间查询商品信息

        在mapper层定义方法 

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

   @Test//自定义方法查询  根据区间查询商品信息
    public void between(){
        List<Producter> byPriceBetween = producterRepository.findByPriceBetween(2900d, 3000d);
        byPriceBetween.forEach(System.err::println);
    }

Spring整合Elasticsearch,spring,elasticsearch,java,搜索引擎

                      关键字                                                         示例                                                         Elasticsearch查询字符串

                         And                                               findByNameAndPrice                         {"bool" : {"must" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}

                         Or                                                      findByNameOrPrice                            {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}

                        Is                                                         findByName                                                 {"bool" : {"must" : {"field" : {"name" : "?"}}}}

                         Not                                                   findByNameNot                                         {"bool" : {"must_not" : {"field" : {"name" : "?"}}}}

                 Betweend                                                 findByPriceBetween                 {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}

                 LessThanEqual                                         findByPriceLessThan             {"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}

                GreaterThanEqual                                 findByPriceGreaterThan            {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}

                Before                                                    findByPriceBefore                      {"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}

                 After                                                        findByPriceAfter                       {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}

                 Like                                                         findByNameLike                               {"bool" : {"must" : {"field" : {"name" : {"query" : "? *","analyze_wildcard" : true}}}}}

                StartingWith                                          findByNameStartingWith                     {"bool" : {"must" : {"field" : {"name" : {"query" : "? *","analyze_wildcard" : true}}}}}

                 EndingWith                                         findByNameEndingWith                        {"bool" : {"must" : {"field" : {"name" : {"query" : "*?","analyze_wildcard" : true}}}}}

                Contains/Containing                                 findByNameContaining                    {"bool" : {"must" : {"field" : {"name" : {"query" : "? ","analyze_wildcard" : true}}}}}

                 In                                                         findByNameIn(Collectionnames)          {"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}}

                 NotIn                                                 findByNameNotIn(Collectionnames)                 {"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}}

                 Near                                                 findByStoreNear                                               Not Supported Yet !

                 True                                                         findByAvailableTrue                                 {"bool" : {"must" : {"field" : {"available" : true}}}}

                False                                                         findByAvailableFalse                                {"bool" : {"must" : {"field" : {"available" : false}}}}

                OrderBy                                                findByAvailableTrueOrderByNameDesc        {"sort" : [{ "name" : {"order" : "desc"} }],"bool" : {"must" : {"field" : {"available" : true}}}}文章来源地址https://www.toymoban.com/news/detail-576579.html

到了这里,关于Spring整合Elasticsearch的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Boot 整合Elasticsearch入门

    Spring Data Elasticsearch 是 Spring Data 项目的子项目,提供了 Elasticsearch 与 Spring 的集成。实现了 Spring Data Repository 风格的 Elasticsearch 文档交互风格,让你轻松进行 Elasticsearch 客户端开发。 应粉丝要求特地将 Elasticsearch 整合到 Spring Boot  中去。本来打算整合到 kono 脚手架中,但是转

    2024年04月13日
    浏览(31)
  • spring boot es | spring boot 整合elasticsearch | spring boot整合多数据源es

    目录 Spring Boot与ES版本对应 Maven依赖 配置类 使用方式 @Test中注入方式 @Component中注入方式 查询文档 实体类 通过ElasticsearchRestTemplate查询 通过JPA查询 保存文档 参考链接 项目组件版本: Spring Boot:2.2.13.RELEASE Elasticsearch:6.8.0 JDK:1.8.0_66 Tips: 主要看第3列和第5列,根据ES版本选择

    2023年04月18日
    浏览(43)
  • 使用ElasticsearchRepository和ElasticsearchRestTemplate操作Elasticsearch,Spring Boot整合Elasticsearch

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 Elasticsearch官网参考文档:https://www.elastic.co/guide/index.html Elasticsearch官方下载地址:https://www.elastic.co/cn/downloads/elasticsearch https://docs.spring.io/spring-data/elasticsearch/reference/ 添加依赖 修改yml配置文件 【自定义

    2024年04月22日
    浏览(33)
  • Spring Boot整合Elasticsearch超详细教程

    SpringBoot整合Elasticsearch超详细教程 最新高级版 (1)导入springboot整合ES高级别客户端的坐标 (2)使用编程的形式设置连接的ES服务器,并获取客户端对象 (3)Book实体类 (4)连接Dao层 (5)使用客户端对象操作ES 例如创建索引:(这里需要先执行上面的删除索引操作,否则会报错)

    2023年04月09日
    浏览(40)
  • Spring Boot进阶(19):Spring Boot 整合ElasticSearch | 超级详细,建议收藏

            ElasticSearch是一款基于Lucene的开源搜索引擎,具有高效、可扩展、分布式的特点,可用于全文搜索、日志分析、数据挖掘等场景。Spring Boot作为目前最流行的微服务框架之一,也提供了对ElasticSearch的支持。本篇文章将介绍如何在Spring Boot项目中整合ElasticSearch,并展

    2024年02月06日
    浏览(31)
  • 在Spring Boot中整合Elasticsearch并实现高亮搜索

    本文详细介绍了如何在Spring Boot项目中整合Elasticsearch,实现高亮搜索功能。通过添加依赖、配置Spring Boot、为实体类添加注解,以及在Service层实现高亮搜索,读者能够了解如何在实际项目中利用Spring Boot Data Elasticsearch来操作Elasticsearch并实现高亮搜索。验证示例演示了如何使用RESTful API端点来搜索并获取包含高亮字段的用户列表,为读者提供了实际应用的参考。这篇文章将帮助读者轻松掌握Spring Boot与Elasticsearch的整合方法,从而为项目增加强大的搜索功能。

    2024年02月06日
    浏览(31)
  • Springboot --- 整合spring-data-jpa和spring-data-elasticsearch

    SpringBoot: 整合Ldap. SpringBoot: 整合Spring Data JPA. SpringBoot: 整合Elasticsearch. SpringBoot: 整合spring-data-jpa和spring-data-elasticsearch. SpringBoot: 整合thymeleaf. SpringBoot: 注入第三方jar包. SpringBoot: 整合Redis. SpringBoot: 整合slf4j打印日志. SpringBoot: 整合定时任务,自动执行方法. SpringBoot: 配置多数据源

    2023年04月25日
    浏览(48)
  • 知识点13--spring boot整合elasticsearch以及ES高亮

    本章知识点沿用知识点12的项目,介绍如何使用spring boot整合ES,没有ES的去我主页 各类型大数据集群搭建文档--大数据原生集群本地测试环境搭建三 中可以看到ES如何搭建 不管你有没有ES,最好是没有,因为一定要知道一点,一定要去官网查一下你当前用的spring boot data es的版

    2024年02月12日
    浏览(33)
  • 统一日志管理方案:Spring项目logback日志与logstash和Elasticsearch整合

    原创/朱季谦 最近在做一个将分布式系统的日志数据通过logstash传到kafka的功能,做完之后决定业余搭一个ELK日志分析系统,将logstash采集到的日志传给Elasticsearch。经过一番捣鼓,也把这个过程给走通了,于是写了这篇总结,可按照以下步骤搭建logstash采集spring日志数据并传输

    2024年02月03日
    浏览(31)
  • [Java Framework] [ELK] Spring 整合ES (ElasticSearch7.15.x +)

    ElasticSearch7.15.x 版本后,废弃了高级Rest客户端的功能 2.1 配置文件 2.2 配置类 3.1 索引的相关操作 3.2 实体映射相关操作 3.2.1 创建实体类 3.2.2 Doc实体操作API 3.3 聚合相关操作 3.3.1 创建实体类 3.3.2 创建操作类 [1] Elasticsearch Clients [2] Elasticsearch Clients - Aggregations

    2023年04月08日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包