TengenceTengence
Product docs

OpenSearch Spring Boot Starter Integration

Add the Tengence OpenSearch Spring Boot starter 1.1.1 to Spring Boot 3: search, count, aggregations, typed keys, query patterns, and the 33-endpoint example.

Add tengence-opensearch-spring-boot-starter 1.1.1 to a Spring Boot 3 application and keep using the official OpenSearch Java client. The starter connects that client to Tengence Search, applies API-key authentication, and adapts response fields for client compatibility.

1.1.1 is read-only. Search, count, aggregations, highlighting, source projection, sorting and pagination are supported. Writes, deletes, index management, _msearch, scroll and PIT are not.

Using the official Elasticsearch Java client? See the Elasticsearch Spring Boot Starter guide.

Scope

Capability Status Notes
_search Supported Full-text, term-level, compound and script queries
_count Supported A query is optional; without one, all documents are counted
Aggregations Supported Terms and stats; post_filter is supported
_source, highlight, sort Supported Standard request fields are passed through
track_total_hits, search_after Supported Use these for exact totals and deep pagination
_msearch, scroll, PIT Not supported Use one request per query
Index and document writes Not supported Only search and count are available; writes are not supported
q URI parameter Not supported The starter rejects q before sending a request; put the query in the request body

 

What changed in 1.1.1

Version 1.1.1 removes the restrictions that appeared in the 1.1.0 guide. count without a query now counts all documents, and match_all, exists, aggregations and size: 0 are supported. The starter sets typed_keys=true on search requests, so the official clients can deserialize typed aggregation keys.

Prerequisites

  • Java 17 or later.
  • Spring Boot 3.2 or later.
  • A Tengence Search application and its API key.
  • The index bound to that application. The examples use tengence.

Install

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'

Configure

The starter reads its own tengence.opensearch.* properties. Do not use Spring Boot’s spring.opensearch.* properties. The URI must include the complete /v1/search path.

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

Export the key in the runtime environment; never commit it:

export TENGENCE_OPENSEARCH_API_KEY="sk-..."

Inject the auto-configured OpenSearchClient. The business code uses only official OpenSearch imports. The examples assume a bean named client and an index named tengence.

Imports used in the examples

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);
}

Count with and without a query

Both forms are valid in 1.1.1. When no query is supplied, match_all; you no longer need to add an empty query to make count work.

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();

Common query patterns

The starter passes the official typed request through. Standard OpenSearch DSL is accepted. The patterns below cover the query families used by the complete example. Responses arrive as the normal typed SearchResponse.

Full-text queries

Use multi_match to weight the title, match_phrase for ordered phrases, match_phrase_prefix for autocomplete, and fuzzy for typos.

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 and simple query string

query_string supports field-qualified expressions and boolean operators. simple_query_string is the safer choice for user-entered text because it does not throw on malformed syntax.

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")));

Term-level queries

Term-level queries skip analysis. Use them for IDs, exact field values, ranges, existence checks and pattern matching.

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.*")));

Compound queries

bool.filter does not affect scoring. dis_max takes the best matching clause, boosting downranks a negative clause, and constant_score gives every match the same 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")))));

Scoring and scripts

function_score adjusts the query score with a scoring function; the example uses random_score. A script query evaluates a field directly.

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))))));

Pagination, source and highlighting

Use from and size for shallow pages. For deep pagination use search_after with a stable sort. track_total_hits returns an exact total; source filtering reduces the payload.

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")));

Aggregations and counts

Aggregations work with or without a query. The starter adds typed_keys=true, so keys arrive as sterms#by_item and stats#item_length. post_filter filters hits after aggregations are computed.

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);

Complete runnable example

The example repository is a complete Spring Boot application with 33 /demo/documents/** example endpoints, not just a search and count demo. These are Spring MVC routes in the demo application, not Elasticsearch or OpenSearch native APIs; the native endpoints are /{index}/_search and /{index}/_count.

Project structure

  • DocumentSearchController.java — HTTP endpoints and request parameters
  • DocumentSearchService.java — typed query construction for all 33 endpoints
  • DocumentSearchResult.java — trimmed response envelope
  • DocumentHit.java — one hit with source and highlight
  • application.yml — service URL and API key

Source: DocumentSearchController.java · DocumentSearchService.java · DocumentSearchResult.java · DocumentHit.java

Run it

Start the application and query the count-all endpoint first:

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'

The OpenSearch example listens on port 8080. The Elasticsearch example uses 8081.

The 33 endpoints

All paths below are demo application routes under /demo/documents, not native Elasticsearch/OpenSearch endpoints. `keyword`, `page` and `size` are representative parameters; the controller also accepts filters, sort fields and source fields on the endpoints that use them.

Example app path Query DSL What it demonstrates
Basics
/demo/documents/search bool + multi_match + filter + sort/highlight/facets Bool query with filters, sorting, highlighting and facets
/demo/documents/all match_all match_all, first 10 hits
Full-text and text matching
/demo/documents/match match match on title
/demo/documents/phrase match_phrase match_phrase on title
/demo/documents/phrase-prefix match_phrase_prefix match_phrase_prefix on title
/demo/documents/autocomplete prefix prefix on title
/demo/documents/typo fuzzy fuzzy for a one-character typo
Term-level
/demo/documents/lookup/ids ids ids lookup
/demo/documents/lookup/terms terms terms on item_id
/demo/documents/range range range on item_id
/demo/documents/with-title exists exists on title
/demo/documents/wildcard wildcard wildcard on title
/demo/documents/regexp regexp regexp on title
/demo/documents/query-string query_string query_string across title and description
/demo/documents/simple-query simple_query_string simple_query_string
Compound and scoring
/demo/documents/filter term filter term filter with pagination
/demo/documents/should bool.should bool.should with minimum_should_match
/demo/documents/strict constant_score constant_score filter
/demo/documents/similar dis_max dis_max over title and description
/demo/documents/boost boosting boosting with a negative clause
/demo/documents/recommend function_score function_score with random_score
/demo/documents/script-filter script script query on item_id length
Pagination and presentation
/demo/documents/page from / size from / size pagination
/demo/documents/empty size: 0 size: 0, hits empty
/demo/documents/total track_total_hits track_total_hits: true
/demo/documents/next search_after search_after cursor
/demo/documents/highlight highlight Highlight title
Aggregations and counts
/demo/documents/facets terms + stats aggs terms and stats aggregations
/demo/documents/filtered-facets post_filter + aggs post_filter with unfiltered aggregations
/demo/documents/export source include/exclude _source includes / excludes
/demo/documents/sort sort Explicit multi-field sort
/demo/documents/count _count with query _count with a query
/demo/documents/count-all _count without query _count without a query (match_all)

 

Response adaptation

Field Behavior
Logical fields Use the configured field name (for example title) in queries, _source, highlight, sort and aggregations; the service maps it to the internal field
title value Returns the original text from the value field, never the tokenized form; do not expect title.tokens or title.value in responses
took, timed_out Filled with 0 and false when omitted
hits.total Numeric totals are normalized to value and relation
aggregations typed_keys=true is set on search requests
Error body Service error codes are mapped to the client exception

 

Limits

Item Limit
Multi-search _msearch is not exposed; issue one request per query
Scroll and PIT Not supported; use search_after for deep pagination
Writes No index, update, delete or bulk endpoints
URI q Not supported; the starter throws before sending, so use a request-body query
Result window Large from + size values are rejected; keep pages shallow
Index The index must be the one bound to the API key
took took may be 0; do not use it as a latency metric

 

Production notes

  • Keep API keys in a secret manager or environment variables, and use a separate key per application.
  • took = 0 is a compatibility value, not real latency; measure latency in your client or server.
  • The index must be the one bound to the API key; do not target physical indices.
  • Do not depend on _msearch; issue separate search requests.

Errors

Symptom Cause
401 or API_KEY_INVALID Missing, revoked or wrong API key
UnsupportedOperationException _msearch was used
IllegalArgumentException q was used on a search or count request
RECALL_SEARCH_FAILED Invalid DSL, unsupported query type, or result window exceeded
404 Wrong service path; include /v1/search

 

See Setup, API reference, and the complete example on GitHub.


Copyright belongs to Tengence Cloud. Sharing and quoting are welcome, provided the source link and this copyright notice are retained. Commercial use requires permission. The official page is the latest version.

Source: https://www.tengence.com/docs/tengence-search/spring-boot-starter/

On this page