What is vector search?
Vector search uses machine learning (ML) to capture the meaning and context of unstructured data, including text and images, transforming it into a numeric representation. Frequently used for semantic search, vector search finds similar data using approximate nearest neighbor (ANN) algorithms. Compared to traditional keyword search, vector search can return more relevant results for queries that describe meaning or intent.
Why vector search matters
Keyword search can't serve queries that describe a meaning or an intent instead of exact keywords. Vector search overcomes this limitation, allowing you to search by what you mean. It finds what users mean, not what they typed, and that matters because most real-world queries, such as natural language questions, image lookups, and recommendation requests, are not exact keyword matches.
Vector search also supplies the retrieval step of modern AI workloads: They ground the answers of retrieval-augmented generation (RAG) in your own documents, find similar items for recommendations, flag anomalies whose vectors fall far from normal behavior, and retrieve images, audio, or video from a text query.
How vector search works
Vector search runs in three stages: embedding your data as vectors, indexing those vectors, and querying, which embeds each query with the same model and retrieves its nearest neighbors from the index.
Vector search engines—known as vector databases, semantic, or cosine search—find the nearest neighbors to a given (vectorized) query.
Each vector is a point in a high-dimensional space, and a distance metric, such as cosine similarity or Euclidean distance, measures how far apart two points are. The nearest neighbors of a query are the stored points closest to it. Elasticsearch finds them with k-nearest neighbor (kNN) search, which has two methods. Exact kNN checks every point, and approximate kNN, also called ANN, checks a promising subset to answer faster.
Where traditional search relies on mentions of keywords, lexical similarity, and the frequency of word occurrences, vector search engines use distances in the embedding space to represent similarity. Finding related data becomes searching for the nearest neighbors of your query.
Vector embeddings
Vector embeddings are the numeric representation of data and related context, stored in high-dimensional (dense) vectors: fixed-length arrays of floating-point numbers that a machine learning model produces to encode the semantic meaning of text, images, or audio. Similar concepts produce embeddings that are geometrically close, so the words "dog" and "puppy" sit closer together in embedding space than "dog" and "invoice." Models that generate embeddings can be trained on millions of examples to deliver more relevant and accurate results. Training on large corpora lets the numbers capture semantic relationships instead of surface form. For some cases, numeric data that you collected or engineered to represent key features of your documents can be used as embeddings. All you need is the ability to search efficiently. A vector database stores the embeddings, and queries must be embedded with the same model as the documents.
Measuring vector similarity
At the core of a vector search engine is the idea that if data and documents are alike, their vectors will be similar. By indexing both queries and documents with vector embeddings, you find similar documents as the nearest neighbors of your query.
Similarity is computed as the geometric distance or angle between two vectors. Most systems offer cosine similarity, dot product, or Euclidean distance:
- Cosine similarity: Measures the cosine of the angle between two vectors, from -1 (opposite directions) to 1 (identical direction). It is preferred for text embeddings because it is insensitive to vector magnitude, so two documents with different lengths but the same topic score the same.
- Euclidean (L2) distance: Measures the straight-line distance between two points, which suits dense numeric data.
- Dot product: Equivalent to cosine similarity for normalized vectors, and computationally efficient.
The metric used at query time must match the metric used when indexing, because the index organizes vectors by that metric.
Brute force vector search (exact kNN search)
Brute force vector search, also called exact kNN search, compares the query vector with every vector in the index and returns the true nearest neighbors. Because it scores every document, its results are fully accurate, but its latency grows with the size of the corpus. It suits small datasets, subsets that a filter has already narrowed down, and cases that need precise scores. In Elasticsearch, you run it with the dense_vector query or a script_score query.
Approximate nearest neighbor search and HNSW
A kNN search returns the k stored vectors closest to a query vector under a chosen distance metric. Exact kNN search compares the query against every stored vector, so its cost scales linearly with corpus size. ANN, or approximate kNN, sacrifices perfect accuracy in exchange for executing efficiently in high-dimensional embedding spaces at scale. In approximate nearest neighbor search, a family of algorithms finds vectors approximately closest to a query vector by searching a subset of the index, trading a small, tunable reduction in recall for large gains in query latency and throughput.
The common index structure is Hierarchical Navigable Small World (HNSW), a graph-based ANN algorithm that organizes vectors into layers of similarity-connected nodes, each a navigable small-world network. A search enters at a sparse top layer with long-range connections and descends through progressively denser layers, pruning the search space at each step, to reach approximate nearest neighbors in sub-linear time. The key tradeoff is recall against latency, which you tune with parameters such as efSearch or num_candidates. Elasticsearch, the search database for AI, uses HNSW, or, when memory is limited, DiskBBQ, a disk-based alternative that groups vectors into clusters.
Read more about understanding how ANN algorithms work, or see the kNN search reference.
Benefits of vector search
Vector search improves search in four ways:
- More relevant results: It matches meaning, so results fit the intent of a query even when they share no words with it.
- Multimodal and multilingual search: Text, images, audio, and video can share one embedding space, and multilingual models place a query and a document in different languages close together.
- Scalability: Approximate nearest neighbor indexes, vector compression, and distributed clusters keep queries fast as collections grow to millions of vectors.
- Tolerance of vague queries: People can describe what they need in their own words, with partial or imprecise terms, and still find it.
Vector search vs. keyword search
Keyword search matches tokens, and vector search matches meaning. A keyword search for "canine" misses a page about a "puppy," because the words differ, while vector search ranks it near the top because "dog," "puppy," and "canine" have embeddings that sit close together. Keyword engines typically rank results with BM25, a probabilistic relevance function that builds on term frequency-inverse document frequency (TF-IDF), which weights a term by how often it appears in a document and how rare it is across the corpus. BM25 is the default ranking algorithm for lexical retrieval in Elasticsearch. Vector search ranks results by vector similarity, such as the cosine similarity between the query and each document.
Hybrid search is a retrieval technique that runs both in parallel, then fuses their ranked lists with an algorithm such as Reciprocal Rank Fusion (RRF). The result is a single relevance-ordered set that benefits from exact matching and semantic understanding, with BM25 as one of its two retrieval signals.
Keyword search vs. vector search vs. hybrid search: Each retrieval method suits a different kind of query. Keyword search is the better choice when you know the exact terms, vector search works well when a query describes a concept or intent, and hybrid search is best for queries that combine the two. The following table compares each method's matching logic, what it finds, and when to use it.
| Matching logic | What it finds | Best when | |
|---|---|---|---|
| Keyword (BM25/TF-IDF) | Exact terms, scored by frequency | Documents that contain the query's words | You know the exact terms, identifiers, or names |
| Vector | Similarity between embeddings | Documents with the same meaning, whatever the wording | Queries describe a concept or intent |
| Hybrid | Both, with ranked lists fused | Exact matches and semantic matches in one list | Queries mix intent with specific terms |
Vector search can lead to natural language questions: In a 2020 study by Karpukhin et al., Dense Passage Retrieval beat a strong BM25 system by 9 to 19 percentage points in top-20 passage retrieval accuracy on open-domain question answering.
Keyword search still wins for exact identifiers such as SKUs, order numbers, and proper names, for highly controlled vocabularies, and when you have to explain why a result matched. BM25 also holds up on new domains: The BEIR benchmark, published in 2021, tested retrieval on domains the systems weren't trained on, across 18 datasets, and found that "BM25 is a robust baseline."
To get both, use hybrid search, which combines the two retrieval methods in a single query through RRF.
Vector search vs. semantic search
Vector search is a technique that compares numerical vectors to find the closest matches, and semantic search is the goal of returning results that match the meaning of a query. Most semantic search runs on vector search, using dense or sparse embeddings of text. Vector search also goes beyond text: It finds similar images, audio, and other data, which isn't semantic text search.
Vector search in RAG and AI pipelines
Vector search is the retrieval layer in retrieval-augmented generation (RAG), an AI architecture pattern that retrieves relevant document chunks from an external knowledge base and passes them to a large language model (LLM) to generate a grounded, factually constrained response. The flow has three steps:
- Ingest: Documents are chunked and embedded into a vector index.
- Retrieve: At query time, the user's question is embedded and its nearest neighbors are retrieved.
- Generate: The retrieved chunks are passed to the LLM as context, grounding the response in trusted data and reducing hallucination.
For example, an internal support chatbot that gets the question "How do I rotate my API keys?" embeds it, retrieves the closest chunks from the security documentation, and passes them to the LLM, which answers from those passages and can cite them.
Chunking is a practical consideration: Large documents are split into smaller chunks so that each embedding represents a coherent unit of meaning. Smaller chunks keep each embedding focused, and a small overlap between chunks keeps a sentence that crosses a boundary in one piece. Top-k, the number of chunks you retrieve, is the other choice: Retrieving more chunks raises the chance that the answer is among them, and retrieving fewer keeps the prompt short and focused. The same pattern applies to AI agents that retrieve memory or knowledge across turns.
With ES|QL, the Elasticsearch Query Language, you can run the retrieve and generate steps as one piped query. TEXT_EMBEDDING turns the question into a vector, KNN retrieves the nearest chunks, and RERANK reorders them. STATS gathers the best chunks into one context, and COMPLETION sends that context and the question to an LLM.
To go hands-on, build a RAG pipeline with Elasticsearch.
Vector search use cases
Vector search applies wherever you need to find items by similarity. A streaming service suggests shows close to what a viewer just watched, a legal team finds earlier cases that describe the same situation in different words, and a photo library returns pictures that match a sentence. When to use vector search
Vector search favors queries that describe a meaning: natural language questions, descriptions of a product or a problem, searches with an image, and requests for similar items.
Semantic search
Semantic search returns results that match the meaning of a query instead of its exact keywords. It uses vector search to represent queries and documents as vectors, or embeddings, compare them by similarity, and return the closest matches. Vector search powers semantic search and similarity search, which find documents by meaning, not by keyword overlap. Since the meaning and context are captured in the embedding, vector search finds what users mean without requiring an exact keyword match, so a query like "running shoes for flat feet" can surface results that say "orthopedic sneakers" without a single shared word. It works with textual data (documents), images, and audio.
Image and video vector search
Image and video vector search finds pictures and videos by what they show. A multimodal embedding model, such as CLIP or a Jina multimodal model, maps images and text into the same embedding space, so you can search with a sentence like "red bicycle on a beach" and get matching photos, or search with an image and get visually similar ones. Video is usually split into frames or short clips, and each one is embedded separately, so a query can return the right moment in a longer video.
Recommendations
The model that generates the embedding learns to recognize similar documents and their vectors in the embedding space. For example, an application may recommend movies or products that others who purchased the one you bought also liked.
Vector distances can be combined with other metrics so that recommendations achieve multiple goals. For example, rank product recommendations by satisfaction scores and revenue potential.
Recommendations use two kinds of embeddings. Item embeddings place similar products, articles, or videos close together, and user embeddings represent what a person has viewed or bought, so the items closest to a user's vector are the best candidates. Because a new item's embedding comes from its own text or image, you can recommend it before anyone has rated, bought, or tagged it, which addresses the cold-start problem. An online store can suggest products similar to the one in a shopper's cart, and a media service can suggest articles or videos close to what a reader just finished.
Question answering
Converting documents to text embeddings can be combined with modern natural language processing (NLP) to deliver full text answers to questions. This approach spares users from studying lengthy manuals and empowers your teams to provide answers more quickly.
A "question answering" transformer model can take the text embedding representation for both the knowledge base of documents and your current question to deliver the closest match as an "answer."
Improving vector search relevance
Production systems layer several techniques on top of raw nearest-neighbor retrieval to improve precision, recall, and ranking. Raw results reflect vector distance alone, so relevance optimization adds more data types, metadata filters, extra ranking signals, and keyword matching.
Browse unstructured data
Search any unstructured data. You can create embeddings for text, images, audio, or sensor measurements.
Filter on metadata
Filter vector search results using metadata. Maintain recall without sacrificing speed by applying a filter in line with approximate nearest neighbor (ANN) search.
Re-rank search results
Vector similarities can be interpreted as similarity scores that you can re-rank with other data. That includes static fields already in your vector search database, and new properties by applying machine learning models.
Hybrid search
To further optimize, run a keyword retrieval (BM25) and a vector retrieval in parallel, then fuse their ranked lists using RRF to return one relevance-ordered result set. Hybrid search wins over pure vector search on queries that mix natural language intent with exact identifiers, such as "comfortable running shoes, Nike Air Zoom size 10. " BM25 retrieves the exact model name, while the vector retrieval handles the description of comfort. For the full treatment, read about hybrid search.
Deploying vector search in production
You can run vector search in three main ways, and each handles indexing, scaling, and updates differently:
- Vector libraries, such as FAISS: Fast in-memory indexes that your application builds and manages. You handle storage, replication, and scaling yourself, and some index types need a rebuild to take in new data.
- Dedicated vector databases: Managed services that store and scale vectors for you. They usually run beside your primary database, so every change has to be copied to both.
- Database extensions, such as pgvector for PostgreSQL: Vector columns added to a database you already run. They are simple to adopt, and they scale with that database.
A search database such as Elasticsearch stores vectors, text, and metadata in one index, updates them as documents change, and scales out with shards and replicas.
How to get started with vector search
Every vector search project needs three things: an embedding model that fits your data and languages, an index that supports nearest neighbor search, and the same model to embed each query at search time. Start with a small set of real queries, so you can check relevance before you scale.
To build vector search in Elasticsearch, follow four steps:
- Pick an embedding model: A semantic_text field uses a default Jina model on Elastic Inference Service in Elastic Cloud, or you can set another inference endpoint.
- Install a client library: For Python, run pip install elasticsearch. You can also send the requests from Kibana Dev Tools.
- Generate vectors: Map a semantic_text field and index your documents: Elasticsearch generates and stores the embeddings at ingest.
- Run a similarity query: A semantic query embeds the question with the same model and returns the closest documents.
PUT /my-articles
{
"mappings": {
"properties": {
"body": { "type": "semantic_text", "inference_id": ".jina-embeddings-v5-text-small" }
}
}
}
POST /my-articles/_doc?refresh=true
{
"body": "Dogs need daily walks, regular vet visits, and a balanced diet."
}
GET /my-articles/_search
{
"query": { "semantic": { "field": "body", "query": "how to care for a puppy" } }
}The search returns the document about dogs first, even though it shares no words with the query.
Vector search with Elasticsearch
Teams use vector search in Elasticsearch for e-commerce search that matches shoppers’ descriptions to products, customer support search that finds answers in help articles, and the retrieval behind RAG applications and AI agents.
Elasticsearch, Elastic's distributed search and analytics engine and the search database for AI, gives you native dense_vector fields indexed with HNSW, sparse_vector fields, and semantic_text for automated embedding generation. ELSER (Elastic Learned Sparse Encoder), Elastic's proprietary sparse NLP model, gives you sparse vector search for out-of-the-box semantic retrieval by expanding query and document text into weighted sets of semantically related terms, without dense vector embeddings or fine-tuning. With the RRF retriever, you combine vector and keyword results in one hybrid query.
To start, define a dense_vector field, generate embeddings with an inference endpoint or external model, and query with kNN: Try the Elasticsearch vector database, or see the vector search docs and the kNN search reference, then build on it with Elastic Agent Builder.