基于spring-boot-starter-data-elasticsearch整合elasticsearch于window系统

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

使用环境:

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

在配置环境中会需要到elasticsearch和kibana,这两个和spring-boot-starter-data-elasticsearch都必须得保持版本一致,我们可以通过查看他maven的配置:

springboot-starter-data-es,elasticsearch,大数据,搜索引擎,java,spring boot,maven

比如我使用的是 spring-boot-starter-data-elasticsearch:2.7.3 查看到他的maven的结构后可以看到他们都指向了elasticsearch的一个版本7.17.4,因此在电脑上的配置好对应的版本springboot-starter-data-es,elasticsearch,大数据,搜索引擎,java,spring boot,maven

官方下载elasticsearch地址:Past Releases of Elastic Stack Software | Elastic

git下载elasticsearch地址:Releases · elastic/elasticsearch · GitHub

官方下载kibana地址:Past Releases of Elastic Stack Software | Elastic

git下载elasticsearch地址:Releases · elastic/kibana · GitHub

ik分词器下载地址:Releases · infinilabs/analysis-ik · GitHub

不用太在意我的7.16.2版本,只是当时不懂事的失败品(哭) 

创建配置类:

config:

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

@Configuration
public class RestClientConfiguration extends AbstractElasticsearchConfiguration {

    @Value("${ES.host}")
    private String host;

    @Value("${ES.post}")
    private String post;

    @Override
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(host + ":" + post)
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

yml文件:

ES:
  host: localhost
  post: 9200

这样配置可以满足各种加入许多不同的需求,具体有什么我也不懂(哭),还有一个简单的配置直接在yml中配置,与上面不同的就是只能满足简单的需求

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: localhost:9200

 以下代码都是基于我做的例子来展示,如果有需要还是得看:

Spring Data Elasticsearch - 参考文档

创建索引库结构:

@Document(indexName = "posts")//索引库名称
public class Posts {
    @Id
    private Long id;

    @Field(type = FieldType.Text, 
            analyzer = "ik_max_word")
    //类型text,analyzer 则是使用ak分词器的 粗颗粒分词
    private String title;

    @Field(type = FieldType.Text,
            analyzer = "ik_max_word")
    private String content;

    @Field(type = FieldType.Date,
            format = DateFormat.custom,
            pattern = "yyyy-MM-dd HH:mm:ss")
    //类型为date,这里的format和pattern是为了规定出时间的格式便于程序与es数据传递
    private LocalDateTime createTime;

    @Field(type = FieldType.Date,
            format = DateFormat.custom,
            pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;

    @Field(type = FieldType.Integer)//类型int
    private int likeCount;

    @Field(type = FieldType.Integer)
    private int commentCount;

    @Field(type = FieldType.Text)
    private String tags;

    @Field(type = FieldType.Text)
    private String imageUrls;

    @Field(type = FieldType.Integer)
    private int bookmarkedCount;

    @Field(type = FieldType.Integer)
    private int shareCount;

    @Field(type = FieldType.Integer)
    private int viewCount;

    @Field(type = FieldType.Integer)
    private int isDelete;

    @Field(type = FieldType.Keyword)//类型关键字
    private String type;

    private String latitude;//纬度

    private String longitude;//经度

    @GeoPointField//如果想使用地理查询就需要配置该注解,创建一个 GeoPoint 的对象
    private GeoPoint location;//els的地理位置

    @Field(type = FieldType.Double)
    private double sort;//els综合排序字段
}

创建出来在es查看的索引库结构为:

"posts" : {
    "aliases" : { },
    "mappings" : {
      "properties" : {
        "_class" : {
          "type" : "keyword",
          "index" : false,
          "doc_values" : false
        },
        "bookmarkedCount" : {
          "type" : "integer"
        },
        "commentCount" : {
          "type" : "integer"
        },
        "content" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        },
        "createTime" : {
          "type" : "date",
          "format" : "yyyy-MM-dd HH:mm:ss"
        },
        "id" : {
          "type" : "long"
        },
        "imageUrls" : {
          "type" : "text"
        },
        "isDelete" : {
          "type" : "integer"
        },
        "latitude" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "likeCount" : {
          "type" : "integer"
        },
        "location" : {
          "type" : "geo_point"
        },
        "longitude" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "shareCount" : {
          "type" : "integer"
        },
        "sort" : {
          "type" : "double"
        },
        "tags" : {
          "type" : "text"
        },
        "title" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        },
        "type" : {
          "type" : "keyword"
        },
        "updateTime" : {
          "type" : "date",
          "format" : "yyyy-MM-dd HH:mm:ss"
        },
        "viewCount" : {
          "type" : "integer"
        }
      }
    }

这里有一个很有意思的点是我对 

private String latitude;//纬度

private String longitude;//经度

这两个字段是什么都没有配置的,但是在索引库中却对它进行了一定的分析构建

"latitude" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },

"longitude" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }

这比我自己写的还好(哭) ,如果有想法可以尝试对一些没什么特殊需求的字段,进行不带任何注解进行创建索引库

Repository类:

public interface PostRepository extends ElasticsearchRepository<Posts, Long> {
}

这就是Repository类,要继承ElasticsearchRepository,两个范型分别为索引库的对应类,以及里面索引库主键的类型,它里面有着许多自定义方法,比如

springboot-starter-data-es,elasticsearch,大数据,搜索引擎,java,spring boot,maven

可以起着与ES查询类似的方法名来进行简单的查询,这些在官方文档,又或者其它文章也有相关的解释(其实是我不会这个哭)文章来源地址https://www.toymoban.com/news/detail-857696.html

自定义查询:

@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;

@Resource
private PostRepository postRepository;

//Spring提供的一个查询条件构建器,帮助构建json格式的请求体
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

nativeSearchQueryBuilder
        .withQuery(QueryBuilders
            .boolQuery()//选择bool查询 这里也可以直接选择其他查询不要bool,只是当前例子需要去掉被删除的帖子
            .must(QueryBuilders.termQuery("isDelete", 1))//去掉被删除的帖子 两个参数为:1.需要进行判断的字段 2.该值为1时去掉
            .must(QueryBuilders.multiMatchQuery(postPageDTO.getKeyWord(), "title", "content")))//添加分词查询 两个参数:1.需要匹配的数据 2.在那个字段中需要进行匹配,这里我对title,content两个字段都用了ik分词器
        .withSorts(SortBuilders.scoreSort());//添加按词频排序

//构建查询信息
NativeSearchQuery searchQuery = nativeSearchQueryBuilder
                                    .withPageable(PageRequest.of(postPageDTO.getPageNum() - 1, postPageDTO.getPageSize()))//添加分页查询 由于ES页码由0开始需要减一
                                    .build();//构建

//用els查询
SearchHits<Posts> search = elasticsearchRestTemplate.search(searchQuery, Posts.class);

关于地理位置的自定义查询:

@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;

@Resource
private PostRepository postRepository;

//此处直接有代码截来。但是知道他代表什么就行
double latitude = postPageDTO.getLocationDTO().getLatitude();//纬度
double longitude = postPageDTO.getLocationDTO().getLongitude();//经度

// 间接实现QueryBuilder接口
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

// 以某点为中心,搜索指定范围
GeoDistanceQueryBuilder distanceQueryBuilder = new GeoDistanceQueryBuilder("location");//这个参数的是对应索引库字段的地理位置字段

distanceQueryBuilder.point(latitude, longitude)//创建以什么为中心的经纬度地址
        distance(postPageDTO.getDistance(), DistanceUnit.KILOMETERS);//两个参数:1.设定查找的距离 2.定位查询单位:公里

//封装查询
boolQueryBuilder.filter(distanceQueryBuilder);

nativeSearchQueryBuilder
        .withQuery(QueryBuilders//添加位置查询同时去除掉被删除的帖子 这一部分与上面雷同
            .boolQuery()
            .must(QueryBuilders.termQuery("isDelete", 1))
            .must(boolQueryBuilder))
         .withSorts(SortBuilders
            .geoDistanceSort("location", latitude, longitude) //三个参数;1.对应索引库字段的地理位置字段 2和3:创建以什么为中心的经纬度地址
            .unit(DistanceUnit.KILOMETERS)//定位查询单位:公里
            .order(SortOrder.ASC));// 按距离升序

//构建查询信息
NativeSearchQuery searchQuery = nativeSearchQueryBuilder
                                    .withPageable(PageRequest.of(postPageDTO.getPageNum() - 1, postPageDTO.getPageSize()))//添加分页查询 由于ES页码由0开始需要减一
                                    .build();//构建

//用els查询
SearchHits<Posts> search = elasticsearchRestTemplate.search(searchQuery, Posts.class);

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

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

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

相关文章

  • Jpa与Druid线程池及Spring Boot整合(二): spring-boot-starter-data-jpa 踏坑异常处理方案

                         docker实战(一):centos7 yum安装docker docker实战(二):基础命令篇 docker实战(三):docker网络模式(超详细) docker实战(四):docker架构原理 docker实战(五):docker镜像及仓库配置 docker实战(六):docker 网络及数据卷设置 docker实战(七):docker 性质及版本选择 认知升维: 道、法、

    2024年02月13日
    浏览(45)
  • Spring Boot Starter Data Redis使用Lettuce客户端报错:NOAUTH Authentication required

    Spring Boot版本升级为:2.6.14 redis依赖: redis配置不变,还是带password的: 项目启动后,获取redis连接时,报错:NOAUTH Authentication required spring-boot-starer-data-redis支持使用Jedis和Lettuce作为redis客户端,如果配置不指定则默认使用Lettuce。 不管是Lettuce还是还是Jedis,核心是构建RedisCo

    2024年01月25日
    浏览(36)
  • Redisson学习之项目引入reidsson— 基于redisson-spring-boot-starter

    or redisson-spring-boot -starter初始化过程 基于redisson学习加载\\\"文本\\\"配置文件

    2024年02月15日
    浏览(39)
  • Spring Boot - spring-boot-starter

    spring-boot-starter 当学习Spring Boot时,可以通过一个完整的案例来理解和实践其基本概念和功能。以下是一个简单的Spring Boot Starter完整案例,展示了如何创建一个基本的Web应用程序: 首先,创建一个名为pom.xml的Maven项目文件,添加以下内容:idea或其他直接创建直接跳过!

    2024年02月09日
    浏览(31)
  • Spring Boot Starters

    Spring Boot Starters 概述 Spring Boot Starters是一系列为特定应用场景预设的依赖管理和自动配置方案。每个Starter都是为了简化特定类型的项目构建和配置。例如, spring-boot-starter-web 是为创建基于Spring MVC的Web应用程序而设计的。 Starter的结构 一个典型的Starter包含以下部分: pom.xml

    2024年01月25日
    浏览(27)
  • 自定义Spring Boot Starter

    Spring Boot starter 我们知道Spring Boot大大简化了项目初始搭建以及开发过程,而这些都是通过Spring Boot提供的starter来完成的。在实际项目中一些基础模块其本质就是starter,所以我们需要对Spring Boot的starter有一个全面深入的了解,这是我们的必备知识。 starter介绍 spring boot 在配置

    2024年02月10日
    浏览(70)
  • Spring Boot Starter设计实现

    Starter 是 Spring Boot 非常重要的一个硬核功能。 通过 Starter 我们可以快速的引入一个功能或模块,而无须关心模块依赖的其它组件。关于配置,Spring Boot 采用“约定大于配置”的设计理念,Starter 一般都会提供默认配置,只有当我们有特殊需求的时候,才需要在 application.yaml 里

    2024年01月18日
    浏览(32)
  • Spring Boot Starter Parent

    在这,您将学习了解 Spring Boot Starter Parent, 它是 Spring Boot 提供的父级 Pom 文件,旨在提供自动版本依赖管理,帮助我们轻松快速地进行 Spring Boot 开发。 通过 Spring Boot Starter Parent, 我们可以进行简单便捷地包依赖管理。在 Spring Boot 每一个发行版中, 均提供了该版本所兼容的依

    2024年02月08日
    浏览(27)
  • 6. Spring Boot的starters

    6. Spring Boot的starters(重要) 一般认为,SpringBoot 微框架从两个主要层面影响 Spring 社区的开发者们: 基于 Spring 框架的“约定优先于配置(COC)”理念以及最佳实践之路。 提供了针对日常企业应用研发各种场景的 spring-boot-starter 自动配置依赖模块,如此多“开箱即用”的依赖模

    2024年01月24日
    浏览(33)
  • shiro-spring-boot-starter针对不同Spring Boot版本

    对于Spring Boot 2.4.10,无法找到shiro-spring-boot-starter的2.7.2版本,这是一个错误的版本号。 shiro-spring-boot-starter针对不同Spring Boot版本,推荐使用的版本如下: Spring Boot 1.x - 使用版本1.4.1 Spring Boot 2.0.x - 使用版本1.5.3 Spring Boot 2.1.x - 使用版本1.6.0 Spring Boot 2.2.x - 使用版本1.7.0 Spring Boot 2.3

    2024年02月13日
    浏览(32)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包