SpringBoot3.x下如何使用es进行数据查询

文章目录

概要

SpringBoot3中的elasticsearch版本已经来到8.x版本,相比较于SpringBoot2中的7.x版本相关写法已经发生改变。在SpringBoot2中会使用ElasticsearchRestTemplate和es进行交互,但这个类在SpringBoot3中已经被移除,需要使用ElasticsearchTemplate或者ElasticsearchClient和es进行交互。下面介绍这两个类的基本使用方式。

ElasticsearchTemplate

java 复制代码
    @Test
    void test_1() {
        NativeQuery query = new NativeQueryBuilder()
                .withPageable(Pageable.ofSize(100))
                //使用lambda表达式使其更符合es语句的写法
                .withQuery(q -> q
                        .bool(b -> b
                                .filter(f -> f
                                        .term(t -> t
                                                .field("Name")
                                                .value("test")))))
                .withSort(s -> s
                        .field(f -> f
                                .field("Name")
                                .order(SortOrder.Desc)))
                .build();
        SearchHits<User> search = elasticsearchTemplate.search(query, User.class, IndexCoordinates.of("test-topic"));
        List<SearchHit<User>> searchHits = search.getSearchHits();
        for (SearchHit<User> searchHit : searchHits) {
            System.out.println(searchHit.getContent().getName());
        }
    }

以上的es查询语句等价于

json 复制代码
{
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "Name": {
                            "value": "test"
                        }
                    }
                }
            ]
        }
    },
    "from": 0,
    "size": 100,
    "sort": [
        {
            "Name": {
                "order": "desc"
            }
        }
    ]
}

ElasticsearchClient

java 复制代码
    @Test
    void test_2() throws IOException {
        Function<SearchRequest.Builder, ObjectBuilder<SearchRequest>> query = fn-> fn
                .index("test-topic")
                .size(100)
                //使用lambda表达式使其更符合es语句的写法
                .query(q -> q
                                .bool(b -> b
                                        .filter(f -> f
                                                .term(t -> t
                                                        .field("Name")
                                                        .value("test")))))
                .sort(s -> s
                        .field(f -> f
                                .field("Name")
                                .order(SortOrder.Desc)));
        SearchResponse<User> search = elasticsearchClient.search(query, User.class);
        List<Hit<User>> hits = search.hits().hits();
        for (Hit<User> hit : hits) {
            System.out.println(hit.source().getName());
        }
    }

小结

1.依赖引入

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2.ElasticsearchTemplate和ElasticsearchClient已经自动装配,业务类中直接注入即可。

3.User类

java 复制代码
    /**
     * test_1:使用第一种测试时,实体属性和es字段属性不对应时需要使用@Field(org.springframework.data.elasticsearch.annotations.Field)注解标识
     * test_2:使用第二种测试时,实体属性和es字段属性不对应时需要使用@JsonProperty(com.fasterxml.jackson.annotation.JsonProperty)注解标识
     */
    @Data
    public class User {

        @Id
        private String id;

        @Field("Name")
        @JsonProperty("Name")
        private String name;
    }
相关推荐
Elasticsearch4 小时前
训练量仅占 0.35%,竞争力却达到 100%:jina-embeddings-v5-omni 背后的冻结塔架构
elasticsearch
扶苏10028 小时前
同一个 Git 项目整出两份,切分支互不影响?两种方案实测
大数据·git·elasticsearch
Elasticsearch10 小时前
用两行 JSON 替换你的 ILM 策略:数据流生命周期新增冻结层支持
elasticsearch
AI大模型-小雄1 天前
Codex写分页接口为什么越翻越慢?用Cursor Pagination解决重复与漏数据
大数据·数据库·elasticsearch·搜索引擎·chatgpt·后端开发·codex
Elasticsearch1 天前
深入浅出 Elastic 工作流(Workflows):核心架构与十一大顶级字段详解
elasticsearch
Elasticsearch1 天前
在 Elasticsearch 中构建上下文:AI Indices 如何使用更少的 tokens 为更智能的 agent 提供支持
elasticsearch
淮北4941 天前
ubuntu22 默认输入法调整频率
运维·服务器·git·ubuntu·elasticsearch
Elasticsearch2 天前
Elasticsearch:使用 AI Agent 来创建 workflows
elasticsearch
gll7732 天前
RAG 检索层实战:Redis 缓存 + ES 混合检索 + BGE-Rerank 重排全链路落地与踩坑
elasticsearch
Elasticsearch2 天前
ES 存日志很贵?我用 ES 9.5 把日志从 4.5G 压到 412M 压缩比11.2倍,日志硬扫每秒128万行!
elasticsearch