ballerinax/ai.aws.opensearch Ballerina library

1.0.0

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:

  • ManagedDomainVectorStore for a managed OpenSearch Service domain
  • ServerlessVectorStore for 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 SearchMode union 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, nested AND/OR) translated to native OpenSearch bool queries, pre-filtered inside the knn clause (Faiss and Lucene; OpenSearch rejects a knn filter on an nmslib index)
  • time:Utc metadata round-trips through RFC 3339 strings; fileSize round-trips through decimal
  • 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.

ModeEmbeddingIndex fieldQuery clausesimilarityScore range
DenseSearchai:Vectorknn_vectorknn[-1, 1] cosine by default; otherwise space-dependent
SparseSearchai:SparseVectorrank_featuresneural_sparseunbounded positive dot product
HybridSearchai:HybridVectorbothhybrid + fusion pipeline(0.0, 1.0] normalized, or (0, 0.033] under RRF
Copy
// 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] SPARSE and HYBRID need the neural-search plugin. It ships in the standard OpenSearch distribution and is present on AWS managed domains from 2.9; raw sparse query_tokens additionally need 2.14+, and the hybrid query needs 2.11+. AWS documents neural_sparse and hybrid for 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 a rank_features mapping.

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 SPARSE or HYBRID on Serverless.

[!NOTE] SPARSE and HYBRID need a sparse encoder you supply. ai:VectorRetriever is not the obstacle — it forwards whatever EmbeddingProvider.embed() returns without narrowing it, and that method's return type is already ai:Embedding, the full Vector|SparseVector|HybridVector union. What is missing is an implementation: every shipped provider (WSO2, OpenAI, Azure, Vertex, OpenRouter) wraps a /embeddings endpoint and returns dense vectors. Supply your own provider around a SPLADE-class encoder — it is a two-method interface — or call add/query directly, which is what the hybrid example does. ai.pinecone and ai.pgvector ship 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:CreateCollectionItems on 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.

Copy
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:

Copy
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.

Copy
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) or https://<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:

Copy
{
  "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:

Copy
[
  {
    "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

Copy
import ballerinax/ai.aws.opensearch;

Step 2: Initialize the vector store

Pick the class for your deployment. For a managed domain:

Copy
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:

Copy
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:

Copy
// 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

Copy
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 domainServerless ClassicServerless NextGen
ClassManagedDomainVectorStoreServerlessVectorStoreServerlessVectorStore
SigV4 signing nameesaossaoss
BasicAuth allowedyesnono
add semanticsupsertappend-onlyupsert
deletesingle _bulk callsearch-then-bulk-deletesingle _bulk call
Write visibilityimmediate with refreshOnWrite, else normal refresh~60 s, unforceable~10 s, unforceable
Index mappingmethod block with engine configurablemethod block, forced faissmethod block without engine; space_type at the field's top level
HNSW tuning (efConstruction/m)yesyesyes
Vector quantizationnonoyes

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 init does not mean the index can be queried yet. When init creates the index, _mapping and _settings report it as present immediately while _search/_count against it still fail with index_not_found_exception for 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 that adds before it queries never sees this. init deliberately 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 an index_not_found_exception for a few seconds before treating it as fatal. Serverless NextGen is searchable at once.

Authentication

Copy
// 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)

FieldDefaultNotes
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
similarityMetricai:COSINEMaps 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 = false needs an index provisioned out of band. init then fails on a missing index rather than construct a store over it. Without that check, a missing index would not make add fail — OpenSearch ships with action.auto_create_index: true, so the first _bulk write would create an index from the document's inferred shape, with no index.knn setting and the vector mapped as a plain float array, after which every query fails with a 400. If the calling principal may not read /<index>/_mapping, the check cannot run and init only logs a warning, so grant that permission alongside this setting.

[!NOTE] Vectors are quantized by default on Serverless NextGen. NextGen auto-configures the knn_vector field, and what it configures is on_disk storage with 32x compression — 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, set compressionLevel: COMPRESSION_1X; NextGen moves the field off on_disk itself to honor it. Leaving it unset preserves the platform default rather than substituting one of this module's own.

compressionLevel is declared on ServerlessNextGenDeployment alone, so it is simply not expressible against a managed domain or a Classic collection. Its companion mode parameter is not exposed at all: the AOSS proxy rejects every value of it with Field parameter 'mode' is not supported, and NextGen is the only flavour that could have carried it. CompressionLevel likewise offers no 4x — NextGen names its own accepted set as [, 1x, 2x, 8x, 16x, 32x], and 4x is 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, engine and compressionLevel are sent in exactly one request — the PUT /<index> that init issues when the index does not yet exist. After that, init sees the index and returns without building a mapping, so editing them changes nothing on the index.

On an existing index, init compares dimension and similarityMetric against 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 _bulk document carries a vector, and a knn query carries a vector and k. Neither mentions engine, m, ef_construction or compression_level, so the server has nothing to disagree with. A compressionLevel set 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)

FieldDefaultNotes
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
includeEmbeddingsInResultsfalseWhether 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
maxBulkSize500Entries 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)
maxResultWindow10000The 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
retryConfigexponential backoff, 3 retriesValues 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:

  1. GET / for the cluster's OpenSearch version, compared against the floors this store's configuration actually needs — 2.11 for hybrid, 2.14 for raw query_tokens, 2.15 for twoPhaseAcceleration, 2.16 for efSearch, 2.19 for RrfFusion. When init is about to create the index, it also checks the knn_vector mapping it will send: 2.19 for the FAISS engine with COSINE, 2.13 for LUCENE with DOT_PRODUCT, and 2.2 for LUCENE at all. An existing index is not held to these, since it may use a different engine. Skipped on both Serverless generations, which do not answer GET /.
  2. GET /<index>/_mapping for the vector field(s) the mode declares — that each exists, is the expected type (knn_vector / rank_features), and carries the configured dimension. A knn_vector field that declares a space_type must also match similarityMetric; one that declares none gets a warning, since its space is set elsewhere. With normalizeCosineScore on, an nmslib cosine field needs OpenSearch 2.19 or later, checked with a further GET /: before 2.19, NMSLIB scores cosine as 1 / (2 - cos), which the normalization cannot invert. Skipped when init just 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+.

Copy
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 similarityScore is 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.
  • topK doubles as the retrieval depth under HYBRID. It becomes both the search size and the dense sub-query's k, so topK: 10 gives 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 the hybrid query's pagination_depth, which is 2.19+ and would silently do nothing on the 2.11 floor this mode otherwise supports. Request a larger topK than you intend to use and truncate the results yourself. For the same reason a HYBRID query with an embedding rejects topK below 1: "all" would be a maxResultWindow-deep k-NN search fused with a full sparse scan.
  • Sparse weights round-trip lossily. rank_features keeps 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 maxQueryTokens terms (default 1024), because neural_sparse compiles to one Lucene clause per term and the cluster's indices.query.bool.max_clause_count bounds 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 under HYBRID silently 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.
  • topK above maxResultWindow is rejected; raise maxResultWindow (and the index's own index.max_result_window setting) 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) as keyword, not the default analyzed text — otherwise == and in filters 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 maxResultWindow can see in one lookup — raise maxResultWindow and retry.
  • A Serverless Classic index is not searchable for ~10 s after init creates 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 a decimal, because JSON has one number type and Ballerina's parser maps every non-integral value to decimal. The value is exact; only the basic type differs, so readBack["rating"] == 4.25 is false. fileSize is the one numeric field restored to its declared type, because ai:Metadata declares it decimal. This matches ai.pinecone's behaviour, so metadata semantics stay identical when swapping vector stores behind the ai:VectorStore interface.

Examples

The ai.aws.opensearch package provides practical examples illustrating real-world use.

  1. RAG search — indexes a handful of text chunks and answers a similarity query with a metadata filter.
  2. 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;Copy

Other versions

1.0.0

Metadata

Released date: about 15 hours ago

Version: 1.0.0

License: Apache-2.0


Security

No known vulnerabilities in libraries

Checked on 2026-12-01 via OSV.dev


Compatibility

Platform: any

Ballerina version: 2201.14.0

GraalVM compatible: Yes


Pull count

Total: 0

Current verison: 0


Weekly downloads


Source repository


Keywords

AI/Vector Database

Cost/Paid

Vendor/Amazon

Area/AI & Machine Learning

Type/Vector Store

Type/Util

Name/AWS OpenSearch Vector Store


Contributors