SpringBoot 3.2.5 + ElasticSearch 8.12.0 - SpringData 开发指南

 

目录

一、SpringData ElasticSearch

1.1、环境配置

1.2、创建实体类

1.3、ElasticSearchTemplate 的使用

1.3.1、创建索引库,设置映射

1.3.2、创建索引映射注意事项

1.3.3、简单的 CRUD

1.3.4、三种构建搜索条件的方式

1.3.5、NativeQuery 搜索实战

1.3.6、completionSuggestion 自动补全


一、SpringData ElasticSearch


1.1、环境配置

a)依赖如下:

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><!--SpringBoot3 之后测试必须引入这个包--><dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>2.23.4</version><scope>test</scope></dependency>

b)配置文件如下:

spring:application:name: eselasticsearch:uris: env-base:9200

1.2、创建实体类

a)简单结构如下(后续示例,围绕此结构展开):

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 = "album_info", )
data class AlbumInfoDo (/*** @Id: 表示文档中的主键,并且会在保存在 ElasticSearch 数据结构中 {"id": "", "userId": "", "title": ""}*/@Id@Field(type = FieldType.Keyword)val id: Long? = null,/*** @Field: 描述 Java 类型中的属性映射*      - name: 对应 ES 索引中的字段名. 默认和属性同名*      - type: 对应字段类型,默认是 FieldType.Auto (会根据我们数据类型自动进行定义),但是建议主动定义,避免导致错误映射*      - index: 是否创建索引. text 类型创建倒排索引,其他类型创建正排索引.  默认是 true*      - analyzer: 分词器名称.  中文我们一般都使用 ik 分词器(ik分词器有 ik_smart 和 ik_max_word)*/@Field(name = "user_id", type = FieldType.Long)val userId: Long,@Field(type = FieldType.Text, analyzer = "ik_max_word")var title: String,@Field(type = FieldType.Text, analyzer = "ik_smart")var content: String,
)

b)复杂嵌套结构如下:

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 = "album_list")
data class AlbumListDo(@Id@Field(type = FieldType.Keyword)var id: Long,@Field(type = FieldType.Nested) // 表示一个嵌套结构var userinfo: UserInfoSimp,@Field(type = FieldType.Text, analyzer = "ik_max_word")var title: String,@Field(type = FieldType.Text, analyzer = "ik_smart")var content: String,@Field(type = FieldType.Nested) // 表示一个嵌套结构var photos: List<AlbumPhotoSimp>,
)data class UserInfoSimp(@Field(type = FieldType.Long)val userId: Long,@Field(type = FieldType.Text, analyzer = "ik_max_word")val username: String,@Field(type = FieldType.Keyword, index = false)val avatar: String,
)data class AlbumPhotoSimp(@Field(type = FieldType.Integer, index = false)val sort: Int,@Field(type = FieldType.Keyword, index = false)val photo: String,
)

对于一个小型系统来说,一般也不会创建这种复杂程度的文档,因为会涉及到很多一致性问题, 需要通过大量的 mq 进行同步,给系统带来一定的开销. 

因此,一般会将需要进行模糊查询的字段存 Document 中(es 就擅长这个),而其他数据则可以在 Document 中以 id 的形式进行存储.   这样就既可以借助 es 高效的模糊查询能力,也能减少为保证一致性而带来的系统开销.  从 es 中查到数据后,再通过其他表的 id 从数据库中拿数据即可(这点开销,相对于从大量数据的数据库中进行 like 查询,几乎可以忽略).

1.3、ElasticSearchTemplate 的使用

1.3.1、创建索引库,设置映射

@SpringBootTest
class ElasticSearchIndexTests {@Resourceprivate lateinit var elasticsearchTemplate: ElasticsearchTemplate@Testfun test1() {//存在索引库就删除if (elasticsearchTemplate.indexOps(AlbumInfoDo::class.java).exists()) {elasticsearchTemplate.indexOps(AlbumInfoDo::class.java).delete()}//创建索引库elasticsearchTemplate.indexOps(AlbumInfoDo::class.java).create()//设置映射elasticsearchTemplate.indexOps(AlbumInfoDo::class.java).putMapping(elasticsearchTemplate.indexOps(AlbumInfoDo::class.java).createMapping())}}

效果如下: 

1.3.2、创建索引映射注意事项

a)在没有创建索引库和映射的情况下,也可以直接向 es 库中插入数据,如下代码:

    @Testfun test2() {val obj = AlbumListDo(id = 1,userinfo = UserInfoSimp(userId = 1,username = "cyk",avatar = "env-base:9200"),title = "今天天气真好",content = "早上起来,我要好好学习,然去公园散步~",photos = listOf(AlbumPhotoSimp(1, "www.photo.com/aaa"),AlbumPhotoSimp(2, "www.photo.com/bbb")))val result = elasticsearchTemplate.save(obj)println(result)}

即使上述代码中 AlbumListDo 中有各种注解标记,但是不会生效!!! es 会根据插入的数据,自动转化数据结构(无视你的注解).

因此,建议先创建索引库和映射,再进行数据插入!

1.3.3、简单的 CRUD

import jakarta.annotation.Resource
import org.cyk.es.model.AlbumInfoDo
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate
import org.springframework.data.elasticsearch.core.document.Document
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates
import org.springframework.data.elasticsearch.core.query.UpdateQuery@SpringBootTest
class ElasticSearchCRUDTests {@Resourceprivate lateinit var elasticsearchTemplate: ElasticsearchTemplate@Testfun testSave() {//保存单条数据val a1 = AlbumInfoDo(id = 1,userId = 10000,title = "今天天气真好",content = "学习完之后,我要出去好好玩")val result = elasticsearchTemplate.save(a1)println(result)//保存多条数据val list = listOf(AlbumInfoDo(2, 10000, "西安六号线避雷", "前俯后仰。他就一直在那前后动。他背后是我朋友,我让他不要挤了,他直接就急了,开始故意很大力的挤来挤去。"),AlbumInfoDo(3, 10000, "字节跳动快上车~", "#内推 #字节跳动内推 #互联网"),AlbumInfoDo(4, 10000, "连王思聪也变得低调老实了", "如今的王思聪,不仅交女友的质量下降,在网上也不再像以前那样随意喷这喷那。显然,资金的紧张让他低调了许多"))val resultList = elasticsearchTemplate.save(list)resultList.forEach(::println)}@Testfun testDelete() {//根据主键删除,例如删除主键 id = 1 的文档elasticsearchTemplate.delete("1", AlbumInfoDo::class.java)}@Testfun testGet() {//根据主键获取文档val result = elasticsearchTemplate.get("1", AlbumInfoDo::class.java)println(result)}@Testfun testUpdate() {//例如,修改 id = 1 的文档val id = 1val title = "今天天气不太好"val content = "天气不好,只能在家里学习了。。。"val uq = UpdateQuery.builder(id.toString()).withDocument(Document.create().append("title", title).append("content", content)).build()val result = elasticsearchTemplate.update(uq, IndexCoordinates.of("album_info")).resultprintln(result.ordinal)println(result.name)}}

1.3.4、三种构建搜索条件的方式

关于搜索条件的构建,Spring 官网上给出了三种构建方式:Elasticsearch Operations :: Spring Data Elasticsearch

a)CriteriaQuery:允许创建查询来搜索数据,而不需要了解 Elasticsearch 查询的语法或基础知识。它们允许用户通过简单地链接和组合 Criteria 对象来构建查询,Criteria 对象指定被搜索文档必须满足的条件。

Criteria criteria = new Criteria("lastname").is("Miller") .and("firstname").is("James")                           
Query query = new CriteriaQuery(criteria);

b)StringQuery:这个类接受 Elasticsearch 查询作为 JSON String。下面的代码显示了一个搜索名为“ Jack”的人的查询:

Query query = new StringQuery("{ \"match\": { \"firstname\": { \"query\": \"Jack\" } } } ");
SearchHits<Person> searchHits = operations.search(query, Person.class);

c)NativeQuery:当您有一个复杂的查询或者一个无法使用 Criteria API 表示的查询时,例如在构建查询和使用聚合时,可以使用 NativeQuery 类。

d)到底使用哪一种呢?在最新的这一版 SpringDataES 中,NativeQuery 中可以通过大量的 Lambda 来构建条件语句,并且外观上也很符合 ElasticSearch DSL,那么对于比较熟悉原生的 DSL 语句的就建议使用 NativeQuery 啦.  我本人也更倾向 NativeQuery,因此后续的案例都会使用它.

1.3.5、NativeQuery 搜索实战

import co.elastic.clients.elasticsearch._types.SortOrder
import co.elastic.clients.json.JsonData
import jakarta.annotation.Resource
import org.cyk.es.model.AlbumInfoDo
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.data.domain.PageRequest
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate
import org.springframework.data.elasticsearch.client.elc.NativeQuery
import org.springframework.data.elasticsearch.core.query.HighlightQuery
import org.springframework.data.elasticsearch.core.query.highlight.Highlight
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField
import org.springframework.data.elasticsearch.core.query.highlight.HighlightParameters@SpringBootTest
class SearchTests {@Resourceprivate lateinit var elasticsearchTemplate: ElasticsearchTemplate/*** 全文检索查询(match_all)*/@Testfun testMatchAllQuery() {val query = NativeQuery.builder().withQuery { q -> q.matchAll { it }}.build()val hits = elasticsearchTemplate.search(query, AlbumInfoDo::class.java)hits.forEach { println(it.content) }}/*** 精确查询(match)*/@Testfun testMatchQuery() {val query = NativeQuery.builder().withQuery { q -> q.match {it.field("title").query("天气")}}.build()val hits = elasticsearchTemplate.search(query, AlbumInfoDo::class.java)hits.forEach { println(it.content) }}/*** 精确查询(term)*/@Testfun testTerm() {val query = NativeQuery.builder().withQuery { q -> q.term { t -> t.field("id").value("2")}}.build()val hits = elasticsearchTemplate.search(query, AlbumInfoDo::class.java)hits.forEach { println(it.content) }}/*** 范围搜索*/@Testfun testRangeQuery() {val query = NativeQuery.builder().withQuery { q -> q.range { r -> r.field("id").gte(JsonData.of(1)).lt(JsonData.of(4)) // 大于等于 1,小于 4}}.build()val hits = elasticsearchTemplate.search(query, AlbumInfoDo::class.java)hits.forEach { println(it.content) }}/*** bool 复合搜索*/@Testfun testBoolQuery() {val query = NativeQuery.builder().withQuery { q -> q.bool { b -> b.must { m -> m.range { r -> r.field("id").gte(JsonData.of(1)).lt(JsonData.of(4)) // 大于等于 1,小于 4}}.mustNot { n -> n.match { mc -> mcmc.field("title").query("天气")}}.should { s -> s.matchAll { it }}}}.build()val hits = elasticsearchTemplate.search(query, AlbumInfoDo::class.java)hits.forEach { println(it.content) }}/*** 排序 + 分页*/@Testfun testSortAndPage() {//a) 方式一
//        val query = NativeQuery.builder()
//            .withQuery { q -> q
//                .matchAll { it }
//            }
//            .withPageable(
//                PageRequest.of(0, 3) //页码(从 0 开始),非偏移量
//                    .withSort(Sort.by(Sort.Order.desc("id")))
//            ).build()//b) 方式二val query = NativeQuery.builder().withQuery { q -> q.matchAll { it }}.withSort { s -> s.field { f->f.field("id").order(SortOrder.Desc) } }.withPageable(PageRequest.of(0, 3)) //页码(从 0 开始),非偏移量).build()val hits = elasticsearchTemplate.search(query, AlbumInfoDo::class.java)hits.forEach { println(it.content) }}@Testfun testHighLight() {//所有需要高亮的字段val highField = listOf(HighlightField("title"),HighlightField("content"))val query = NativeQuery.builder().withQuery { q ->q.multiMatch { ma -> ma.fields("title", "content").query("天气")}}.withHighlightQuery(HighlightQuery(Highlight(HighlightParameters.builder().withPreTags("<span style='color:red'>") //前缀标签.withPostTags("</span>") //后缀标签.withFragmentSize(10) //高亮的片段长度(多少个几个字需要高亮,一般会设置的大一些,让匹配到的字段尽量都高亮).withNumberOfFragments(1) //高亮片段的数量.build(),highField),String::class.java)).build()val hits = elasticsearchTemplate.search(query, AlbumInfoDo::class.java)//hits.content 本身是没有高亮数据的,因此这里需要手动处理hits.forEach {val result = it.content//根据高亮字段名称,获取高亮数据集合val titleList = it.getHighlightField("title")val contentList = it.getHighlightField("content")if (titleList.size > 0) result.title = titleList[0]if (contentList.size > 0) result.content = contentList[0]println(result)}}}

1.3.6、completionSuggestion 自动补全

a)自动补全的字段必须是 completion 类型. 
这里自动补全的字段为 title,通过 copyTo 将其拷贝到 suggestion 字段中,实现自动补全.
import org.springframework.data.annotation.Id
import org.springframework.data.elasticsearch.annotations.CompletionField
import org.springframework.data.elasticsearch.annotations.Document
import org.springframework.data.elasticsearch.annotations.Field
import org.springframework.data.elasticsearch.annotations.FieldType
import org.springframework.data.elasticsearch.core.suggest.Completion@Document(indexName = "album_doc")
data class AlbumSugDo (@Id@Field(type = FieldType.Keyword)val id: Long,@Field(name = "user_id", type = FieldType.Long)val userId: Long,@Field(type = FieldType.Text, analyzer = "ik_max_word", copyTo = ["suggestion"]) //注意,copyTo 的字段一定是 var 类型val title: String,@Field(type = FieldType.Text, analyzer = "ik_smart")val content: String,@CompletionField(maxInputLength = 100, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")var suggestion: Completion? = null, //注意,被 copyTo 的字段一定要是 var 类型
)

Ps:被 copyTo 的字段一定要是 var 类型

b)需求:在搜索框中输入 “今天”,对其进行自动补全.

import co.elastic.clients.elasticsearch.core.search.FieldSuggester
import co.elastic.clients.elasticsearch.core.search.FieldSuggesterBuilders
import co.elastic.clients.elasticsearch.core.search.Suggester
import jakarta.annotation.Resource
import org.cyk.es.model.AlbumSugDo
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate
import org.springframework.data.elasticsearch.client.elc.NativeQuery
import org.springframework.data.elasticsearch.core.suggest.response.Suggest@SpringBootTest
class SuggestTests {@Resourceprivate lateinit var elasticsearchTemplate: ElasticsearchTemplate@Testfun init() {if(elasticsearchTemplate.indexOps(AlbumSugDo::class.java).exists()) {elasticsearchTemplate.indexOps(AlbumSugDo::class.java).delete()}elasticsearchTemplate.indexOps(AlbumSugDo::class.java).create()elasticsearchTemplate.indexOps(AlbumSugDo::class.java).putMapping(elasticsearchTemplate.indexOps(AlbumSugDo::class.java).createMapping())elasticsearchTemplate.save(listOf(AlbumSugDo(1, 10000, "今天发现西安真美", "西安真美丽啊,来到了钟楼...."),AlbumSugDo(2, 10000, "今天六号线避雷", "前俯后仰。他就一直在那前后动。他背后是我朋友,我让他不要挤了,他直接就急了,开始故意很大力的挤来挤去。"),AlbumSugDo(3, 10000, "字节跳动快上车~", "#内推 #字节跳动内推 #互联网"),AlbumSugDo(4, 10000, "连王思聪也变得低调老实了", "如今的王思聪,不仅交女友的质量下降,在网上也不再像以前那样随意喷这喷那。显然,资金的紧张让他低调了许多")))}@Testfun suggestTest() {//模拟客户端输入的需要自动补全的字段val input = "今天"val limit = 10val fieldSuggester = FieldSuggester.Builder().text(input) //用户输入.completion(FieldSuggesterBuilders.completion().field("suggestion") //对哪个字段自动补全.skipDuplicates(true) //如果有重复的词条,自动跳过.size(limit) //最多显示 limit 条数据.build()).build()val query = NativeQuery.builder().withSuggester(Suggester.of { s -> s.suggesters("sug1", fieldSuggester) }) //参数一: 自定义自动补全名.build()val hits = elasticsearchTemplate.search(query, AlbumSugDo::class.java)val suggestList = hits.suggest?.getSuggestion("sug1")?.entries?.get(0)?.options?.map(::map) ?: emptyList()println(suggestList)}private fun map(hit: Suggest.Suggestion.Entry.Option): String {return hit.text}}

上述代码中的 hits 结构如下:

运行结果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/701466.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

鸿蒙开发之跨设备文件访问

分布式文件系统为应用提供了跨设备文件访问的能力&#xff0c;开发者在多个设备安装同一应用时&#xff0c;通过基础文件接口&#xff0c;可跨设备读写其他设备该应用分布式文件路径&#xff08;/data/storage/el2/distributedfiles/&#xff09;下的文件。 例如&#xff1a;多…

一文读懂通用漏洞评分系统CVSS4.0:顺带理清CVE、CWE及其与CVSS之间的关系

事件响应和安全团队论坛 (FIRST&#xff0c;Forum of Incident Response and Security Teams) 于 2023 年 11 月 1 日正式推出第四版通用漏洞评分系统 (CVSS 4.0&#xff0c;Common Vulnerability Scoring System version 4.0)。CVSS 4.0 是评估计算机系统安全漏洞严重性的行业…

申请免费的必应搜索API

申请免费的必应搜索API 文章目录 申请免费的必应搜索API前言一、原理1.1 登录1.2 进入1.3 获取密钥1.4 申请VISA信用卡1.5 创建必应自定义搜索资源 二、创建成功 前言 准备条件&#xff1a; 1、outlook邮箱 2、招商银行全币种VISA信用卡【建议之前就有一张招商银行信用卡&…

服务器通的远程桌面连接不上,关于服务器通畅但远程桌面连接不上问题的专业分析

在日常的企业IT管理中&#xff0c;服务器远程桌面连接是一个重要的操作功能。然而&#xff0c;有时会出现服务器网络通畅&#xff0c;但远程桌面无法连接的情况。 问题分析 1. 防火墙或安全组设置问题&#xff1a;服务器的防火墙或安全组可能阻止了远程桌面连接的端口&#xf…

QCC30xx 开发板如何测试待机电流

高通的通用蓝牙开发板底CF376上&#xff0c;有各种各样的外围电路与芯片&#xff0c;组成一整套完整的开发板平台&#xff0c;但客户通常只关心其中蓝牙芯片的各个状态下的工作电流&#xff0c;本文就介绍如何在CF376底板上&#xff0c;通过断开其它非必要电路 &#xff0c;去测…

LeetCode2215找出两数组的不同

题目描述 给你两个下标从 0 开始的整数数组 nums1 和 nums2 &#xff0c;请你返回一个长度为 2 的列表 answer &#xff0c;其中&#xff1a;answer[0] 是 nums1 中所有 不 存在于 nums2 中的 不同 整数组成的列表。answer[1] 是 nums2 中所有 不 存在于 nums1 中的 不同 整数组…

Linux的进程间通信 管道 进程池

目录 前言 进程间通信的基本概念 管道 匿名管道 pipe函数 cfc 管道的四种情况 管道的五种特征 进程池 ProcessPool.cpp&#xff1a; Task.cpp&#xff1a; 前言 ubuntu系统的默认用户名不为root的解决方案&#xff08;但是不建议&#xff09;&#xff1a;轻量应用服…

linux 网络管理 实验

目录 网络管理主机名管理网络管理 网络管理 主机名管理 执行如下命令查看主机名。 [rootopenEuler ~]# hostname openEuler [rootopenEuler ~]# cat /etc/hostname #这个文件是主机名的配置文件 openEuler执行如下命令临时修改主机名。 [rootopenEuler ~]# hostname huawe…

JVM从1%到99%【精选】-运行时数据区

目录 1.总览运行时数据区 2.内存溢出 3. 程序计数器 4.虚拟机栈 5.本地方法栈 6.堆 7.方法区 8.直接内存 1.总览运行时数据区 Java虚拟机在运行Java程序过程中管理的内存区域,称之为运行时数据区。运行时数据区可以分为方法区、堆、虚拟机栈、本地方法栈、程序计数器…

传输文件协议FTP与LFTP

目录 一.简介 二. FTP基础 主动模式&#xff08;Active Mode&#xff09;&#xff1a; 被动模式&#xff08;Passive Mode&#xff09;&#xff1a; 三. Vsftp 服务器简介 四. Vsftpd配置 1. 安装vsftpd&#xff08;ftp服务端&#xff09; 2.编辑配置文件 &#xff08;…

导航app为什么知道还有几秒变绿灯?

在使用地图导航app行驶至信号灯的交叉路口时&#xff0c;这些应用程序会贴心地告知用户距信号灯变化还有多少秒&#xff0c;无论是即将转为绿灯还是红灯。这一智能化提示不仅使得驾驶员能适时做好起步或刹车的准备&#xff0c;有效缓解了因等待时间不确定而产生的焦虑情绪&…

“Linux”的vi / vim目录编辑器

在前面中我们了解到Linux中的基础命令&#xff0c;20多个命令每个记住格式是&#xff1a;命令 选项 参数或者文件名&#xff0c;下面在了解一下最后两个命令&#xff1a;tree命令和find命令 一、补充的命令 &#xff08;1&#xff09;tree 作用&#xff1a;以竖状显示文件…