AWS Builder Center

Amazon OpenSearch Service as a Vector Store for RAG

Learn how to use Amazon OpenSearch Service as a vector store for retrieval-augmented generation. Create a k-NN index, embed text with Amazon Bedrock, run semantic, filtered and hybrid searches, and answer questions from the results.

Create a vector index, load embeddings made with Amazon Bedrock, run semantic and filtered searches, and hand the best passages to a model to answer from.
In the knowledge base article, Bedrock took care of the vector store for us. That's the easy road, and for many projects it's the right one. But sometimes you want more control: your own chunking, your own metadata, filters on who can see what, or keyword and meaning searches combined. Or your team already runs OpenSearch and you'd like to use what you have.
Amazon OpenSearch Service can store vectors alongside ordinary text and search both. In this article we'll build a small RAG setup on it: create a vector index, embed some passages with a Bedrock embedding model, search by meaning, add a filter and then answer a question from the results.


What you need

  • The setup from the earlier articles: Python, boto3 and working Bedrock credentials
  • An Amazon OpenSearch Service domain, or permission to create one. A small test domain is fine.
  • Access to a Bedrock embedding model, with its model ID from the model's documentation
  • The  opensearch-py  library:  pip install opensearch-py 
  • About ninety minutes, much of it waiting for the domain to start
An OpenSearch domain bills for as long as it exists, whether you're using it or not, so read the cost and clean-up sections before you create one.

How the pieces fit

  1. You split your documents into chunks and embed each one with a Bedrock embedding model.
  1. You store each chunk's text, its metadata and its embedding in an OpenSearch k-NN index.
  1. At question time, you embed the question the same way and ask OpenSearch for the nearest chunks.
  1. You give those chunks to a model with the question, and it writes an answer from them.
The embeddings idea is the one from our Medium article on how AI turns meaning into numbers. OpenSearch is where those numbers live and get compared.

When to choose this over a managed knowledge base

Choose OpenSearch directly when
Choose a managed knowledge base when
You need hybrid search, mixing keywords and meaning
You want the quickest route to a working Q&A app
You need fine control over chunking, mappings and filters
Standard chunking options are enough
You already run OpenSearch and have the skills
You'd rather not manage a search cluster
The same index serves other search features
Retrieval is the only job
No shame in choosing the simpler column. Start there, and move when you hit its limits. Check which OpenSearch options your Bedrock knowledge bases currently support, because you may be able to combine both.

Step 1: Create a domain

In the Amazon OpenSearch Service console, create a domain. For a test:
  • Choose a current OpenSearch version.
  • Pick a small instance type and a single node. This is for learning, not production.
  • Turn on fine-grained access control and encryption, and choose IAM as the way to authenticate.
  • Don't leave it open to the world. Restrict the access policy to the IAM role or user you'll connect with. An OpenSearch domain with a wide-open policy has been the cause of plenty of data leaks.
The domain takes a while to become active. Note its endpoint when it's ready.
Some features discussed here, such as k-NN search, depend on the version of OpenSearch, and the managed service has its own list of differences and limits. The AWS documentation on k-NN in OpenSearch Service covers them.

Step 2: Connect from Python

Requests to the domain are signed with your AWS credentials:
import json
import boto3
from opensearchpy import AWSV4SignerAuth, OpenSearch, RequestsHttpConnection

REGION = "us-east-1"
HOST = "YOUR-DOMAIN-ENDPOINT" # without https://
INDEX = "docs-vector"
EMBED_MODEL_ID = "YOUR_EMBEDDING_MODEL_ID" # from the model's documentation

credentials = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(credentials, REGION, "es")

client = OpenSearch(
hosts=[{"host": HOST, "port": 443}],
http_auth=auth,
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection,
)

bedrock = boto3.client("bedrock-runtime", region_name=REGION)
print(client.info())
The  "es"  in the signer is the service name for OpenSearch Service domains. (OpenSearch Serverless uses a different one, so check if you go that way.) If  client.info()  prints details about the cluster, you're connected. If you get a permissions error, check that your identity is allowed by the domain's access policy and that fine-grained access control maps it to a suitable role.

Step 3: Create a vector index

A k-NN index needs two things: the  index.knn  setting turned on, and a field of type  knn_vector  with the right number of dimensions. That number must match your embedding model's output exactly.
DIMENSIONS = 1024 # must match your embedding model

index_body = {
"settings": {"index.knn": True},
"mappings": {
"properties": {
"text": {"type": "text"},
"source": {"type": "keyword"},
"embedding": {
"type": "knn_vector",
"dimension": DIMENSIONS,
"method": {
"name": "hnsw",
"engine": "faiss",
"space_type": "innerproduct",
},
},
}
},
}

client.indices.create(index=INDEX, body=index_body)
A few notes on what's in there:
  •  text  holds the chunk for keyword search and for showing to the model.
  •  source  is a keyword field for metadata such as the file name. You can filter on it.
  •  knn_vector  holds the embedding. HNSW is an algorithm for finding approximate nearest neighbours quickly. The Faiss and Lucene engines both support it.
  •  space_type  is how "closeness" is measured. Here we use inner product, which behaves like cosine similarity when the vectors are normalised, as we ask for in the next step. Which space types are supported depends on the engine and version, so check the current OpenSearch documentation if you'd rather use cosine similarity directly.
The vector dimension and the embedding model are linked for good. If you change the model later, you'll need a new index and to re-embed everything.

Step 4: Embed and load your chunks

First a function that turns text into an embedding. The request body below follows the format of Amazon Titan Text Embeddings. Other embedding models expect different bodies, so check the documentation for the model you chose.
def embed(text):
body = json.dumps({"inputText": text, "dimensions": DIMENSIONS, "normalize": True})
response = bedrock.invoke_model(
modelId=EMBED_MODEL_ID,
body=body,
contentType="application/json",
accept="application/json",
)
return json.loads(response["body"].read())["embedding"]
Now load some chunks. In real life you'd split documents carefully, as we'll cover in an upcoming article. For now, a few short passages will do:
from opensearchpy import helpers

chunks = [
("Annual plans can be refunded in full within 30 days of purchase.", "refund-policy.pdf"),
("Late deliveries qualify for a 10 percent refund on request.", "shipping-policy.pdf"),
("Gift cards never expire and can be used on any order.", "gift-cards.pdf"),
]

actions = [
{"_index": INDEX, "_source": {"text": text, "source": source, "embedding": embed(text)}}
for text, source in chunks
]
helpers.bulk(client, actions)
Use the bulk helper for more than a handful of documents, and avoid forcing an index refresh after every write, since that's expensive with vector indexes. New documents become searchable after the regular refresh interval, which is usually about a second.

Step 5: Search by meaning

def search(question, k=3, source=None):
knn = {"vector": embed(question), "k": k}
if source:
knn["filter"] = {"term": {"source": source}}
body = {
"size": k,
"_source": ["text", "source"],
"query": {"knn": {"embedding": knn}},
}
hits = client.search(index=INDEX, body=body)["hits"]["hits"]
return [(h["_score"], h["_source"]["source"], h["_source"]["text"]) for h in hits]

for score, source, text in search("How do I get my money back on a yearly subscription?"):
print(round(score, 3), source, text)
Notice the question shares almost no words with the refund passage, and it should still come back near the top. That's semantic search working.
The  source  argument shows the filter. Filtering by metadata, such as a department, a document type, a date range or the user's permissions, is one of the main reasons to run your own index. The OpenSearch documentation notes that its Lucene and Faiss HNSW engines both support efficient filtering inside the k-NN query. That's a better approach than searching first and filtering afterwards, which can leave you with fewer results than you asked for.

Step 6: Combine keywords and meaning

Semantic search can miss exact terms such as product codes, names and error messages. Keyword search misses paraphrases. Hybrid search uses both. A simple version combines a text match and a k-NN query in one request:
def hybrid_search(question, k=3):
body = {
"size": k,
"_source": ["text", "source"],
"query": {
"bool": {
"should": [
{"match": {"text": question}},
{"knn": {"embedding": {"vector": embed(question), "k": k}}},
]
}
},
}
return client.search(index=INDEX, body=body)["hits"]["hits"]
This works, but keyword scores and vector scores sit on different scales, so one can drown out the other. OpenSearch's neural search features offer proper score normalisation and blending through search pipelines. If hybrid search matters to you, read the current documentation on hybrid queries and the normalisation processor, since the details depend on your OpenSearch version.

Step 7: Answer from the results

Now close the loop and let a model write the answer, using only what was retrieved:
MODEL_ID = "YOUR_MODEL_ID" # a text model, from the model's documentation

def answer(question):
passages = search(question, k=3)
context = "\n\n".join(f"[{source}] {text}" for _, source, text in passages)
prompt = (
"Answer the question using only the passages below. "
"If the answer isn't in them, say you can't find it. "
"Mention the source name for each fact.\n\n"
f"<passages>\n{context}\n</passages>\n\n"
f"Question: {question}"
)
response = bedrock.converse(
modelId=MODEL_ID,
messages=[{"role": "user", "content": [{"text": prompt}]}],
inferenceConfig={"maxTokens": 300, "temperature": 0},
)
return response["output"]["message"]["content"][0]["text"]

print(answer("Can I get a refund if my parcel arrives late?"))
print(answer("Do you sell bicycles?"))
The second question is deliberate. Your passages say nothing about bicycles, so the right answer is "I can't find that." If the model invents one, tighten the instructions, and add that case to your tests.

Step 8: Tune and test

The settings that matter most:
  •  k , the number of passages. More gives the model more to work with but costs more tokens and can add noise.
  • Chunk size. Too big and the key sentence gets lost. Too small and it loses its context.
  • The approximate-search settings, such as the number of candidates considered, which trade speed against accuracy. The OpenSearch documentation explains them.
  • Vector compression. OpenSearch supports options such as byte vectors, binary quantisation and half-precision vectors that shrink memory use, at some cost to accuracy. AWS has published guidance on these, and they matter once your index is large.
Write ten to twenty questions you know the answers to, including a few the documents can't answer, and run them after every change. As in the knowledge base article, separate two questions: did retrieval find the right passage, and did the model use it well? Print the retrieved passages when an answer is wrong.

Keeping it safe

  • Lock down access. Use IAM and fine-grained access control, not an open policy. Consider placing the domain in a VPC.
  • Mind what's in the index. Chunks are copies of your documents. If a document is sensitive, so is its chunk.
  • Respect permissions. If different users may see different documents, filter on that in the query, and test it. Don't rely on the model to withhold things.
  • Keep secrets out of prompts and logs.
  • Encrypt, and back up. Encryption at rest and regular snapshots protect against loss.

What it costs

  • Domain instances are billed for every hour they run. This is usually the biggest part of the bill for a small project.
  • Storage for the index, and for backups.
  • Embedding calls to Bedrock, once per chunk when you load and once per question.
  • Model calls for the answers.
Vectors held in memory make large indexes costly, which is why compression is worth learning about. OpenSearch Serverless is an alternative that avoids managing instances, but it has its own baseline capacity charges, so compare the current pricing for both before you pick.

Common mistakes

  • Wrong dimension. The mapping and the embedding model must match.
  • Mixing embedding models in one index.
  • Leaving the domain open to the public.
  • Forgetting to delete the domain after experimenting.
  • Refreshing after every write.
  • Not filtering by permissions.
  • Judging only the final answer, and never looking at what was retrieved.
  • Never testing questions the documents can't answer.

Clean up

When you've finished, delete the index and, importantly, the domain itself. Check for snapshots and any other resources, and look at your bill after a day or two.

A checklist

  1. Does the mapping's dimension match your embedding model?
  1. Is the domain locked down with IAM, encryption and no open policy?
  1. Are you using the bulk helper, without forcing refreshes?
  1. Do you filter by metadata and permissions inside the k-NN query?
  1. Do you have a test set that includes unanswerable questions?
  1. Do you check retrieval separately from generation?
  1. Do you have a budget alert, and a plan to delete the domain?

Where we go next

Next, we'll look at how to pull structured data out of scanned documents with Amazon Textract and Bedrock, which gives your retrieval system better material to work with.
OpenSearch versions, k-NN features, supported engines, pricing and the console change often. Check the current Amazon OpenSearch Service documentation before you follow any step here, and test in a non-production account first.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article