OpenSearch Spring Boot Starter 接入
OpenSearch Spring Boot Starter 1.1.1 接入:在 Spring Boot 3 中使用官方 OpenSearch Java Client 3.8,完成搜尋、計數、聚合與 typed keys,並附 33 個業務介面覆蓋表和完整範例。
在 Spring Boot 3 專案中引入 tengence-opensearch-spring-boot-starter 1.1.1,繼續使用官方 OpenSearch Java Client。Starter 負責設定用戶端連線、注入 API Key,並對用戶端版本所需的回應欄位做相容處理。
1.1.1 是唯讀接入。 支援搜尋、計數、聚合、高亮、欄位裁剪、排序和分頁;不支援寫入、刪除、索引管理、_msearch、scroll 和 PIT。
使用官方 Elasticsearch Java Client?請閱讀 Elasticsearch 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-opensearch-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
Gradle:
implementation 'com.tengence:tengence-opensearch-spring-boot-starter:1.1.1'
設定
Starter 讀取自己的 tengence.opensearch.* 設定,不使用 Spring Boot 的 spring.opensearch.*。URI 必須包含完整的 /v1/search 路徑。
tengence:
opensearch:
uris: https://api.tengence.com/v1/search
api-key: ${TENGENCE_OPENSEARCH_API_KEY}
connection-timeout: 5000
socket-timeout: 30000
compat:
normalize-search-response: true
在執行環境中注入 API Key,不要提交到倉庫:
export TENGENCE_OPENSEARCH_API_KEY="sk-..."
第一次搜尋
注入自動設定的 OpenSearchClient。業務程式碼只使用官方 OpenSearch 型別;下面的範例假定 Bean 名為 client,索引名為 tengence。
範例使用的匯入
import org.opensearch.client.opensearch.OpenSearchClient;
import org.opensearch.client.opensearch._types.FieldValue;
import org.opensearch.client.opensearch._types.SortOptions;
import org.opensearch.client.opensearch._types.SortOrder;
import org.opensearch.client.opensearch._types.query_dsl.Query;
import org.opensearch.client.opensearch.core.CountRequest;
import org.opensearch.client.opensearch.core.SearchRequest;
import org.opensearch.client.opensearch.core.SearchResponse;
import org.opensearch.client.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 直接透傳官方型別化請求,支援標準 OpenSearch 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
.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(org.opensearch.client.opensearch._types.query_dsl.FunctionBoostMode.Multiply)));
Query scriptFilter = Query.of(q -> q.script(sc -> sc.script(si -> si
.inline(i -> i
.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.inline(i -> i
.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_OPENSEARCH_API_KEY="sk-..."
mvn spring-boot:run
curl 'http://localhost:8080/demo/documents/count-all'
curl 'http://localhost:8080/demo/documents/search?keyword=sofa&page=1&size=10'
OpenSearch 範例監聽 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-hant/docs/tengence-search/spring-boot-starter/