Elasticsearch Spring Boot Starter 接入
Elasticsearch Spring Boot Starter 1.1.1 接入:在 Spring Boot 3 中使用官方 Elasticsearch Java Client 8.18,完成搜索、计数、聚合与 typed keys,并附 33 个业务接口覆盖表和完整示例。
在 Spring Boot 3 项目中引入 tengence-elasticsearch-spring-boot-starter 1.1.1,继续使用官方 Elasticsearch Java Client。Starter 负责配置客户端连接、注入 API Key,并对客户端版本所需的响应字段做兼容处理。
1.1.1 是只读接入。 支持搜索、计数、聚合、高亮、字段裁剪、排序和分页;不支持写入、删除、索引管理、_msearch、scroll 和 PIT。
使用官方 OpenSearch Java Client?请阅读 OpenSearch Spring Boot Starter 接入。
能力范围
| 能力 | 状态 | 说明 |
|---|---|---|
_search |
支持 | 全文、词项、复合和脚本查询 |
_count |
支持 | query 可选;不传时统计全部文档 |
| 聚合 | 支持 | terms、stats;支持 post_filter |
_source、高亮、排序 |
支持 | 标准请求字段直接透传 |
track_total_hits、search_after |
支持 | 用于精确总数和深分页 |
_msearch、scroll、PIT |
不支持 | 每个查询单独发一次请求 |
| 索引和文档写入 | 不支持 | 仅支持搜索与计数,不支持写入 |
URI q 参数 |
不支持 | Starter 会在发送前抛出 IllegalArgumentException,查询必须写在请求体中 |
1.1.1 的变化
1.1.1 移除了 1.1.0 文档中的限制。现在 count 可以不传 query,直接统计全部文档;match_all、exists、聚合和 size: 0 均已支持。Starter 会在搜索请求中设置 typed_keys=true,确保官方客户端能反序列化带类型的聚合键。
前置条件
- Java 17 及以上。
- Spring Boot 3.2 及以上。
- 已创建通智搜索应用并获取 API Key。
- 已为该应用绑定索引。示例使用
tengence。
安装
Maven:
<dependency>
<groupId>com.tengence</groupId>
<artifactId>tengence-elasticsearch-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
Gradle:
implementation 'com.tengence:tengence-elasticsearch-spring-boot-starter:1.1.1'
配置
Starter 读取自己的 tengence.elasticsearch.* 配置,不使用 Spring Boot 的 spring.elasticsearch.*。URI 必须包含完整的 /v1/search 路径。
tengence:
elasticsearch:
uris: https://api.tengence.com/v1/search
api-key: ${TENGENCE_ELASTICSEARCH_API_KEY}
connection-timeout: 5000
socket-timeout: 30000
compat:
normalize-search-response: true
在运行环境中注入 API Key,不要提交到仓库:
export TENGENCE_ELASTICSEARCH_API_KEY="sk-..."
第一次搜索
注入自动配置的 ElasticsearchClient。业务代码只使用官方 OpenSearch 类型;下面的示例假定 Bean 名为 client,索引名为 tengence。
示例使用的导入
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.CountRequest;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.json.JsonData;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.List;
public SearchResponse<JsonNode> firstSearch(String keyword) throws IOException {
return client.search(s -> s
.index("tengence")
.query(q -> q.match(m -> m
.field("title")
.query(FieldValue.of(keyword))))
.from(0)
.size(10), JsonNode.class);
}
带 query 与不带 query 的计数
1.1.1 两种写法都合法。未传 query 时会使用 match_all,不再需要为了计数而补一个空查询。
CountRequest allRequest = CountRequest.of(c -> c.index("tengence"));
long total = client.count(allRequest).count();
CountRequest matchedRequest = CountRequest.of(c -> c
.index("tengence")
.query(q -> q.match(m -> m
.field("title")
.query(FieldValue.of("sofa")))));
long matched = client.count(matchedRequest).count();
常用查询范式
Starter 直接透传官方类型化请求,支持标准 Elasticsearch DSL。下面的范式覆盖完整示例中使用的查询族;响应仍是正常的类型化 SearchResponse。
全文查询
用 multi_match 提高标题权重,match_phrase 匹配有序短语,match_phrase_prefix 做自动补全,fuzzy 容忍拼写错误。
Query fullText = Query.of(q -> q.bool(b -> b
.should(s -> s.multiMatch(mm -> mm
.fields("title^2", "description")
.query(keyword)))
.should(s -> s.matchPhrase(p -> p
.field("title").query("marble coffee table")))
.should(s -> s.matchPhrasePrefix(p -> p
.field("title").query("halo mar")))
.should(s -> s.prefix(p -> p
.field("title").value("halo")))
.should(s -> s.fuzzy(f -> f
.field("title")
.value(FieldValue.of("marbl"))
.fuzziness("1")))
.minimumShouldMatch("1"));
query_string 与 simple_query_string
query_string 支持字段限定和布尔表达式;面向用户输入时优先用 simple_query_string,语法异常不会直接抛错。
Query queryString = Query.of(q -> q.queryString(qs -> qs
.query("title:sofa OR description:marble")
.fields("title", "description")));
Query simpleQuery = Query.of(q -> q.simpleQueryString(qs -> qs
.query("sofa | marble")
.fields("title", "description")));
词项查询
词项查询不做分词,适合 ID、精确值、范围、存在性和模式匹配。
Query byIds = Query.of(q -> q.ids(i -> i
.values(List.of("AL-SOF-101", "AL-TBL-318"))));
Query byTerms = Query.of(q -> q.terms(t -> t
.field("item_id")
.terms(v -> v.value(List.of(
FieldValue.of("AL-SOF-101"),
FieldValue.of("AL-TBL-318"))))));
Query byRange = Query.of(q -> q.range(r -> r.untyped(u -> u
.field("item_id")
.gte(JsonData.of("AL-SOF-101")))));
Query withTitle = Query.of(q -> q.exists(e -> e.field("title")));
Query byWildcard = Query.of(q -> q.wildcard(w -> w
.field("title")
.value("halo*")));
Query byRegexp = Query.of(q -> q.regexp(r -> r
.field("title")
.value("halo.*")));
复合查询
bool.filter 不影响打分;dis_max 取匹配最好的子句,boosting 降低负向子句的权重,constant_score 让所有命中获得相同分数。
Query boolQuery = Query.of(q -> q.bool(b -> b
.should(s -> s.term(t -> t.field("item_id").value("AL-SOF-101")))
.should(s -> s.term(t -> t.field("item_id").value("AL-TBL-318")))
.minimumShouldMatch("1")
.filter(f -> f.term(t -> t.field("status").value("active")))));
Query disMax = Query.of(q -> q.disMax(d -> d.queries(List.of(
Query.of(qq -> qq.match(m -> m
.field("title").query(FieldValue.of("sofa"))),
Query.of(qq -> qq.match(m -> m
.field("description").query(FieldValue.of("sofa"))))));
Query boosting = Query.of(q -> q.boosting(b -> b
.positive(p -> p.matchAll(m -> m))
.negative(n -> n.term(t -> t.field("item_id").value("AL-TBL-318")))
.negativeBoost(0.1)));
Query constantScore = Query.of(q -> q.constantScore(cs -> cs
.filter(f -> f.term(t -> t.field("item_id").value("AL-TBL-318")))));
打分与脚本
function_score 用打分函数调整查询分数,示例使用 random_score;script 查询直接对字段求值。
Query recommend = Query.of(q -> q.functionScore(fs -> fs
.query(inner -> inner.match(m -> m
.field("title")
.query(FieldValue.of("sofa"))))
.functions(fn -> fn.randomScore(rs -> rs))
.boostMode(co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Multiply)));
Query scriptFilter = Query.of(q -> q.script(sc -> sc.script(si -> si
.source("doc['item_id'].value.length() >= params.min")
.params("min", JsonData.of(10)))));
分页、字段裁剪与高亮
浅分页用 from 和 size;深分页用稳定排序加 search_after。track_total_hits 返回精确总数,_source 过滤可减少响应体积。
SortOptions byId = SortOptions.of(so -> so
.field(f -> f.field("item_id").order(SortOrder.Asc)));
SearchRequest request = SearchRequest.of(s -> s
.index("tengence")
.query(q -> q.matchAll(m -> m))
.from(0)
.size(10)
.trackTotalHits(t -> t.enabled(true))
.source(sc -> sc.filter(f -> f.includes(List.of("title", "item_id"))))
.highlight(h -> h.fields("title", f -> f))
.sort(List.of(byId))
.searchAfter(FieldValue.of("AL-CHR-204")));
聚合与计数
聚合可以带查询,也可以只做全量统计。Starter 会补 typed_keys=true,聚合键会变成 sterms#by_item、stats#item_length。post_filter 在聚合计算完成后再过滤命中。
SearchRequest facets = SearchRequest.of(s -> s
.index("tengence")
.query(q -> q.matchAll(m -> m))
.postFilter(pf -> pf.term(t -> t.field("item_id").value("AL-TBL-318")))
.aggregations("by_item", a -> a
.terms(t -> t.field("item_id").size(10)))
.aggregations("item_length", a -> a
.stats(st -> st.script(si -> si
.source("doc['item_id'].value.length()")))
.size(0));
long all = client.count(c -> c.index("tengence")).count();
SearchResponse<JsonNode> empty = client.search(s -> s
.index("tengence")
.size(0), JsonNode.class);
完整可运行示例
示例仓库是完整的 Spring Boot 应用,包含 33 个 /demo/documents/** 示例接口,不是只有 search 和 count 的演示。这些是示例应用的 Spring MVC 路由,不是 Elasticsearch/OpenSearch 原生 API;原生搜索与计数接口是 /{index}/_search 和 /{index}/_count。
项目结构
DocumentSearchController.java:HTTP 接口和请求参数DocumentSearchService.java:33 个接口的类型化查询构造DocumentSearchResult.java:裁剪后的响应结构DocumentHit.java:单条命中及 source、highlightapplication.yml:服务地址和 API Key
来源: DocumentSearchController.java · DocumentSearchService.java · DocumentSearchResult.java · DocumentHit.java
运行
启动应用后先调用 count-all:
export TENGENCE_ELASTICSEARCH_API_KEY="sk-..."
mvn spring-boot:run
curl 'http://localhost:8081/demo/documents/count-all'
curl 'http://localhost:8081/demo/documents/search?keyword=sofa&page=1&size=10'
Elasticsearch 示例监听 8080,Elasticsearch 示例监听 8081。
33 个接口覆盖表
以下路径是示例应用 /demo/documents 下的路由,不是 Elasticsearch/OpenSearch 原生接口。keyword、page、size 是代表性参数;控制器还接受过滤、排序和字段裁剪参数。
| 示例应用路径 | 查询 DSL | 演示内容 |
|---|---|---|
| 基础 | ||
/demo/documents/search |
bool + multi_match + filter + sort/highlight/facets |
布尔查询,含过滤、排序、高亮和聚合 |
/demo/documents/all |
match_all |
match_all,前 10 条 |
| 全文与文本匹配 | ||
/demo/documents/match |
match |
title 上的 match |
/demo/documents/phrase |
match_phrase |
title 上的 match_phrase |
/demo/documents/phrase-prefix |
match_phrase_prefix |
title 上的 match_phrase_prefix |
/demo/documents/autocomplete |
prefix |
title 上的 prefix |
/demo/documents/typo |
fuzzy |
单字符拼写错误的 fuzzy |
| 词项 | ||
/demo/documents/lookup/ids |
ids |
ids 批量查询 |
/demo/documents/lookup/terms |
terms |
item_id 上的 terms |
/demo/documents/range |
range |
item_id 上的 range |
/demo/documents/with-title |
exists |
title 的 exists |
/demo/documents/wildcard |
wildcard |
title 的 wildcard |
/demo/documents/regexp |
regexp |
title 的 regexp |
/demo/documents/query-string |
query_string |
跨标题和描述的 query_string |
/demo/documents/simple-query |
simple_query_string |
simple_query_string |
| 复合与打分 | ||
/demo/documents/filter |
term filter |
term 过滤加分页 |
/demo/documents/should |
bool.should |
带 minimum_should_match 的 bool.should |
/demo/documents/strict |
constant_score |
constant_score 过滤 |
/demo/documents/similar |
dis_max |
标题和描述上的 dis_max |
/demo/documents/boost |
boosting |
带负向子句的 boosting |
/demo/documents/recommend |
function_score |
random_score 的 function_score |
/demo/documents/script-filter |
script |
按 item_id 长度过滤的 script 查询 |
| 分页与展示 | ||
/demo/documents/page |
from / size |
from / size 分页 |
/demo/documents/empty |
size: 0 |
size: 0,hits 为空 |
/demo/documents/total |
track_total_hits |
track_total_hits: true |
/demo/documents/next |
search_after |
search_after 游标 |
/demo/documents/highlight |
highlight |
高亮 title |
| 聚合与计数 | ||
/demo/documents/facets |
terms + stats aggs |
terms 和 stats 聚合 |
/demo/documents/filtered-facets |
post_filter + aggs |
post_filter 加未过滤聚合 |
/demo/documents/export |
source include/exclude |
_source 包含 / 排除 |
/demo/documents/sort |
sort |
显式多字段排序 |
/demo/documents/count |
_count with query |
带 query 的 _count |
/demo/documents/count-all |
_count without query |
不带 query 的 _count(match_all) |
响应兼容
| 字段 | 行为 |
|---|---|
| 逻辑字段 | 查询、_source、高亮、排序和聚合都使用配置的逻辑字段名(如 title),服务内部自动映射到实际字段 |
title 取值 |
返回 value 字段中的原始文本,不是分词结果;响应中不会出现 title.tokens 或 title.value |
took、timed_out |
缺失时补 0 和 false |
hits.total |
数字总数规范为 value 和 relation |
aggregations |
搜索请求中设置 typed_keys=true |
| 错误响应 | 服务错误码映射为客户端异常 |
限制
| 项目 | 限制 |
|---|---|
| 多搜索 | 未暴露 _msearch,每个查询单独发请求 |
| Scroll 和 PIT | 不支持;深分页用 search_after |
| 写入 | 没有索引、更新、删除或批量接口 |
URI q |
不支持;Starter 会在发送前抛出异常,查询必须写在请求体中 |
| 结果窗口 | 过大的 from + size 会被拒绝,分页不宜过深 |
| 索引 | 必须使用 API Key 绑定的索引 |
took |
took 可能返回 0,不要当作延迟指标 |
生产建议
- API Key 放在密钥管理或环境变量中,并按应用独立分配。
took = 0是兼容值,不是真实延迟;延迟应在客户端或服务端测量。- 索引必须是 API Key 绑定的索引,不要访问物理索引。
- 不要依赖
_msearch,请拆成多次搜索请求。
错误
| 现象 | 原因 |
|---|---|
401 或 API_KEY_INVALID |
API Key 缺失、失效或错误 |
UnsupportedOperationException |
使用了 _msearch |
IllegalArgumentException |
搜索或计数请求使用了 q |
RECALL_SEARCH_FAILED |
DSL 非法、查询类型不支持或超出结果窗口 |
| 404 | 服务路径错误,需包含 /v1/search |
相关文档
参见 接入准备、API 参考,以及 GitHub 上的完整示例。
版权归通智云所有。欢迎在保留来源链接和本版权声明的前提下分享与引用;商业用途需获得许可。以线上页面为最新版本。
来源: https://www.tengence.com/zh-hans/docs/tengence-search/spring-boot-starter-elasticsearch/