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.

Power your search experiences with vector search.


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.

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.


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:

  1. Ingest: Documents are chunked and embedded into a vector index.
  2. Retrieve: At query time, the user's question is embedded and its nearest neighbors are retrieved.
  3. 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.

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.

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.


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.