Semantic retrieval compares the meaning of a question with stored text, even when they use different words. An OpenSearch vector index stores embeddings from Sentence Transformers beside each document so a Python application can retrieve the nearest matches through k-NN search.
The embedding model runs in Python on the CPU; OpenSearch receives ordinary floating-point vectors rather than loading the model itself. The document and query encoders must use the same model, and the index's vector dimension must match its output. Changing models requires re-encoding every document, even when both models have the same dimension.
A single-node Docker service on a Linux development machine is enough for a small corpus. The bundled security configuration provides password authentication and HTTPS with demonstration certificates, so it belongs on a private, local service rather than a public or production endpoint. The Python client and Docker service run on the same machine.
Steps to build an OpenSearch vector index with Sentence Transformers:
- Prepare a Linux development machine with Docker Engine and at least 4 GiB of RAM.
Docker must be running before the container starts. On Ubuntu, the vendor maintains the repository installation instructions at Install Docker Engine on Ubuntu. The Python project also needs Python 3 with venv support and internet access for the initial model download.
Related: Install Python 3 on Ubuntu or Debian - Create a virtual environment in your Python project directory.
$ python3 -m venv .venv
On Ubuntu or Debian, a missing ensurepip module means the matching python3-venv package is required.
Related: Create a Python virtual environment - Activate the project environment in your Bash shell.
$ source .venv/bin/activate
The remaining shell commands use this same session so the environment and password remain available.
Related: Activate a Python virtual environment - Install Sentence Transformers using its CPU-only installation path.
The CPU PyTorch wheel avoids downloading GPU runtime packages for this local service.
Related: Install Sentence Transformers with pip - Install the OpenSearch Python client in the active environment.
$ python -m pip install --upgrade opensearch-py
- Enter a strong initial OpenSearch admin password without echoing it to the terminal.
$ read -rsp 'OpenSearch admin password: ' OPENSEARCH_INITIAL_ADMIN_PASSWORD
The password must pass OpenSearch's strength check. It is read into a shell variable rather than written into source code or shell history.
- Export the password for Docker and the Python client.
$ export OPENSEARCH_INITIAL_ADMIN_PASSWORD
Docker administrators can still inspect container environment variables, and the demo admin user has full cluster privileges. This account is for the local demonstration, not an application account on a shared cluster.
- Check the Linux host's memory-map limit before starting OpenSearch.
$ sysctl vm.max_map_count vm.max_map_count = 1048576OpenSearch requires at least 262144 memory maps. If the value is lower, sudo sysctl -w vm.max_map_count=262144 raises it until reboot; the setting affects the Linux Docker host, not only the container. The value shown is already sufficient.
- Start a dedicated OpenSearch container bound to loopback.
The bundled certificates and other demonstration users are unsuitable for production. The 127.0.0.1 binding keeps this service's published port local; changing it to 9200:9200 exposes it on every host interface. The named volume keeps indexed data when the container stops, and deleting that volume would delete the index.
$ sudo --preserve-env=OPENSEARCH_INITIAL_ADMIN_PASSWORD docker run -d \ --name opensearch-vector-demo \ -p 127.0.0.1:9200:9200 \ -e discovery.type=single-node \ -e bootstrap.memory_lock=true \ -e 'OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m' \ -e OPENSEARCH_INITIAL_ADMIN_PASSWORD \ --ulimit memlock=-1:-1 \ --ulimit nofile=65536:65536 \ -v opensearch-vector-data:/usr/share/opensearch/data \ opensearchproject/opensearch:3.9.0
single-node avoids discovery of a second node. The 512 MiB JVM heap leaves room for native memory and the Python model on a small development machine; it is not a production sizing recommendation. Memory locking prevents that heap from being swapped. The Security plugin remains enabled. Startup can take a minute; a connection refusal during startup is different from an authentication error. If startup fails, sudo docker logs opensearch-vector-demo shows the cause. An existing container or volume with these names belongs to a previous service and must not be overwritten blindly.
- Copy the demonstration root certificate from the local container into the project.
$ sudo docker cp opensearch-vector-demo:/usr/share/opensearch/config/root-ca.pem ./opensearch-root-ca.pem
This is a public CA certificate, not a private key. It lets the Python client validate the server's certificate chain without disabling TLS verification.
- Create a file named build_opensearch_index.py in your text editor with the authenticated connection code.
- build_opensearch_index.py
import os from opensearchpy import OpenSearch, helpers from sentence_transformers import SentenceTransformer INDEX = "travel-docs-demo" client = OpenSearch( hosts=[{"host": "localhost", "port": 9200}], http_auth=("admin", os.environ["OPENSEARCH_INITIAL_ADMIN_PASSWORD"]), use_ssl=True, verify_certs=True, ca_certs="opensearch-root-ca.pem", timeout=60, ) print("OpenSearch:", client.info()["version"]["number"])
The Docker demo server certificate includes localhost, so the client checks both the hostname and its CA chain. For an existing secured service, the host, trusted CA, and account must match that service. A wrong password causes an authentication error rather than an anonymous connection.
- Append the sample documents and CPU embedding code after the connection code.
documents = [ {"id": "refund", "title": "Refund a cancelled train ticket", "text": "Request a refund for a cancelled rail journey and return the ticket payment."}, {"id": "booking", "title": "Change a train booking", "text": "Change the departure date or time of an existing train reservation."}, {"id": "bicycle", "title": "Carry a bicycle on a train", "text": "Reserve a bicycle space before taking your bike aboard the train."}, {"id": "cake", "title": "Bake a chocolate cake", "text": "Mix flour, cocoa and eggs, then bake the cake in an oven."}, ] model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cpu") vectors = model.encode_document( [doc["text"] for doc in documents], normalize_embeddings=True, show_progress_bar=False, ) dimension = vectors.shape[1] print("Embedding dimension:", dimension)
The first model load downloads public weights from Hugging Face. This model produces 384 values per document, but the mapping below takes the dimension from the actual encoded array. Its input limit is 256 word pieces, so longer source documents need chunking before ingestion.
- Append the vector index definition after the embedding code.
client.indices.create( index=INDEX, body={ "settings": { "index.knn": True, "number_of_shards": 1, "number_of_replicas": 0, }, "mappings": { "properties": { "title": {"type": "text"}, "text": {"type": "text"}, "embedding": { "type": "knn_vector", "dimension": dimension, "method": { "name": "hnsw", "engine": "lucene", "space_type": "cosinesimil", }, }, }, }, }, )
index.knn enables approximate k-NN indexing. Lucene HNSW supplies the graph index and cosinesimil compares vector direction. One shard and zero replicas suit a single-node development service. Index creation fails if travel-docs-demo already exists; it never deletes existing data. For a fresh run, a different unused INDEX name preserves the earlier index.
- Append the bulk ingestion code after the index definition.
indexed, _ = helpers.bulk( client, [ { "_index": INDEX, "_id": doc["id"], "_source": { "title": doc["title"], "text": doc["text"], "embedding": vector.tolist(), }, } for doc, vector in zip(documents, vectors) ], ) client.indices.refresh(index=INDEX) print("Indexed documents:", indexed) print("Stored documents:", client.count(index=INDEX)["count"])
The bulk helper raises an error if a document cannot be indexed, including a vector-length mismatch. Refresh makes the new documents searchable immediately instead of waiting for the normal refresh interval.
- Append the same-model query and result display after ingestion.
query = "How can I get my money back after my train was cancelled?" query_vector = model.encode_query( query, normalize_embeddings=True, show_progress_bar=False, ) response = client.search( index=INDEX, body={ "size": 2, "query": { "knn": { "embedding": {"vector": query_vector.tolist(), "k": 2}, }, }, "_source": ["title", "text"], }, ) print("Index:", INDEX) print("Query:", query) for rank, hit in enumerate(response["hits"]["hits"], start=1): print( f"{rank}. {hit['_id']} score={hit['_score']:.4f} " f"title={hit['_source']['title']}" )
The same model encodes both sides of the search. k requests two nearest neighbors, and size limits the returned hits to two. Excluding the embedding from _source keeps hundreds of vector values out of the displayed response.
- Save build_opensearch_index.py with all five code sections in their shown order.
- Run the completed OpenSearch indexing script. Example output:
$ python build_opensearch_index.py ##### snipped ##### OpenSearch: 3.9.0 ##### snipped ##### Embedding dimension: 384 Indexed documents: 4 Stored documents: 4 Index: travel-docs-demo Query: How can I get my money back after my train was cancelled? 1. refund score=0.8554 title=Refund a cancelled train ticket 2. booking score=0.7034 title=Change a train booking
The model download and loading messages are omitted. An unauthenticated Hugging Face Hub warning refers to download rate limits; this public model needs no sign-in. Both document counts should be 4, the dimension should be 384, and the first match should be refund. The query asks for money back without using the word “refund”; that ranking demonstrates semantic retrieval. The index and documents remain in the named volume for subsequent searches. Scores can vary slightly with package versions.