Module ai.aws.opensearch
ballerinax/ai.aws.opensearch Ballerina library
Overview
Amazon OpenSearch Service is a managed search and
analytics engine that also supports k-NN (approximate nearest-neighbor) vector search. This
package provides two ai:VectorStore implementations backed by OpenSearch, so either can be used
anywhere the ballerina/ai RAG APIs expect a vector store:
ManagedDomainVectorStorefor a managed OpenSearch Service domainServerlessVectorStorefor both generations of OpenSearch Serverless (Classic and NextGen)
There is no ballerinax/opensearch connector this package wraps: it talks the OpenSearch REST
API directly over ballerina/http, signing every request with AWS Signature Version 4 via
ballerinax/aws.auth (or, on a managed
domain with fine-grained access control enabled, HTTP basic authentication against the internal
user database).
Key features
- Managed OpenSearch Service domains and both OpenSearch Serverless generations (Classic and NextGen), each with correct SigV4 signing, index-mapping, and delete semantics
- Dense, sparse and hybrid search, selected once at construction through a closed
SearchModeunion so a setting that does not apply to the chosen mode cannot be named at all - Automatic index creation with the right mapping for the mode —
knn_vector,rank_features, or both — opt-out-able for least-privilege deployments - Full metadata filtering (
==,!=,>,>=,<,<=,in,nin, nestedAND/OR) translated to native OpenSearchboolqueries, pre-filtered inside theknnclause (Faiss and Lucene; OpenSearch rejects aknnfilter on annmslibindex) time:Utcmetadata round-trips through RFC 3339 strings;fileSizeround-trips throughdecimal- Exponential-backoff retry on transient failures, and explicit parsing of
_bulk's per-item partial-failure responses (OpenSearch returns HTTP 200 even when individual items fail) - GraalVM-compatible
Search modes
The searchMode argument decides the index mapping, which ai:Embedding member add and query
accept, and how results are scored. The match is checked in both directions: a store built for one
mode and handed another's embedding fails rather than writing a field no query reads.
| Mode | Embedding | Index field | Query clause | similarityScore range |
|---|---|---|---|---|
DenseSearch | ai:Vector | knn_vector | knn | [-1, 1] cosine by default; otherwise space-dependent |
SparseSearch | ai:SparseVector | rank_features | neural_sparse | unbounded positive dot product |
HybridSearch | ai:HybridVector | both | hybrid + fusion pipeline | (0.0, 1.0] normalized, or (0, 0.033] under RRF |
// Sparse: no dimension, no similarity metric, no HNSW tuning -- a rank_features index has none. searchMode = {queryMode: ai:SPARSE} // Hybrid: both vector fields, and how their scores are fused. searchMode = { queryMode: ai:HYBRID, indexConfig: {dimension: 1536}, fusion: {denseWeight: 0.3, sparseWeight: 0.7} }
Sparse vectors are precomputed by the caller: an ai:SparseVector's indices become
rank_features token names and its values become the weights, sent as-is. No ML model, ingest
pipeline or index.knn setting is involved, and nothing needs to be deployed server-side.
[!IMPORTANT]
SPARSEandHYBRIDneed theneural-searchplugin. It ships in the standard OpenSearch distribution and is present on AWS managed domains from 2.9; raw sparsequery_tokensadditionally need 2.14+, and thehybridquery needs 2.11+. AWS documentsneural_sparseandhybridfor Serverless without distinguishing collection generation, so both are permitted on every deployment type here — but neither has been verified against a real Serverless collection, and a Classic vector search collection may yet reject arank_featuresmapping.On OpenSearch Serverless, neural search is additionally limited to a subset of AWS regions rather than everywhere Serverless runs. In an unsupported region the collection is created normally and only the search fails, with nothing in the error naming the region as the cause. Check the "Supported AWS Regions" list on AWS's Configure neural search and hybrid search on OpenSearch Serverless page before choosing
SPARSEorHYBRIDon Serverless.
[!NOTE]
SPARSEandHYBRIDneed a sparse encoder you supply.ai:VectorRetrieveris not the obstacle — it forwards whateverEmbeddingProvider.embed()returns without narrowing it, and that method's return type is alreadyai:Embedding, the fullVector|SparseVector|HybridVectorunion. What is missing is an implementation: every shipped provider (WSO2, OpenAI, Azure, Vertex, OpenRouter) wraps a/embeddingsendpoint and returns dense vectors. Supply your own provider around a SPLADE-class encoder — it is a two-method interface — or calladd/querydirectly, which is what the hybrid example does.ai.pineconeandai.pgvectorship sparse support under the same condition.
Hybrid score fusion
A hybrid query needs a normalization search pipeline; without one OpenSearch does not fail, it
leaks large negative sentinel scores into the results. This module sends the pipeline inline in
the request body on every query and provisions nothing:
- fusion weights are query-time semantics, so binding them to durable cluster state would leave them silently stale the moment you retuned one;
- an OpenSearch Serverless search pipeline is a collection-scoped resource, so provisioning
would require
aoss:CreateCollectionItemson top of this module's index-scoped needs; - it sidesteps AWS's documented up-to-15-second Serverless pipeline propagation delay.
HybridSearchConfig exposes normalization (MIN_MAX, L2), combination (ARITHMETIC_MEAN,
GEOMETRIC_MEAN, HARMONIC_MEAN) and the two weights, which must be set together, each in
[0.0, 1.0], summing to 1.0. All of them are optional: an unset one is left out of the processor,
so OpenSearch's default applies (min_max, arithmetic_mean, equal weights). The default
fusion: {} therefore sends the processor with no settings.
Reciprocal rank fusion is the alternative, and is worth reaching for here: it combines the sub-queries by the rank each document reached rather than by its score, so a bounded cosine score and an unbounded sparse dot product never have to be put on a shared scale at all. It needs OpenSearch 2.19+, and it discards score magnitude — a document that won by a wide margin contributes exactly what one that barely won contributes.
fusion = {technique: RRF}
RrfFusion carries no other settings, deliberately. The score-ranker-processor documents a
rank_constant and a weights array, and neither has a wire shape that behaves consistently
across the versions this floor admits: neural-search reads rank_constant from
combination.parameters through 3.0 and from combination itself from 3.1, where the old location
became a hard error; and weights is accepted by every version but honored by none before 3.1.
Use HybridSearchConfig when the sub-queries must be weighted unequally — it takes weights
everywhere and honors them everywhere.
To use a pipeline already on the cluster instead — for a least-privilege deployment, or to share one tuned pipeline — name it:
fusion = {name: "my-hybrid-pipeline"}
Those are separate union members, not extra fields, so naming a pipeline and setting the inline knobs is not expressible: OpenSearch rejects a request carrying both forms.
Whichever you pick, a fused _score is never negative. A hybrid query whose pipeline carried no
fusion processor does not fail — OpenSearch's negative sub-query delimiter scores survive into the
results — so query rejects such a score with an error naming the fusion source rather than
returning a corrupted ranking as though it were a real one.
Accelerating sparse queries
By default a neural_sparse query scores every matching document against every one of its query
tokens. SparseSearch.twoPhaseAcceleration opts into OpenSearch's
neural_sparse_two_phase_processor (2.15+), sent inline like the fusion pipeline: the
high-weight tokens select a candidate set and the low-weight ones rescore only those.
searchMode = {queryMode: ai:SPARSE, twoPhaseAcceleration: {}}
{} sends the processor with no parameters, so OpenSearch's defaults apply (prune_ratio 0.4).
Set pruneRatio to override it.
It is unset by default because it raises the version floor, and it is reachable from SPARSE alone
— the processor rewrites neural_sparse clauses at the top level or under a bool's should, and
does not descend into a hybrid query, where it would be accepted and then quietly do nothing. A
filtered query keeps the clause under should for that reason.
The processor rescores a window of size × 5 documents and fails past 10,000, its defaults. So a
query asking for more than 2,000 results, including "all", runs without acceleration: exact, only
slower.
Prerequisites
1. Create an OpenSearch deployment
Choose one of:
- Managed domain — an OpenSearch Service domain,
endpoint shaped like
https://<domain>.<region>.es.amazonaws.com. - Serverless Classic — an OpenSearch Serverless vector search collection,
endpoint shaped like
https://<collection-id>.<region>.aoss.amazonaws.com. - Serverless NextGen — the current default generation for new Serverless vector collections,
endpoint shaped like
https://<collection-id>.aoss.<region>.on.aws(per-collection) orhttps://<account-id>.aoss.<region>.on.aws(per-account, see Collection endpoints).
The two Serverless generations behave differently at the data-plane level (custom document _id
support, refresh interval, and whether the search response includes the vector by default), and
AWS does not expose a way to detect which generation a collection is from the data plane — you
must tell ServerlessVectorStore which one you have via generation.
2. Obtain credentials
For a managed domain or Serverless (SigV4), the module authenticates via any AWS credential
source supported by ballerinax/aws.auth: static keys, a named profile, an assumed role, web
identity federation, IAM Identity Center (SSO), or DEFAULT_CREDENTIALS (the standard AWS
credential provider chain — environment, shared config, EC2/ECS instance role, and so on).
DEFAULT_CREDENTIALS is the recommended choice in production.
For a managed domain with fine-grained access control and the internal user database enabled,
you may instead use BasicAuth (username/password). Serverless has no basic-auth path — a
domain access policy that accepts IAM principals requires SigV4-signed requests, so you cannot
mix a username/password with IAM credentials on the same request
(AWS: fine-grained access control).
3. Grant the required IAM permissions
Managed domain — a domain access policy granting es:ESHttp* on the domain ARN:
{ "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::<account-id>:root"}, "Action": "es:ESHttp*", "Resource": "arn:aws:es:<region>:<account-id>:domain/<domain>/*" }
Serverless — a data access policy granting at least:
[ { "Rules": [ { "ResourceType": "index", "Resource": ["index/<collection>/<index>"], "Permission": ["aoss:CreateIndex", "aoss:DescribeIndex", "aoss:WriteDocument", "aoss:ReadDocument"] } ], "Principal": ["arn:aws:iam::<account-id>:role/<your-role>"] } ]
Drop aoss:CreateIndex if you pass createIndexIfNotExists = false to init and manage the index
yourself.
Quickstart
Step 1: Import the module
import ballerinax/ai.aws.opensearch;
Step 2: Initialize the vector store
Pick the class for your deployment. For a managed domain:
import ballerina/ai; import ballerinax/ai.aws.opensearch; import ballerinax/aws.auth; opensearch:ManagedDomainVectorStore vectorStore = check new ( serviceUrl = "https://search-my-domain-abc123.us-east-1.es.amazonaws.com", region = "us-east-1", indexName = "my-knowledge-base", auth = auth:DEFAULT_CREDENTIALS, searchMode = {queryMode: ai:DENSE, indexConfig: {dimension: 1536}} );
The managed-only settings, the engine and a forced refresh, go in storeConfig alongside the
shared ones, and auth also accepts basic auth:
opensearch:ManagedDomainVectorStore vectorStore = check new ( serviceUrl, region, indexName, auth = {username: "...", password: "..."}, searchMode = {queryMode: ai:DENSE, indexConfig: {dimension: 1536}}, storeConfig = {engine: opensearch:LUCENE, refreshOnWrite: true} );
For a Serverless collection, deployment selects the generation, and each variant exposes only the
settings that generation honors, so a setting that does not apply cannot be named at all:
// Serverless Classic: nothing to tune. Faiss is the sole engine it supports, and its refresh // interval is fixed, so neither is a choice. opensearch:ServerlessVectorStore vectorStore = check new ( serviceUrl = "https://abc123.us-east-1.aoss.amazonaws.com", region = "us-east-1", indexName = "my-knowledge-base", auth = auth:DEFAULT_CREDENTIALS, deployment = {generation: opensearch:CLASSIC}, searchMode = {queryMode: ai:DENSE, indexConfig: {dimension: 1536}} ); // Serverless NextGen: the only generation exposing vector quantization. deployment = { generation: opensearch:NEXTGEN, collection: {name: "my-collection"}, // or {id: "..."}; needed on a per-account endpoint compressionLevel: opensearch:COMPRESSION_1X }
auth is required on both stores. It is deliberately not defaulted to
auth:DEFAULT_CREDENTIALS: a store that silently picks up the ambient AWS credential chain hides a
misconfiguration until it surfaces as a 403 from a principal nobody intended to use. Pass
auth:DEFAULT_CREDENTIALS to opt into that chain explicitly.
Settings honored identically on every deployment are split by whether they depend on the kind of
search being performed. The index shape and the vector field names live on searchMode
(dimension, similarityMetric, efConstruction, m, vectorFieldName); the rest — the other
field names, bulk sizing, retries — live on storeConfig. Switching between the two stores carries
both across untouched.
indexName names one index or alias. init rejects what OpenSearch does not accept as one,
including a pattern or list such as logs-* or a,b.
By default (createIndexIfNotExists = true, an init parameter), init creates the index with the
correct mapping if it does not already exist. Pass false to have init fail on a missing or
mistyped index name instead of creating an empty index.
Step 3: Add, query, and delete vector entries
check vectorStore.add([ { id: "doc-1", embedding: [0.12, 0.98, ...], chunk: {'type: "text-chunk", content: "Ballerina is a cloud-native programming language.", metadata: {"language": "en"}} } ]); ai:VectorMatch[] results = check vectorStore.query({ embedding: [0.11, 0.97, ...], topK: 5, filters: {filters: [{key: "language", operator: ai:EQUAL, value: "en"}]} }); check vectorStore.delete("doc-1");
vectorStore satisfies ai:VectorStore, so it plugs directly into ai:KnowledgeBase and any
other ballerina/ai API that accepts a vector store.
Configuration
Deployment types and their behavioral differences
| Managed domain | Serverless Classic | Serverless NextGen | |
|---|---|---|---|
| Class | ManagedDomainVectorStore | ServerlessVectorStore | ServerlessVectorStore |
| SigV4 signing name | es | aoss | aoss |
BasicAuth allowed | yes | no | no |
add semantics | upsert | append-only | upsert |
delete | single _bulk call | search-then-bulk-delete | single _bulk call |
| Write visibility | immediate with refreshOnWrite, else normal refresh | ~60 s, unforceable | ~10 s, unforceable |
| Index mapping | method block with engine configurable | method block, forced faiss | method block without engine; space_type at the field's top level |
HNSW tuning (efConstruction/m) | yes | yes | yes |
| Vector quantization | no | no | yes |
On Serverless Classic, a custom document _id cannot be written, so re-adding the same
logical id creates a duplicate document rather than upserting, and delete must first search for
the internal _ids carrying that logical id (via the doc_id field this module always writes)
before it can delete them. A document added less than the collection's refresh interval ago will
not be found by that search and will survive the delete — this is a real limitation of the
platform, not a bug in this module.
[!NOTE] On Serverless Classic, a successful
initdoes not mean the index can be queried yet. Wheninitcreates the index,_mappingand_settingsreport it as present immediately while_search/_countagainst it still fail withindex_not_found_exceptionfor roughly ten seconds. It is a propagation delay, not a missing shard: the index becomes searchable on its own with no write and no intervention. Writes are unaffected and succeed immediately, so code thatadds before it queries never sees this.initdeliberately does not wait the delay out, which would add up to ten seconds to every Classic construction including the callers who write first; if you must query straight after constructing the store, retry anindex_not_found_exceptionfor a few seconds before treating it as fatal. Serverless NextGen is searchable at once.
Authentication
// Static keys auth = {accessKeyId: "...", secretAccessKey: "..."} // The standard AWS credential chain (recommended) auth = auth:DEFAULT_CREDENTIALS // HTTP basic auth — requires FGAC + an internal user database and an `https://` service URL, // and is accepted only by `ManagedDomainVectorStore`. `ServerlessVectorStore`'s `auth` does not admit this type. auth = {username: "...", password: "..."}
On both stores, auth is an init parameter of its own, right after indexName.
Index configuration (IndexConfig)
| Field | Default | Notes |
|---|---|---|
dimension | (required) | 1 to 16,000, OpenSearch's documented maximum; init rejects anything outside it. AWS also documents 10,000 in places, so a lower limit is left to the server |
similarityMetric | ai:COSINE | Maps to OpenSearch space_type: COSINE→cosinesimil, EUCLIDEAN→l2, DOT_PRODUCT→innerproduct. Always sent; OpenSearch's own default would be l2 |
efConstruction | (unset) | HNSW build-time accuracy/speed trade-off. Sent only when set; unset leaves OpenSearch's default (100, or 512 on 2.11). Honored on all three deployment types |
m | (unset) | HNSW max bi-directional links per node. Sent only when set; unset leaves OpenSearch's default (16). Honored on all three deployment types |
engine and compressionLevel are not here: they live where only the deployment that honors
them can set them (ManagedDomainStoreConfiguration.engine and
ServerlessNextGenDeployment.compressionLevel), so naming one against a deployment that ignores it
does not compile.
[!WARNING]
createIndexIfNotExists = falseneeds an index provisioned out of band.initthen fails on a missing index rather than construct a store over it. Without that check, a missing index would not makeaddfail — OpenSearch ships withaction.auto_create_index: true, so the first_bulkwrite would create an index from the document's inferred shape, with noindex.knnsetting and the vector mapped as a plainfloatarray, after which everyqueryfails with a400. If the calling principal may not read/<index>/_mapping, the check cannot run andinitonly logs a warning, so grant that permission alongside this setting.
[!NOTE] Vectors are quantized by default on Serverless NextGen. NextGen auto-configures the
knn_vectorfield, and what it configures ison_diskstorage with32xcompression — the same index created on a managed domain stores full-precision vectors. Nothing in the request or the response announces this; the stored mapping is the only place it shows up. To store vectors uncompressed, setcompressionLevel: COMPRESSION_1X; NextGen moves the field offon_diskitself to honor it. Leaving it unset preserves the platform default rather than substituting one of this module's own.
compressionLevelis declared onServerlessNextGenDeploymentalone, so it is simply not expressible against a managed domain or a Classic collection. Its companionmodeparameter is not exposed at all: the AOSS proxy rejects every value of it withField parameter 'mode' is not supported, and NextGen is the only flavour that could have carried it.CompressionLevellikewise offers no4x— NextGen names its own accepted set as[, 1x, 2x, 8x, 16x, 32x], and4xis a Lucene-only ratio that Faiss refuses, so it is unusable everywhere this module builds a mapping.
[!WARNING] Index-shape settings apply only when the index is created.
dimension,similarityMetric,efConstruction,m,engineandcompressionLevelare sent in exactly one request — thePUT /<index>thatinitissues when the index does not yet exist. After that,initsees the index and returns without building a mapping, so editing them changes nothing on the index.On an existing index,
initcomparesdimensionandsimilarityMetricagainst the stored mapping and fails on a mismatch, unless the mapping cannot be read. None of the other settings is checked, so editing them has no effect and produces no error. Nothing in a later request restates them: a_bulkdocument carries a vector, and aknnquery carries a vector andk. Neither mentionsengine,m,ef_constructionorcompression_level, so the server has nothing to disagree with. AcompressionLevelset to opt out of NextGen's default quantization leaves the vectors quantized.To change the shape of an existing index, reindex into a new one. This module does not update mappings.
IndexConfig is reachable only from DenseSearch and HybridSearch. A SparseSearch maps no
knn_vector field, so none of these settings exist there rather than being ignored.
Other configuration (StoreConfiguration)
| Field | Default | Notes |
|---|---|---|
contentFieldName | "content" | |
idFieldName | "doc_id" | The field carrying the logical entry id; always written, and the only identity handle on Serverless Classic |
metadataFieldName | "metadata" | Set to "" to address bare <key> paths — for pointing this module at a pre-existing index with a flat schema. A metadata key that would then collide with a reserved field name (embedding, sparse_embedding, content, doc_id, chunk_type) is rejected with an ai:Error rather than silently overwriting that field. When this module creates the index, "" also maps every string field it does not map itself as keyword: those fields match exactly only, and values over 8,191 characters are not indexed |
includeEmbeddingsInResults | false | Whether a query result carries the stored vector. Off by default, so every vector field the mode declares is excluded from _source — a meaningful bandwidth saving at high dimensions and large topK, and a larger one under SPARSE/HYBRID. Set true when the caller needs the vectors back |
maxBulkSize | 500 | Entries per _bulk request; add and delete split larger calls. It counts entries, not bytes: lower it if large entries make a request exceed the endpoint's payload limit (a 413) |
maxResultWindow | 10000 | The size used when topK < 1 ("return all"), and the ceiling enforced on an explicit topK. At least 2 on Serverless Classic, where delete looks ids up first. A query with an embedding also asks for at most 10,000 neighbours, OpenSearch's knn limit |
retryConfig | exponential backoff, 3 retries | Values must not be negative, and backoffFactor must be at least 1. Applied to 429/408/5xx responses, and to add items a _bulk response rejects with 429, which are re-sent on their own. Each attempt is signed afresh. On Serverless Classic, a failed indexing request is never retried, since it may have been partly applied and a replay appends duplicates; items it rejects with 429 were not applied and are re-sent. httpConfig.retryConfig is ignored, so retries are set only here |
vectorFieldName, normalizeCosineScore and efSearch are not here: they live on the
SearchMode variant that honors them, alongside sparseVectorFieldName, maxQueryTokens,
twoPhaseAcceleration and fusion. All the configurable
field names must be distinct from each other and from the fixed chunk_type; a collision is
rejected at construction rather than silently producing an index where one field overwrites
another.
httpConfig takes any http:ClientConfiguration, but four of its settings are always overridden:
httpVersion and http1Settings.chunking (SigV4 needs HTTP/1.1 and an unchunked body),
retryConfig (the store retries itself, above) and auth (credentials come only from auth).
Construction-time verification
Nothing else in this module connects a store's configuration to the index it is pointed at, and
every way of being wrong is silent: a SPARSE store aimed at a dense index writes successfully
forever and fails every query with a bare 400; a renamed vectorFieldName reads a field that is
not there and returns nothing; a dimension that drifted stays wrong until the embeddings
themselves change length. So init always makes two reads:
GET /for the cluster's OpenSearch version, compared against the floors this store's configuration actually needs — 2.11 forhybrid, 2.14 for rawquery_tokens, 2.15 fortwoPhaseAcceleration, 2.16 forefSearch, 2.19 forRrfFusion. Wheninitis about to create the index, it also checks theknn_vectormapping it will send: 2.19 for theFAISSengine withCOSINE, 2.13 forLUCENEwithDOT_PRODUCT, and 2.2 forLUCENEat all. An existing index is not held to these, since it may use a different engine. Skipped on both Serverless generations, which do not answerGET /.GET /<index>/_mappingfor the vector field(s) the mode declares — that each exists, is the expected type (knn_vector/rank_features), and carries the configureddimension. Aknn_vectorfield that declares aspace_typemust also matchsimilarityMetric; one that declares none gets a warning, since its space is set elsewhere. WithnormalizeCosineScoreon, annmslibcosine field needs OpenSearch 2.19 or later, checked with a furtherGET /: before 2.19, NMSLIB scores cosine as1 / (2 - cos), which the normalization cannot invert. Skipped wheninitjust created the index, which is correct by construction. Only the vector fields are checked; pointing this module at a pre-existing index whose content and metadata fields look different is supported.
A check that runs and disagrees is fatal — init returns an ai:Error naming the specific
mismatch. A check that cannot run, because the calling principal may not read / or
/<index>/_mapping, logs a warning and construction continues. A missing index is the one
exception and is an error, which is what turns createIndexIfNotExists: false from a hazard
discovered later into a failure at construction.
The cost is up to two extra round trips per store, and nothing per operation afterwards.
Tuning search-time recall (efSearch)
IndexConfig.efConstruction and .m are fixed when the index is created. efSearch is the
search-time counterpart — how many candidates the HNSW traversal examines before returning the top
k — and is sent with every query as method_parameters.ef_search, so changing it takes effect
immediately on an existing index. It needs OpenSearch 2.16+.
searchMode = {queryMode: ai:DENSE, indexConfig: {dimension: 1536}, efSearch: 512}
Leaving it unset omits method_parameters entirely and lets the index's own
index.knn.algo_param.ef_search apply, whose default is 100. AWS's own vector-store CDK construct
provisions collections with 512; measure rather than assume.
Similarity score range
This section describes DenseSearch only. A SPARSE score is an unbounded dot product and a
HYBRID score is already normalized to (0.0, 1.0] by the fusion pipeline — see the table under
"Search modes". normalizeCosineScore is not a field either of those modes declares, so the
conversion below cannot be applied to them.
Under ai:COSINE, VectorMatch.similarityScore is a true cosine in [-1, 1] — the same range
ai:InMemoryVectorStore returns, so a threshold tuned against one store means the same thing
against the other. That conversion (cos = 2 * score - 1) is what normalizeCosineScore = true
does, and it is the default for exactly that reason.
Set normalizeCosineScore = false to get OpenSearch's raw _score instead. Its range is
space-dependent: cosinesimil gives [0, 1], l2 gives (0, 1], and innerproduct is
piecewise. The setting applies only under ai:COSINE; the other metrics always pass through.
When a query has no embedding (a metadata-only filter, or neither embedding nor filters),
OpenSearch's constant score is not a similarity at all, so similarityScore is always 0.0 for
those matches regardless of this setting.
[!TIP] API guide — a walkthrough of every public type: what it is for, when you would touch it, and what it does on the wire.
Limitations
- A sparse
similarityScoreis not comparable to a dense one. It is an unbounded dot product, so a relevance threshold tuned against a dense store means nothing against a sparse one. An RRF-fused score is not comparable to a normalization-fused one either. topKdoubles as the retrieval depth underHYBRID. It becomes both the searchsizeand the dense sub-query'sk, sotopK: 10gives fusion exactly ten dense candidates. Hybrid relevance normally improves when each sub-query retrieves deeper than the final result count. There is no separate depth control: OpenSearch's lever is thehybridquery'spagination_depth, which is 2.19+ and would silently do nothing on the 2.11 floor this mode otherwise supports. Request a largertopKthan you intend to use and truncate the results yourself. For the same reason aHYBRIDquery with an embedding rejectstopKbelow 1: "all" would be amaxResultWindow-deep k-NN search fused with a full sparse scan.- Sparse weights round-trip lossily.
rank_featureskeeps roughly nine significant bits, so a returned weight carries about 0.4% relative error, and a returned sparse vector is always sorted by index ascending regardless of the order it was written in. Never compare one to a locally-held weight with exact float equality. - Sparse weights are bounded by Lucene. A stored weight must be finite and at least
Float.MIN_NORMAL— zero and negative weights cannot be indexed, so drop those terms rather than sending them. A query weight must additionally be in(0, 64]. Both are rejected before the request is sent rather than clamped, since clamping would silently rewrite your ranking. - A sparse query is capped at
maxQueryTokensterms (default 1024), becauseneural_sparsecompiles to one Lucene clause per term and the cluster'sindices.query.bool.max_clause_countbounds it. Prune the query vector to its highest-weighted terms, or raise both. A query vector with no terms is rejected: OpenSearch would match nothing, and underHYBRIDsilently return dense-only results. - Hybrid metadata filters are duplicated into each sub-query rather than sent as a top-level
hybrid.filter, which is OpenSearch 3.0+ only. The two are documented as equivalent. - Sparse and hybrid are unverified on OpenSearch Serverless. Both are exercised against OpenSearch 2.19.1 in the integration suite; AWS documents the underlying queries for Serverless but this module has not been run against a real collection.
topKabovemaxResultWindowis rejected; raisemaxResultWindow(and the index's ownindex.max_result_windowsetting) if you need more than 10,000 results.- A pre-existing index this module did not create must map
metadata.*(or, under a flat schema, every metadata field) askeyword, not the default analyzedtext— otherwise==andinfilters on string metadata will silently return zero hits. - Serverless Classic delete can fail loudly (rather than silently under-deleting) if a
single logical id has accumulated more duplicate documents than
maxResultWindowcan see in one lookup — raisemaxResultWindowand retry. - A Serverless Classic index is not searchable for ~10 s after
initcreates it, though it is writable immediately — see the note under "Deployment types" above. - Fractional metadata values change Ballerina type on a round trip. A custom metadata key
written as a
float({"rating": 4.25}) is read back as adecimal, because JSON has one number type and Ballerina's parser maps every non-integral value todecimal. The value is exact; only the basic type differs, soreadBack["rating"] == 4.25isfalse.fileSizeis the one numeric field restored to its declared type, becauseai:Metadatadeclares itdecimal. This matchesai.pinecone's behaviour, so metadata semantics stay identical when swapping vector stores behind theai:VectorStoreinterface.
Examples
The ai.aws.opensearch package provides practical examples illustrating real-world use.
- RAG search — indexes a handful of text chunks and answers a similarity query with a metadata filter.
- Hybrid search — indexes entries carrying both a dense and a sparse vector, and shows how the fusion weights decide which sub-query wins.
Import
import ballerinax/ai.aws.opensearch;Other versions
1.0.0