
I Tried Using Amazon OpenSearch Serverless NextGen as a Vector Store for Knowledge Bases and Checked Its Scale-to-Zero Costs and Cold Start Countermeasures
This page has been translated by machine translation. View original
Introduction
Hi, I'm Kosuke from the AI Business Division.
Using Amazon OpenSearch Serverless as the vector store for Amazon Bedrock Knowledge Bases is very convenient, since you get hybrid search and metadata filtering. On the other hand, you keep paying for the minimum number of OCUs (the unit of compute resources) even during hours when almost no searches arrive, so for lightly used systems the vector store can account for most of the monthly bill.
NextGen for OpenSearch Serverless, released in May 2026, can scale OCUs down to 0 while idle, so no charges accrue during that period. However, the first search after OCUs have scaled down to 0 is a cold start and takes extra time on top of the normal search time.
In this article, I first use a NextGen collection as the vector store for Knowledge Bases and confirm that search works. Then I look at how OCUs scale down to 0 after a certain idle period and how that changes the charges. Finally, I try countermeasures for the wait time (cold start) on the first search after OCUs have scaled down to 0.
What is OpenSearch Serverless NextGen?
OpenSearch Serverless is OpenSearch that you can use without managing servers or clusters yourself. Data is held in units called collections, compute resources are counted in units called OCUs (OpenSearch Compute Unit), and you are billed according to the time used.
NextGen is a new generation of this service, rebuilt from scratch. The previous generation is now called Classic.
Differences from Classic
| Item | Classic | NextGen |
|---|---|---|
| OCUs when not in use | The minimum OCUs are maintained (at least 2 OCUs) | After 10 minutes idle, scales down to the OCUs set as the minimum (the default is 0 OCU, so charges stop) |
| Unit for setting OCU upper/lower limits | Account, or collection group | Collection group |
Specifying engine for a vector index |
Can be specified (nmslib if not specified) | Cannot be specified (specifying it causes an error) |
| Vector compression | To compress, specify the method in the index definition | Compressed 32x by default. The ratio can be changed with compression_level |
| Connecting from a VPC | A VPC endpoint dedicated to OpenSearch Serverless | Standard interface endpoint (aoss-data) |
A note on vector compression from the table. Vectors are normally stored as 32-bit numbers per dimension. Vector compression reduces the number of bits per dimension, making the data loaded into memory at search time smaller. With less data in memory, the same number of vectors can be searched with fewer OCUs, which keeps costs down. The more vectors you have, the greater this effect.
NextGen applies 32x compression by default. For a 1024-dimension vector, the data used for search works out to about 128 bytes per item. When creating an index, you can choose the ratio from 1x, 2x, 8x, 16x, and 32x with compression_level. 1x means no compression.
| Classic | NextGen | |
|---|---|---|
| Default | No compression is specified in the documentation examples | 32x (compression_level: 32x) |
| Options | Quantization to 16 bits (Faiss fp16), binary vectors, disk-based vector search (mode: on_disk) |
1x, 2x, 8x, 16x, 32x |
| How to specify | Write the method in the index definition | Write compression_level in the field definition |
The higher the compression, the less memory is needed, but because the search looks for nearby data in the compressed vector space, search accuracy may be more likely to drop. According to the OpenSearch documentation, a search with the disk-based method (mode: on_disk) runs in two stages. First, it collects a generous number of candidates using the compressed vectors; then, for those candidates, it loads the original-precision vectors stored on disk, recalculates the scores, and narrows down to the top results. This process preserves accuracy while saving memory through compression, and it is enabled by default with 32x compression. The index created in Step 2 below also gets mode: on_disk and compression_level: 32x set automatically.

Figure 1: Conceptual diagram of vector compression and two-stage search
Note that on NextGen indexes with the default 32x compression, searches that filter by a distance or score threshold (Radial search) cannot be used. The documentation doesn't say whether it works with a lower compression ratio, and I didn't check it this time. I also couldn't find figures in the AWS documentation for accuracy or memory usage per compression ratio. If accuracy matters to you, you'll need to create indexes with lower compression and compare them.
Collection groups and scale to zero
A collection group is a container for sharing OCUs among multiple collections, and you can set a minimum and maximum number of OCUs separately for search and for indexing (data writes).
When the minimum is set to 0, the behavior is as follows.
- If no collection in the group receives a request for 10 minutes, the search and indexing OCUs scale down to 0 and billing stops
- Search and indexing OCUs scale down separately and start up separately. While only search traffic arrives, the indexing OCUs stay at 0
- The first request after OCUs have scaled down to 0 takes an extra 10–30 seconds until the OCUs start up
- The 10-minute idle time cannot be changed
If you set the minimum to a non-zero value, OCUs don't scale down and stay at the minimum. You use this minimum to balance eliminating wait time against lowering cost.

Figure 2: Search OCU transitions during scale to zero (conceptual diagram)
Reference documents
This explains the scale-to-zero specification. It contains the statements that support the "Collection groups and scale to zero" section above.
- OCUs scale down to 0 after 10 minutes idle, and billing stops
When no collection in the group has incoming requests for 10 minutes, search and indexing workers scale down to zero OCU and billing stops.
- The length of the idle time cannot be changed
This idle period is not configurable.
- An extra wait of 10–30 seconds occurs at startup
Expect 10–30 seconds of latency on the first request to each component while capacity is restored.
- How to keep OCUs from scaling down to 0
If you don't want your collection capacities to scale to zero, make sure they are part of a collection group with minimum capacity set to a non-zero value.
Next, the explanation of minimum and maximum OCUs.
- The minimum and maximum can be set separately for indexing and searching, per collection group
You can set a minimum and maximum OCU per collection group, separately for indexing and searching.
- Setting the minimum OCU above 0 lets you avoid the startup wait
Use minimum capacity to avoid cold start delays when scaling from zero
Next, the explanation of NextGen vector search collections. It covers the index definition and compression mentioned in this section.
- Indexes are compressed 32x by default, and the ratio can be chosen
All indexes are created with advanced 32x compression technique by default. You can override the default compression level and select any supported compression level: 1x, 2x, 8x, 16x, or 32x (default).
- Radial search cannot be used with 32x compression
Radial search isn't supported on NextGen vector indexes that use 32x compression.
The setup we'll build
- Amazon S3: where the documents to be searched are stored
- OpenSearch Serverless: a NextGen collection group (minimum 0 OCU) and a vector search collection
- Amazon Bedrock Knowledge Bases: ingestion and search of documents. The collection above is specified as the vector store
- Local PC: builds the environment and runs the Python scripts (boto3) for search and measurement

Figure 3: Test environment configuration and the creation steps for each resource
Prerequisites
- Region: Tokyo (ap-northeast-1)
- Execution environment: local PC (AWS credentials configured), Python 3.13, boto3 1.44.17
- Bedrock model:
amazon.titan-embed-text-v2:0(1024 dimensions) - Test data: I wrote 20 internal documents for a fictional company, "Sample Coffee Trading Co." They include a partner FAQ, work rules, meeting minutes, system specifications, monthly reports, and so on
Step 1: Create the collection group and collection
I build the test environment with the boto3 script 00_setup.py. Passing base as the argument creates the following together.
- An S3 bucket to hold the sample documents
- An IAM role for the Knowledge Base
- Three policies: encryption, network, and data access
- The NextGen collection group
sample-coffee-pre-ng - The vector search collection
sample-coffee-pre-kb

Figure 4: Relationship between the collection group and the collection
"""検証環境を boto3 で作る。
python3 00_setup.py base # S3・ポリシー・IAM ロール・コレクショングループ・コレクション
python3 00_setup.py kb # Knowledge Base・データソース・同期(先に 01_create_index.py を実行しておく)
作ったリソースの ID は STATE_FILE(デフォルトは ./.local-state.json。.gitignore 済み)に保存する。
"""
import json
import os
import sys
import time
import uuid
from pathlib import Path
import boto3
REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
PREFIX = os.environ.get("PREFIX", "sample-coffee-pre")
STATE_FILE = Path(os.environ.get("STATE_FILE", ".local-state.json"))
DOCS_DIR = Path(__file__).resolve().parent.parent / "data" / "docs"
def make_arn(service: str, resource: str, region: str = "", account: str = "") -> str:
"""ARN を組み立てる(アカウント ID や実在のリソース名をコードに書かないため)。"""
return ":".join(["arn", "aws", service, region, account, resource])
EMBEDDING_MODEL_ARN = make_arn("bedrock", "foundation-model/amazon.titan-embed-text-v2:0", region=REGION)
INDEX_NAME = "bedrock-knowledge-base-default-index"
GROUP_NAME = f"{PREFIX}-ng"
COLLECTION_NAME = f"{PREFIX}-kb"
ROLE_NAME = f"{PREFIX}-kb-role"
session = boto3.session.Session(region_name=REGION)
aoss = session.client("opensearchserverless")
iam = session.client("iam")
s3 = session.client("s3")
sts = session.client("sts")
agent = session.client("bedrock-agent")
def load_state() -> dict:
return json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}
def save_state(state: dict) -> None:
STATE_FILE.write_text(json.dumps(state, indent=2))
def caller_principal() -> str:
"""データアクセスポリシーに入れる、自分の IAM ユーザーまたはロールの ARN。"""
arn = sts.get_caller_identity()["Arn"]
if ":assumed-role/" in arn:
role_name = arn.split(":assumed-role/")[1].split("/")[0]
return iam.get_role(RoleName=role_name)["Role"]["Arn"]
return arn
def step(message: str, started: float) -> None:
print(f"[{time.perf_counter() - started:6.1f} 秒] {message}", flush=True)
def base() -> None:
state = load_state()
started = time.perf_counter()
account_id = sts.get_caller_identity()["Account"]
# ---------- S3 ----------
bucket = state.get("bucket") or f"{PREFIX}-docs-{uuid.uuid4().hex[:8]}"
s3.create_bucket(Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": REGION})
for path in sorted(DOCS_DIR.glob("*.md")):
s3.upload_file(str(path), bucket, path.name)
state["bucket"] = bucket
save_state(state)
step(f"S3 バケットを作成し {len(list(DOCS_DIR.glob('*.md')))} 件をアップロード", started)
# ---------- IAM ロール(Knowledge Base 用) ----------
role = iam.create_role(
RoleName=ROLE_NAME,
AssumeRolePolicyDocument=json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "bedrock.amazonaws.com"},
"Action": "sts:AssumeRole",
"Condition": {"StringEquals": {"aws:SourceAccount": account_id}},
}],
}),
)["Role"]
iam.put_role_policy(
RoleName=ROLE_NAME,
PolicyName="kb-access",
PolicyDocument=json.dumps({
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": "bedrock:InvokeModel", "Resource": EMBEDDING_MODEL_ARN},
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [make_arn("s3", bucket), make_arn("s3", f"{bucket}/*")]},
{"Effect": "Allow", "Action": "aoss:APIAccessAll",
"Resource": make_arn("aoss", "collection/*", region=REGION, account=account_id)},
],
}),
)
state["role_arn"] = role["Arn"]
save_state(state)
step("IAM ロールを作成", started)
# ---------- 暗号化・ネットワーク・データアクセスの 3 ポリシー ----------
aoss.create_security_policy(
name=f"{PREFIX}-enc", type="encryption",
policy=json.dumps({"Rules": [{"ResourceType": "collection", "Resource": [f"collection/{COLLECTION_NAME}"]}],
"AWSOwnedKey": True}),
)
aoss.create_security_policy(
name=f"{PREFIX}-net", type="network",
policy=json.dumps([{"Rules": [{"ResourceType": "collection", "Resource": [f"collection/{COLLECTION_NAME}"]}],
"AllowFromPublic": True}]),
)
aoss.create_access_policy(
name=f"{PREFIX}-data", type="data",
policy=json.dumps([{
"Rules": [
{"ResourceType": "collection", "Resource": [f"collection/{COLLECTION_NAME}"], "Permission": ["aoss:*"]},
{"ResourceType": "index", "Resource": [f"index/{COLLECTION_NAME}/*"], "Permission": ["aoss:*"]},
],
"Principal": [caller_principal(), role["Arn"]],
}]),
)
step("ポリシー 3 つを作成", started)
# ---------- コレクショングループ(NextGen・最小 0 OCU) ----------
group = aoss.create_collection_group(
name=GROUP_NAME, generation="NEXTGEN", standbyReplicas="ENABLED",
capacityLimits={"minIndexingCapacityInOCU": 0, "maxIndexingCapacityInOCU": 2,
"minSearchCapacityInOCU": 0, "maxSearchCapacityInOCU": 2},
)["createCollectionGroupDetail"]
state["group_id"] = group["id"]
save_state(state)
step(f"コレクショングループを作成: generation={group.get('generation')} limits={group.get('capacityLimits')}", started)
# ---------- コレクション ----------
collection = aoss.create_collection(
name=COLLECTION_NAME, type="VECTORSEARCH", collectionGroupName=GROUP_NAME, standbyReplicas="ENABLED",
)["createCollectionDetail"]
state["collection_id"] = collection["id"]
state["collection_arn"] = collection["arn"]
save_state(state)
created = time.perf_counter()
while True:
detail = aoss.batch_get_collection(ids=[collection["id"]])["collectionDetails"][0]
if detail["status"] != "CREATING":
break
time.sleep(3)
step(f"コレクションが {detail['status']}(作成から {time.perf_counter() - created:.0f} 秒)", started)
shown = {k: v for k, v in detail.items() if k not in ("arn", "kmsKeyArn", "collectionEndpoint", "dashboardEndpoint")}
print(json.dumps(shown, ensure_ascii=False, indent=2, default=str))
def kb() -> None:
state = load_state()
started = time.perf_counter()
created = agent.create_knowledge_base(
name=f"{PREFIX}-kb",
roleArn=state["role_arn"],
knowledgeBaseConfiguration={
"type": "VECTOR",
"vectorKnowledgeBaseConfiguration": {
"embeddingModelArn": EMBEDDING_MODEL_ARN,
"embeddingModelConfiguration": {"bedrockEmbeddingModelConfiguration": {"dimensions": 1024}},
},
},
storageConfiguration={
"type": "OPENSEARCH_SERVERLESS",
"opensearchServerlessConfiguration": {
"collectionArn": state["collection_arn"],
"vectorIndexName": INDEX_NAME,
"fieldMapping": {
"vectorField": "bedrock-knowledge-base-default-vector",
"textField": "AMAZON_BEDROCK_TEXT_CHUNK",
"metadataField": "AMAZON_BEDROCK_METADATA",
},
},
},
)["knowledgeBase"]
state["kb_id"] = created["knowledgeBaseId"]
save_state(state)
while agent.get_knowledge_base(knowledgeBaseId=state["kb_id"])["knowledgeBase"]["status"] == "CREATING":
time.sleep(2)
step(f"Knowledge Base を作成: {state['kb_id']}", started)
source = agent.create_data_source(
knowledgeBaseId=state["kb_id"], name=f"{PREFIX}-docs",
dataSourceConfiguration={"type": "S3", "s3Configuration": {"bucketArn": make_arn("s3", state["bucket"])}},
)["dataSource"]
state["data_source_id"] = source["dataSourceId"]
save_state(state)
step("データソースを作成", started)
job = agent.start_ingestion_job(knowledgeBaseId=state["kb_id"], dataSourceId=state["data_source_id"])["ingestionJob"]
while True:
job = agent.get_ingestion_job(knowledgeBaseId=state["kb_id"], dataSourceId=state["data_source_id"],
ingestionJobId=job["ingestionJobId"])["ingestionJob"]
if job["status"] not in ("STARTING", "IN_PROGRESS"):
break
time.sleep(5)
step(f"同期が {job['status']}: {json.dumps(job.get('statistics', {}))}", started)
if job.get("failureReasons"):
print("failureReasons:", job["failureReasons"])
if __name__ == "__main__":
{"base": base, "kb": kb}[sys.argv[1]]()
python3 00_setup.py base
The output is as follows.
[ 3.5 秒] S3 バケットを作成し 20 件をアップロード
[ 5.3 秒] IAM ロールを作成
[ 6.5 秒] ポリシー 3 つを作成
[ 6.7 秒] コレクショングループを作成: generation=NEXTGEN limits={'maxIndexingCapacityInOCU': 2.0, 'maxSearchCapacityInOCU': 2.0, 'minIndexingCapacityInOCU': 0.0, 'minSearchCapacityInOCU': 0.0}
[ 14.1 秒] コレクションが ACTIVE(作成から 6 秒)
There are two NextGen-specific settings.
- Create the collection group with
generation="NEXTGEN". Setting the minimum incapacityLimitsto 0 is what lets OCUs scale down to 0. I set the maximum to 2 so it wouldn't grow larger than expected during testing - When creating the collection, specify the group with
collectionGroupName. Whether it's NextGen or Classic is specified when creating the collection group, not the collection
The collection became active about 10 seconds after creation.
Reference documents
Step 2: Create the index for Knowledge Bases
First, create the vector index that Knowledge Bases will write data to. On NextGen, you write only name: hnsw in method in the vector field definition.
Create it with 01_create_index.py. The field names must match the names you specify when creating the Knowledge Base.
"""NextGen のベクトル検索コレクションに、Knowledge Bases 用のベクトルインデックスを作る。
使い方:
COLLECTION_ID=<コレクション ID> python3 01_create_index.py
"""
import json
import os
import boto3
REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
COLLECTION_ID = os.environ["COLLECTION_ID"]
INDEX_NAME = os.environ.get("INDEX_NAME", "bedrock-knowledge-base-default-index")
DIMENSION = 1024 # Titan Text Embeddings V2
aoss = boto3.client("opensearchserverless", region_name=REGION)
# On NextGen, engine cannot be specified (specifying it gives "Field parameter 'engine' is not supported").
# If only hnsw is written in method, engine is registered as faiss and passes the Knowledge Bases check.
# If method is omitted, creating the Knowledge Base fails with an error saying "recreate it with FAISS".
INDEX_SCHEMA = {
"settings": {"index": {"knn": True}},
"mappings": {
"properties": {
"bedrock-knowledge-base-default-vector": {
"type": "knn_vector",
"dimension": DIMENSION,
"space_type": "l2",
"method": {"name": "hnsw"},
},
"AMAZON_BEDROCK_TEXT_CHUNK": {"type": "text"},
"AMAZON_BEDROCK_METADATA": {"type": "text", "index": False},
}
},
}
def main() -> None:
aoss.create_index(id=COLLECTION_ID, indexName=INDEX_NAME, indexSchema=INDEX_SCHEMA)
created = aoss.get_index(id=COLLECTION_ID, indexName=INDEX_NAME)
created.pop("ResponseMetadata", None)
print(json.dumps(created, ensure_ascii=False, indent=2, default=str))
if __name__ == "__main__":
main()
COLLECTION_ID=<コレクション ID> python3 01_create_index.py
The definition retrieved after creation is as follows.
{
"indexSchema": {
"bedrock-knowledge-base-default-index": {
"settings": {
"index": {
"knn.remote_index_build": {
"enabled": "true"
},
"number_of_shards": "2",
"provided_name": "bedrock-knowledge-base-default-index",
"knn": "true",
"creation_date": "(省略)",
"custom_doc_id_enabled": "true",
"number_of_replicas": "0",
"uuid": "(省略)",
"version": {
"created": "137247827"
}
}
},
"mappings": {
"properties": {
"AMAZON_BEDROCK_METADATA": {
"type": "text",
"index": false
},
"bedrock-knowledge-base-default-vector": {
"mode": "on_disk",
"type": "knn_vector",
"method": {
"name": "hnsw",
"engine": "faiss",
"parameters": {},
"space_type": "l2"
},
"dimension": 1024,
"compression_level": "32x",
"space_type": "l2"
},
"AMAZON_BEDROCK_TEXT_CHUNK": {
"type": "text"
}
}
},
"aliases": {}
}
}
}
Items I didn't specify were set to default values. The vector field got mode: on_disk and compression_level: 32x (32x compression) in addition to engine: faiss. The index settings include 2 shards, 0 replicas, and GPU-based index building (knn.remote_index_build) enabled.
Reference documents
Step 3: Create the Knowledge Base and ingest the sample data
The Knowledge Base is created by passing kb to 00_setup.py from Step 1. For the vector store, I specify the OpenSearch Serverless collection, the index created in Step 2, and its field names. After creation, it registers the S3 data source and runs a sync.
python3 00_setup.py kb
When I specified the index created with the Step 2 definition, I was able to create a Knowledge Base on a NextGen collection.

Figure 5: What 00_setup.py kb does
The sync of 20 documents finished in about 40 seconds, and I confirmed in the document list that all 20 had been ingested.
Incidentally, during testing I deleted and recreated an index with the same name and synced right afterward, and 10 of the 20 documents failed with index_not_found_exception (an error referring to the deleted old index). When I checked again after a short wait, all 20 had been ingested. After recreating an index, it seems best to wait a little before syncing.
Reference documents
Step 4: Try vector search and hybrid search
We now have all the resources needed for search. The flow is as follows. When the local PC sends a query to the Knowledge Bases Retrieve API, Knowledge Bases converts the query into an embedding and searches the NextGen collection. The local PC retrieves the top 5 results.

Figure 6: Test environment configuration and search flow
For search I use 02_retrieve.py. It calls the Knowledge Bases Retrieve API once and displays the elapsed time and the top 5 results.
"""Knowledge Base に検索(Retrieve)を投げて、所要時間と結果を表示する。
使い方:
KB_ID=<ナレッジベース ID> python3 02_retrieve.py "生豆の最低発注量は?"
KB_ID=<ナレッジベース ID> python3 02_retrieve.py "生豆の最低発注量は?" --type SEMANTIC
"""
import argparse
import os
import time
import boto3
REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
KB_ID = os.environ["KB_ID"]
runtime = boto3.client("bedrock-agent-runtime", region_name=REGION)
def retrieve(query: str, search_type: str = "HYBRID", top_k: int = 5) -> tuple[float, list[dict]]:
"""Retrieve を 1 回呼び、所要時間(秒)と結果を返す。"""
started = time.perf_counter()
response = runtime.retrieve(
knowledgeBaseId=KB_ID,
retrievalQuery={"text": query},
retrievalConfiguration={
"vectorSearchConfiguration": {"numberOfResults": top_k, "overrideSearchType": search_type}
},
)
return time.perf_counter() - started, response["retrievalResults"]
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("query")
parser.add_argument("--type", default="HYBRID", choices=["HYBRID", "SEMANTIC"])
args = parser.parse_args()
elapsed, results = retrieve(args.query, args.type)
print(f"[{args.type}] {args.query} 所要時間: {elapsed:.2f} 秒")
for rank, item in enumerate(results, start=1):
uri = item.get("location", {}).get("s3Location", {}).get("uri", "")
text = item["content"]["text"].replace("\n", " ")[:60]
print(f"{rank}. score={item.get('score', 0):.3f} {uri.rsplit('/', 1)[-1]} {text}")
if __name__ == "__main__":
main()
I try both hybrid search and vector-only search (semantic search).
KB_ID=<ナレッジベース ID> python3 02_retrieve.py "生豆の最低発注量は?"
KB_ID=<ナレッジベース ID> python3 02_retrieve.py "生豆の最低発注量は?" --type SEMANTIC
The output is as follows.
[HYBRID] 生豆の最低発注量は? 所要時間: 1.05 秒
1. score=0.483 faq_partners_13.md # 取引先向け FAQ ※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物
2. score=0.483 faq_partners_08.md # 取引先向け FAQ ※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物
3. score=0.483 faq_partners_18.md # 取引先向け FAQ ※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物
4. score=0.483 faq_partners_03.md # 取引先向け FAQ ※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物
5. score=0.370 meeting_procurement_16.md - 発行: サンプル珈琲商事株式会社 調達部 - 版: 2026-04-01 - 日時: 2026-07-22 10:0
[SEMANTIC] 生豆の最低発注量は? 所要時間: 0.63 秒
1. score=0.483 faq_partners_08.md # 取引先向け FAQ ※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物
2. score=0.483 faq_partners_18.md # 取引先向け FAQ ※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物
3. score=0.483 faq_partners_13.md # 取引先向け FAQ ※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物
4. score=0.483 faq_partners_03.md # 取引先向け FAQ ※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物
5. score=0.370 meeting_procurement_16.md - 発行: サンプル珈琲商事株式会社 調達部 - 版: 2026-04-01 - 日時: 2026-07-22 10:0
Specifying hybrid search (HYBRID) did not cause an error, and the partner FAQ describing the minimum order quantity ranked at the top. The top 4 results have the same score because the 4 FAQ documents in the sample data have identical text.
The elapsed times for 10 consecutive searches each are as follows.

Figure 7: Elapsed time for consecutive searches
The median was 0.46 seconds for hybrid search and 0.39 seconds for semantic search. While OCUs are provisioned, searches return at about this speed.
Reference documents
Step 5: Check the scale-to-zero behavior
Checking behavior until OCUs reach 0 with no traffic
I stop sending search requests and check with CloudWatch metrics how OCUs scale down to 0. 04_show_ocu.py displays SearchOCU and IndexingOCU at 1-minute granularity.
"""CloudWatch から OpenSearch Serverless の OCU のメトリクスを取り出して表示する。
使い方:
python3 04_show_ocu.py --hours 3
"""
import argparse
import datetime
import os
import boto3
REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
NAMESPACE = "AWS/AOSS"
cloudwatch = boto3.client("cloudwatch", region_name=REGION)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--hours", type=float, default=3)
args = parser.parse_args()
end = datetime.datetime.now(datetime.UTC)
start = end - datetime.timedelta(hours=args.hours)
for metric_name in ("SearchOCU", "IndexingOCU"):
# Dimensions appear as a combination of CollectionGroupId, CollectionGroupName, and ClientId
metrics = cloudwatch.list_metrics(Namespace=NAMESPACE, MetricName=metric_name)["Metrics"]
for metric in metrics:
dimensions = metric["Dimensions"]
# ClientId is the account ID, so don't display it
label = ", ".join(f"{d['Name']}={d['Value']}" for d in dimensions if d["Name"] != "ClientId")
points = cloudwatch.get_metric_statistics(
Namespace=NAMESPACE, MetricName=metric_name, Dimensions=dimensions,
StartTime=start, EndTime=end, Period=60, Statistics=["Maximum"],
)["Datapoints"]
print(f"## {metric_name} [{label}]")
for point in sorted(points, key=lambda p: p["Timestamp"]):
local = point["Timestamp"].astimezone().strftime("%H:%M")
print(f"{local} {point['Maximum']}")
if __name__ == "__main__":
main()
python3 04_show_ocu.py --hours 1
The metrics are in the CloudWatch namespace AWS/AOSS and can be retrieved per collection group. Graphing 3 hours of this test gives the following.

Figure 8: OCU transitions during the test period
Here is what the graph showed.
- Search OCUs scaled up from 0 to 2 when I sent a search
- 10–11 minutes after the last search, they scaled down to 0. In the stretch where I searched every 15 minutes, they scaled down to 0 each time and scaled up to 2 again on the next search
- In the stretch where the minimum OCU was 2, search OCUs did not scale down to 0 and stayed at 2 even when no searches were sent for 20 minutes. OCUs are held even while not in use, which is the same behavior as the previous OpenSearch Serverless (Classic). I cover this setting in the cold-start countermeasures section
- Indexing OCUs went to 1 for about 10 minutes after the sync in Step 3, and after that stayed at 0 even when I sent searches. I confirmed that search and indexing scale down separately
The current OCU value can also be obtained from currentCapacity in the BatchGetCollectionGroup API.
Checking the time taken by the first search after scale-down
Next, I measure the time taken by the first search after OCUs have scaled down to 0. 03_idle_probe.py waits for the specified time, then records the elapsed time of the first search and of the two searches that follow.
"""しばらく検索を止めた後の、最初の検索と続く 2 回の検索の所要時間を測る。
使い方:
KB_ID=<ナレッジベース ID> python3 03_idle_probe.py --idle-minutes 15 --rounds 3
"""
import argparse
import datetime
import importlib
import json
import time
retrieve = importlib.import_module("02_retrieve").retrieve
QUERY = "生豆の最低発注量は?"
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--idle-minutes", type=float, default=15)
parser.add_argument("--rounds", type=int, default=3)
args = parser.parse_args()
for round_no in range(1, args.rounds + 1):
print(f"round {round_no}: {args.idle_minutes} 分待ちます", flush=True)
time.sleep(args.idle_minutes * 60)
record = {"round": round_no, "idle_minutes": args.idle_minutes,
"started_at": datetime.datetime.now().isoformat(timespec="seconds"), "seconds": []}
for _ in range(3): # The first search, then 2 more in a row
try:
elapsed, results = retrieve(QUERY)
record["seconds"].append(round(elapsed, 2))
record["hits"] = len(results)
except Exception as error: # Also record whether it fails during startup
record["seconds"].append(None)
record["error"] = repr(error)
print(json.dumps(record, ensure_ascii=False), flush=True)
if __name__ == "__main__":
main()
I measure the search after 15 minutes of no traffic three times, and the search after 30 minutes of no traffic once.
KB_ID=<ナレッジベース ID> python3 03_idle_probe.py --idle-minutes 15 --rounds 3
KB_ID=<ナレッジベース ID> python3 03_idle_probe.py --idle-minutes 30 --rounds 1
The results are as follows. For the 30-minute run, I confirmed that OCUs were at 0 just before the search.

Figure 9: Search time after no traffic
| Idle time | First search | 2nd | 3rd |
|---|---|---|---|
| 15 min (run 1) | 4.52 s | 0.75 s | 0.63 s |
| 15 min (run 2) | 14.76 s | 0.67 s | 0.55 s |
| 15 min (run 3) | 12.82 s | 3.79 s | 1.39 s |
| 30 min | 15.66 s | 0.85 s | 0.51 s |
The first search after scale-down took 13–16 seconds in 3 of the 4 runs. It doesn't fail with an error; it just takes longer to get the Retrieve response. There was no difference in wait time between 15 and 30 minutes of no traffic. Only the first 15-minute run was shorter, at 4.52 seconds (explained below).
The 2nd and 3rd searches were often under 1 second, but one took 3.79 seconds. It seems it can take a few searches to return to the 0.46 seconds seen with consecutive searches.
A note on why the first 15-minute run was shorter. Looking at the OCU transitions, in that run the search OCUs had scaled down to 0 about 3 minutes before the search and then scaled up to 2 right after. I hadn't sent any searches myself, and I don't know why it scaled up. Since OCUs were already up at the time of the search, the wait appears to have been shorter. As a rule, it's probably best to assume a cold start takes around 10–15 seconds.
Reference documents
Pricing
Billing differences between Classic and NextGen
OpenSearch Serverless pricing is determined by OCU usage time and the amount of stored data. OCUs are billed per second, per collection group.
| Item | Classic | NextGen (minimum 0 OCU) |
|---|---|---|
| OCUs during unused time | You keep paying for the minimum OCUs | No charge |
| OCUs during used time | OCUs used | OCUs used (until 10 minutes after the last request) |
| Storage | Charged by data volume | Charged by data volume |
Unit prices in the Tokyo region are as follows (AWS published price list, version of November 25, 2026).
| Item | Unit price |
|---|---|
| Search OCU, indexing OCU | 0.334 USD / OCU-hour |
| OCU for accelerated vector index building (GPU) | 0.334 USD / OCU-hour |
| Storage (hot) | 0.36 USD / GB-month |
| Storage (S3) | 0.026 USD / GB-month |
Monthly cost comparison by usage pattern
I compare the search OCU cost by calculating from the unit price (0.334 USD / OCU-hour) and the time OCUs are provisioned. I assume 730 hours per month and 20 business days.
| Usage pattern | Hours OCUs are provisioned (per month) | OCUs | OCU-hours (per month) | Monthly cost |
|---|---|---|---|---|
| Classic (always the minimum OCUs) | 730 hours | 2 | 1,460 | About 488 USD |
| NextGen, always keeping a minimum of 2 OCUs | 730 hours | 2 | 1,460 | About 488 USD |
| NextGen, keeping a minimum of 2 OCUs only 8 hours on business days | About 163 hours | 2 | About 327 | About 109 USD |
| NextGen, minimum 0 OCU (20 searches per business day, spaced apart) | About 73 hours | 2 | About 147 | About 49 USD |
The monthly cost is the OCU-hours multiplied by the unit price. For row 3, I added the 10 minutes between returning the minimum OCU to 0 and the scale-down to the 8 business hours. For row 4, since this measurement showed 2 OCUs held for 10–11 minutes after a single search, I calculated 11 minutes per search. If the interval between searches is shorter than 10 minutes, the provisioned time will be shorter than this.
The lighter the usage, the greater the effect of a minimum of 0 OCU. With 20 searches a day, the monthly cost is about 49 USD, roughly one-tenth of keeping 2 OCUs at all times. Even the approach of holding the minimum OCUs only during business hours comes to about 109 USD, less than a quarter.
Reference documents
Cold-start countermeasures
I try two ways to avoid the wait on the first search after scale-down.
Holding the minimum OCUs only during business hours
In AWS Lambda terms, this is close to reserving execution environments in advance with Provisioned Concurrency. If the hours of use are fixed, raise the collection group's minimum search OCU only during those hours and return it to 0 outside them. 05_set_min_search_ocu.py does the switching.
"""コレクショングループの検索の最小容量(OCU)を切り替える。
営業時間の開始時に 2、終了時に 0 を指定する想定。
使い方:
python3 05_set_min_search_ocu.py 2
python3 05_set_min_search_ocu.py 0
"""
import argparse
import json
import os
import boto3
REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
COLLECTION_GROUP_NAME = os.environ.get("COLLECTION_GROUP_NAME", "sample-coffee-nextgen")
aoss = boto3.client("opensearchserverless", region_name=REGION)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("min_search_ocu", type=float)
args = parser.parse_args()
group = aoss.batch_get_collection_group(names=[COLLECTION_GROUP_NAME])["collectionGroupDetails"][0]
limits = dict(group["capacityLimits"])
print("変更前:", json.dumps(limits))
limits["minSearchCapacityInOCU"] = args.min_search_ocu
aoss.update_collection_group(id=group["id"], capacityLimits=limits)
after = aoss.batch_get_collection_group(names=[COLLECTION_GROUP_NAME])["collectionGroupDetails"][0]
print("変更後:", json.dumps(after["capacityLimits"]))
if __name__ == "__main__":
main()
python3 05_set_min_search_ocu.py 2
KB_ID=<ナレッジベース ID> python3 03_idle_probe.py --idle-minutes 20 --rounds 1
python3 05_set_min_search_ocu.py 0
These are the results of searching after 20 minutes of no traffic with the minimum OCU set to 2.

Figure 10: Comparison of search time by minimum OCU setting
| Condition | OCUs before search | First search | 2nd | 3rd |
|---|---|---|---|---|
| Minimum 0 OCU (30 min no traffic) | 0 OCU | 15.66 s | 0.85 s | 0.51 s |
| Minimum 2 OCU (20 min no traffic) | 2 OCU | 1.33 s | 0.59 s | 1.81 s |
Naturally, with the minimum OCU at 2, OCUs stayed at 2 even when no searches arrived for 20 minutes, and the first search completed in 1.33 seconds. The setting change took effect within a few seconds of running it, so if you prepare a workflow that changes it each time, it should be perfectly workable operationally.
I couldn't find a feature in OpenSearch Serverless itself for switching OCUs by time of day. If you want to switch at fixed times, you'll need to build a mechanism that calls UpdateCollectionGroup from something like Amazon EventBridge Scheduler. For example, you could create two schedules: "set the minimum OCU to 2 at 8:00 on weekdays" and "return it to 0 at 19:00 on weekdays."
Keep the following in mind when building the switching mechanism.
capacityLimitsinUpdateCollectionGroupis not a partial update. Items you don't specify revert to their defaults, so pass all four items (minimum and maximum) every time- Even if you return the minimum OCU to 0, it doesn't scale down at that moment; it scales down 10 minutes after requests stop arriving
Keeping OCUs up with periodic searches
This is the same idea as the Lambda cold-start countermeasure of invoking a function periodically to keep the execution environment warm. If you keep sending searches at intervals shorter than 10 minutes, OCUs won't scale down. 06_keep_warm.py sends a search at the specified interval.
"""一定の間隔で検索を送り、検索の OCU が 0 までスケールダウンしないようにする。
使い方:
KB_ID=<ナレッジベース ID> python3 06_keep_warm.py --interval-minutes 9 --hours 1
"""
import argparse
import datetime
import importlib
import time
retrieve = importlib.import_module("02_retrieve").retrieve
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--interval-minutes", type=float, default=9)
parser.add_argument("--hours", type=float, default=1)
args = parser.parse_args()
deadline = time.time() + args.hours * 3600
while time.time() < deadline:
elapsed, _ = retrieve("ウォームアップ")
print(f"{datetime.datetime.now():%H:%M:%S} 所要時間: {elapsed:.2f} 秒", flush=True)
time.sleep(args.interval_minutes * 60)
if __name__ == "__main__":
main()
KB_ID=<ナレッジベース ID> python3 06_keep_warm.py --interval-minutes 9 --hours 1

Figure 11: Search time with 9-minute intervals
These are the results of searching 4 times at 9-minute intervals starting from OCUs at 0 (for the measurement I used a separate script that does the same thing but is adapted to refresh credentials).
| Run | Time since previous search | Elapsed time | OCUs after search |
|---|---|---|---|
| 1st | 40 min | 14.62 s | 2 |
| 2nd | 9 min | 1.10 s | 2 |
| 3rd | 9 min | 1.08 s | 2 |
| 4th | 9 min | 1.08 s | 2 |
The 1st run started from OCUs at 0, so it took 14.62 seconds, but from the 2nd onward OCUs stayed at 2 even with 9 minutes between searches, and they completed in about 1.1 seconds. If you keep sending searches at intervals shorter than 10 minutes, you can keep OCUs up.
However, the OCUs held this way are the same 2 as with the minimum-OCU approach, so there is no difference in cost. On top of that you pay for the mechanism that keeps sending searches and for the embeddings each time, so if the hours you want OCUs held are fixed, I think raising the minimum OCU is the more straightforward approach.
Comparing wait time and monthly cost by countermeasure
| Countermeasure | First search after a gap | Monthly search OCU cost | Required changes |
|---|---|---|---|
| None (minimum 0 OCU) | 13–16 s | About 49 USD | None |
| Hold minimum OCUs only during business hours | 1.3 s | About 109 USD | A scheduled switching mechanism |
| Send searches periodically | 1.1 s | About 109 USD | A periodic execution mechanism |
The monthly search OCU cost for no countermeasure assumes 20 spaced-out search requests per business day. The bottom two are for keeping OCUs up for 8 hours on business days, and the time taken by the first search after a gap is within the margin of error.
Reference documents
Things to know before using it
Differences in index definitions
Index definitions written for Classic may not work as-is on NextGen. As in Step 2, drop the engine specification, and when using it with Knowledge Bases, write only hnsw in method. If you migrate a Knowledge Base running on Classic to NextGen, review the index definition.
Access from a VPC
I tested with public access this time, but when accessing from inside a VPC, NextGen uses a standard interface endpoint (service name com.amazonaws.<region>.aoss-data). It is separate from the VPC endpoint dedicated to OpenSearch Serverless on Classic, so when migrating from Classic you need to add an endpoint and register it in the network policy.
Use as a Knowledge Bases vector store
As of writing, the Knowledge Bases documentation doesn't mention NextGen collections. In this test, I confirmed that creating a Knowledge Base, syncing from S3, and running hybrid and semantic search all worked.
Reference documents
Cleanup
When testing is finished, delete things in the following order.
- Delete the Knowledge Base (the data source is deleted too)
- Delete the collection
sample-coffee-pre-kb, then delete the collection groupsample-coffee-pre-ng - Delete the data access policy, network policy, and encryption policy
- Empty and delete the S3 bucket
- Delete the IAM role created for the Knowledge Base
With the minimum left at 0 OCU, you aren't charged for OCUs while they're unused, but storage charges continue to accrue.
Conclusion
In this article, I used OpenSearch Serverless NextGen as the vector store for Knowledge Bases and checked how OCUs scale down to 0, the pricing, and cold-start countermeasures.
Thank you for reading to the end!
References
- What is Amazon OpenSearch Serverless? - Amazon OpenSearch Service
- Scale to zero for Amazon OpenSearch Serverless - Amazon OpenSearch Service
- Managing capacity limits for Amazon OpenSearch Serverless - Amazon OpenSearch Service
- Amazon OpenSearch Serverless collection groups - Amazon OpenSearch Service
- Creating collections - Amazon OpenSearch Service
- Working with vector search collections - Amazon OpenSearch Service
- Data plane access through AWS PrivateLink - Amazon OpenSearch Service
- Prerequisites for using a vector store you created for a knowledge base - Amazon Bedrock
- Configure and customize queries and response generation - Amazon Bedrock
- Amazon OpenSearch Service Pricing
- The next generation of Amazon OpenSearch Serverless - AWS Big Data Blog
