What Is Semantic Search in Elasticsearch?

What Is Semantic Search in Elasticsearch?

Semantic search finds results by meaning instead of by exact words. This guide explains embeddings, vector search, ELSER, the semantic text field, hybrid search, reranking, and how to run all of it safely and affordably in production.

Imagine you walk into a library and ask the librarian, “Do you have anything about keeping my house warm without spending much?” A keyword-matching helper would hunt for books with the exact words “keeping”, “house”, and “warm”, and would probably miss a wonderful book titled “Cheap Ways to Insulate Your Home”. A librarian who understands meaning would walk straight to that book, because she knows that keeping a house warm and insulating a home are the same idea. Semantic search gives Elasticsearch that second kind of librarian.

1What Is Semantic Search?

Semantic search is a way of searching where the engine tries to understand what you mean, not only which words you typed.

The word semantic comes from the study of meaning. In classic search, the engine compares the letters and words of your question with the letters and words in documents. If they match, the document is a candidate. In semantic search, the engine compares the meaning of your question with the meaning of documents. Two texts can share no words at all and still be judged very close, because they talk about the same idea.

Elasticsearch has always been excellent at the first kind of search, which is called lexical search. Over the last few years it has added many features for the second kind: fields that store meaning as numbers, models that turn text into those numbers, fast search over them, and ways to blend both kinds of search into one result list. This guide walks through all of it in simple steps.

Simple Analogy

Think of two ways to find a friend in a crowded railway station. In keyword search, you shout the friend’s exact name and hope she hears it. In semantic search, you describe her: “tall, wearing a red scarf, carrying a blue bag”, and people who saw someone like that can point you in the right direction, even if they never heard her name.

i
One Sentence Summary

Semantic search turns text into numbers that capture meaning, then finds the documents whose numbers are closest to the question’s numbers.

2The Problem: Words Are Not Meaning

People say the same thing in many ways. Search that only sees words is easily fooled.

Human language is full of synonyms, different phrasings, spelling styles, and context. A customer may search for “cheap phone with good battery” while the product page says “budget smartphone, long-lasting power”. Almost no words match, yet the product is exactly what the customer wants. This gap between how people ask and how documents are written is called the vocabulary mismatch problem.

The opposite problem also exists. One word can have several meanings. A search for “jaguar speed” could mean the animal or the car. Keyword search returns both, because the word is the same, and it cannot tell which one you care about.

What the User TypesWhat the Document SaysKeyword SearchSemantic Search
how to fix a leaking tapRepairing a dripping faucetMisses it, no shared wordsFinds it, same meaning
laptop for studentsNotebook computers for collegeMisses itFinds it
my bank card is stuck in the ATMWhat to do when a machine retains your debit cardWeak matchStrong match
jaguar speedTop speed of the jaguar cat in the wildMatches by word onlyUses the surrounding meaning
Simple Analogy

A tourist asks for “the place where trains come and go”. A person who only matches words looks for a sign that says exactly that. A person who understands meaning says, “Ah, the railway station,” and points the way.

Older tricks tried to reduce the gap: synonym lists, stemming, spelling correction, and hand-written rules. They help, but they need constant human work, and they never cover everything. Semantic search attacks the root of the problem instead.

3A Quick Look at How Keyword Search Works

To appreciate semantic search, we should remember what the traditional approach does well.

When you index a document, Elasticsearch breaks the text into small pieces called tokens, usually words. It builds an inverted index, which is like the index at the back of a textbook: for each word, a list of documents that contain it. When you search, the engine finds the documents that contain your words and then scores them using a formula called BM25.

BM25 gives a higher score when your words appear more often in a document, when the words are rare across all documents, and when the document is short. Rare words such as “photosynthesis” matter more than common words such as “the”. This approach is fast, cheap, transparent, and very precise for exact terms.

Strengths of Keyword Search

  • Very fast and light on memory
  • Excellent for exact names, codes, and identifiers
  • Easy to explain why a result matched
  • No machine learning model is needed
  • Supports highlighting, filters, and aggregations naturally

Weaknesses of Keyword Search

  • Cannot bridge vocabulary differences
  • Ignores context and word order meaning
  • Struggles with long, natural language questions
  • Needs manual synonym and rule maintenance
i
Keep It

Semantic search does not replace keyword search. The best systems use both, and Elasticsearch is designed to let you combine them.

4Meaning as Numbers: Embeddings

The central idea of semantic search is the embedding. Everything else in this guide is built on it.

An embedding is a list of numbers, called a vector, that represents the meaning of a piece of text. For example, a sentence might become a list of 384 or 768 numbers. A machine learning model, trained on huge amounts of text, decides what those numbers should be. The training teaches the model that texts with similar meanings should produce similar lists of numbers.

You never need to read the numbers yourself. What matters is the relationship: if two texts mean nearly the same thing, their numbers will be close to each other. If they mean very different things, their numbers will be far apart.

flowchart LR
  T1["Text: repairing a dripping faucet"] --> M["Embedding model"]
  T2["Text: how to fix a leaking tap"] --> M
  T3["Text: history of the Roman empire"] --> M
  M --> V1["Vector A: 0.21, -0.43, 0.88 and more"]
  M --> V2["Vector B: 0.20, -0.41, 0.90 and more"]
  M --> V3["Vector C: -0.75, 0.32, 0.10 and more"]
        
FIG 1 — A model turns each text into a vector, and similar texts get similar vectors

In the picture, vectors A and B are almost the same because the two texts describe the same task. Vector C is very different because it is about something else. Searching then becomes a simple question: which stored vectors are closest to the vector of the question?

Simple Analogy

Every city has a latitude and longitude, two numbers that place it on the map. Cities close to each other have similar numbers. An embedding is like a set of coordinates for meaning, only with hundreds of numbers instead of two.

5The Map of Meaning: Vector Space

If you could see all embeddings at once, related ideas would form neighborhoods.

Imagine a huge invisible map where every sentence has a location. Sentences about cooking gather in one region. Sentences about football gather in another. Sentences about banking are in a third. A question about “boiling pasta” lands in the cooking region, so the closest documents are recipes and kitchen tips, even if none of them uses the word “boiling”.

This map has many more than two directions. Each of the hundreds of numbers is one direction. Humans cannot picture that, but computers handle it easily, and the same ideas of “near” and “far” still work.

flowchart TD
  Q["Question: how long to boil pasta"] --> N{"Nearest neighbors in vector space"}
  N --> D1["Recipe: cooking spaghetti"]
  N --> D2["Guide: al dente timing"]
  N --> D3["Tips: salting water"]
  N -.->|"far away"| D4["Article: stock market news"]
        
FIG 2 — The closest neighbors of a question are the documents with the most similar meaning

Neighborhoods Form Automatically

Nobody draws the regions by hand. The model learned from data where ideas belong. This is why semantic search works across topics without special rules for each one.

Distance Means Difference

The further two vectors are apart, the less related the texts are. Search results are simply the nearest points to the question.

Because the map is built once and reused, adding a new document just means placing a new point on it. The rest of the map does not change.

6Measuring Closeness: Similarity Metrics

To find the nearest neighbors, the engine needs a way to measure how close two vectors are.

Elasticsearch supports a few standard measures. Each turns two vectors into a single similarity number. The right choice depends on how the embedding model was trained, so the model’s documentation should guide you.

MeasureIdea in Simple WordsWhen to Use
Cosine similarityCompares the direction the vectors point, ignoring their lengthVery common default for text embeddings
Dot productMultiplies matching numbers and adds them up; longer vectors score higherWhen the model was trained for it, and vectors are normalized
Euclidean distanceThe straight-line distance between the two pointsWhen absolute position matters, less common for text
Maximum inner productA dot product that allows unnormalized vectorsFor models that need it, such as some recommendation models
Simple Analogy

Two people pointing their fingers in almost the same direction agree on where to look, even if one has a longer arm. Cosine similarity checks whether the fingers point the same way. Euclidean distance instead measures how far apart the fingertips are.

!
Match the Model

Use the similarity measure that the embedding model recommends. Using the wrong one can quietly reduce result quality, and nothing will show an error.

Elasticsearch converts these measures into a positive score so that higher always means better, which lets vector results be shown and combined like any other search result.

7Where Do Embeddings Come From?

A trained model creates them. Choosing that model is the most important quality decision you will make.

Embedding models are neural networks, usually of the transformer kind, trained on large collections of text. Given a piece of text, the model outputs its vector. Models differ in the size of the vector they produce, the languages they know, the length of text they can read, the domains they were trained on, and the computing power they need.

Choice 1

Model Built Into Elastic

Elastic offers models that run inside the cluster on machine learning nodes, such as ELSER for English and multilingual embedding models. No data leaves your cluster.

Choice 2

Hosted Third-Party Service

Services from AI providers create embeddings through an online interface. Elasticsearch can call them for you, but your text travels to that provider.

Choice 3

Open Model You Import

You can bring a compatible open model and run it in your own cluster, choosing one that fits your language or domain.

Choice 4

Vectors Made Outside

Your own pipeline may create the vectors and send them in already computed. Elasticsearch then only stores and searches them.

What to look for in a model

First, the language: a model trained mostly on English text will do poorly on Hindi or Japanese. Second, the maximum text length: most models read a limited number of tokens, so long documents must be cut into pieces. Third, the vector size: bigger vectors can hold more detail but cost more storage and time. Fourth, the domain: a model trained on general web text may not understand legal or medical language well. Finally, cost and speed: larger models are slower and need stronger hardware.

i
Golden Rule

The same model must be used to embed both the documents and the questions. Vectors from different models live on different maps and cannot be compared.

8Dense Vectors and Sparse Vectors

Elasticsearch supports two very different shapes of embedding. Knowing both prevents a lot of confusion.

A dense vector is a fixed-length list of numbers where almost every position holds a value, such as 768 numbers. Each position has no human meaning by itself. The meaning lives in the pattern of all numbers together. Dense vectors are searched with nearest neighbor search.

A sparse vector is a very long list where almost all positions are zero and only a few hundred carry weights. In the sparse approach used by Elastic’s own model, each position stands for an actual word or word piece. The model expands a text into related words with weights. A text about “cheap phones” might get weight on words such as “budget”, “smartphone”, “affordable”, and “mobile”, even though those words were never written. Sparse vectors are searched using the same inverted index technology as keyword search.

PointDense VectorsSparse Vectors
ShapeFixed length, almost all values non-zeroVery long, mostly zeros, few weighted terms
Meaning of each positionNo single meaningA word or word piece
Field typedense_vectorsparse_vector
Search methodNearest neighbor search on a graphInverted index style scoring
ExplainabilityLow, numbers are hard to readHigher, you can see which terms matched
StorageFull vector per document, memory heavyOnly non-zero terms stored
Typical modelEmbedding models such as multilingual E5 or third-party modelsELSER
Simple Analogy

A dense vector is like a smoothie: all flavors are blended together and you cannot pick out the strawberry. A sparse vector is like a fruit plate: you can see each fruit and how much of it there is.

9The Building Blocks in Elasticsearch

Here is the toolbox. Each block will get its own chapter, so treat this as a map of what is coming.

Field Type

dense_vector

Stores a fixed-length vector per document and supports nearest neighbor search on it.

Field Type

sparse_vector

Stores weighted terms produced by a sparse model like ELSER and supports queries over them.

Field Type

semantic_text

The simplest option: you supply plain text, and Elasticsearch creates embeddings, splits long text, and stores everything for you.

Service

Inference API

A single place to create and manage endpoints for models, whether built in, imported, or hosted elsewhere.

Search

kNN Search

Finds the k nearest vectors to a query vector, either exactly or approximately with a graph.

Search

Retrievers

A pipeline style way to describe search: get candidates, combine them, and rerank them.

Ranking

Hybrid and RRF

Blends keyword and semantic results into a single list using rank based fusion.

Ranking

Semantic Reranking

Uses a stronger model to reorder the top results for better precision.

!
Version Note

Elasticsearch adds and renames features in this area quickly. Names, defaults, and license levels differ between versions, so always check the documentation of the version you run before you build on a specific feature.

10Architecture and Components

A semantic search system has a few moving parts. Seeing them together shows how they cooperate.

flowchart TD
  APP["Application"] --> CO["Coordinating node"]
  CO --> ING["Ingest node: pipelines and inference"]
  ING --> ML["Machine learning node or external model service"]
  ML --> ING
  ING --> DN["Data nodes: shards with text, vectors and HNSW graphs"]
  CO --> DN
  CO -.->|"embed the question"| ML
  DN --> CO
  CO --> APP
        
FIG 3 — Text is embedded at ingest time and at query time, and shards hold both text and vectors

Model Runtime

Machine learning nodes host models inside the cluster, or the inference API calls an outside service. Either way, this is the place that turns text into vectors.

Ingest Side

When documents are indexed, their text passes through an ingest step, or a semantic text field, that asks the model for vectors before the data is stored.

Storage Side

Data nodes hold the original text, the vectors, and the search structures. For dense vectors, this includes a graph of neighbors for each segment.

Query Side

At search time, the question is embedded with the same model, and the resulting vector is used to find near neighbors on each shard. Results are merged like any other search.

Because the model is used twice, once for documents and once for each user question, the model’s speed and availability affect both indexing speed and search latency.

11The Inference API and Endpoints

The inference API gives every model the same simple front door, no matter where the model lives.

An inference endpoint is a named connection to a model. You create it once, telling Elasticsearch which task it performs, such as producing dense embeddings, producing sparse embeddings, or reranking, and which service provides it. After that, other features refer to the endpoint by name and do not care how the model is run.

Task TypeWhat the Endpoint DoesUsed By
Text embeddingReturns a dense vector for a textdense_vector pipelines, semantic_text
Sparse embeddingReturns weighted terms for a textsparse_vector, semantic_text with ELSER
RerankScores how well each document answers a queryReranking retrievers
CompletionGenerates text from a promptApplications that add answer generation

The benefit is flexibility. You can start with an endpoint that runs a model inside your cluster, and later switch to a hosted provider, or the other way around, by changing the endpoint and re-embedding. Your search definitions can stay much the same.

i
Default Endpoints

Recent versions provide ready-made default endpoints for Elastic’s own models, so that a semantic text field can work without any manual model setup. Check the documentation for the names and the license needs in your version.

!
Secrets

Endpoints for outside providers need an API key. Elasticsearch stores such keys as secret settings and does not show them again in responses. Treat them like passwords and rotate them on a schedule.

12ELSER: Elastic’s Sparse Model

ELSER is a model made by Elastic for semantic search that works well without any tuning.

ELSER stands for Elastic Learned Sparse EncodeR. It is a sparse model for English text. It reads a document and produces a set of weighted terms that describe it, including terms that were never in the original text. For example, a paragraph about a car engine might get weight on “motor”, “vehicle”, and “mechanic”. At query time, the question is expanded in the same way, and matching is done between the expanded terms.

Because the output is a list of real words with weights, it fits neatly into the same inverted index technology that powers keyword search. That makes it fast, reasonably cheap in memory, and easier to understand than dense vectors, since you can inspect which terms contributed to a match.

sequenceDiagram
  participant D as Document text
  participant E as ELSER model
  participant I as Index
  D->>E: cheap budget phone with long battery
  E->>I: Weighted terms: phone, cheap, budget, smartphone, battery, power, affordable, mobile
  Note over I: Stored as a sparse vector using the inverted index
        
FIG 4 — ELSER expands text into related weighted terms, including terms that were never written

Why Teams Like ELSER

  • Good relevance out of the box, no training or tuning needed
  • Runs inside your cluster, so text does not leave it
  • Uses inverted index structures, with modest memory needs
  • Matches can be inspected by looking at terms

Things to Consider

  • Designed for English text, so other languages need other models
  • Needs machine learning nodes and enough processing power
  • Requires a paid subscription level in most versions
  • Indexing is slower than plain keyword indexing, since every text passes through the model
Simple Analogy

ELSER is like a helpful assistant who, before filing a document, writes extra keywords on the cover: not only the words in the document, but also related words that people might use when searching for it.

13Dense Embedding Models

Dense models are the most widely used family of embedding models, and they cover many languages and domains.

A dense embedding model reads text and outputs a fixed-length vector. Popular families include the E5 models, which have multilingual versions, and the many models offered by AI providers. Elasticsearch can run some of these inside the cluster, and can call the others through the inference API.

Multilingual Search

A multilingual dense model can map text of many languages into the same map of meaning. A question in Hindi can then find a matching document written in English, because the meaning lands in the same neighborhood.

Domain Fit

If your documents use special vocabulary, such as medical or legal text, look for a model trained or fine-tuned for that area, and test it against your own questions.

Size and Speed Trade-Off

Small models are fast and cheap, but capture less nuance. Large models are more accurate but slower and more expensive, and they produce bigger vectors that need more storage.

Vector SizeBytes per Vector (32-bit floats)Typical Feel
384 numbers1,536Small and fast models
768 numbers3,072Common mid-size models
1,024 numbers4,096Larger, more accurate models
1,536 numbers6,144Large hosted models
i
Test On Your Own Data

Public leaderboards are a good starting point, but the best model is the one that ranks your real questions best. Always run a small experiment with your own documents.

14The dense_vector Field

This is the field type that stores dense embeddings and makes them searchable.

When you define a dense_vector field in a mapping, you set a few things. The number of dimensions must equal the size of the vectors your model produces. The similarity measure tells the engine how to compare vectors. And the index options choose how vectors are stored and searched, including whether a graph is built and whether the numbers are compressed.

Setting

Dimensions

Must match the model exactly. A mismatch causes indexing errors, and there is an upper limit on how large it can be.

Setting

Similarity

Cosine, dot product, or Euclidean distance, chosen to match the model’s training.

Setting

Index Options

Choose the graph settings and the storage form, such as full precision or compressed vectors.

Setting

Indexed or Not

If a field is only used for exact scoring in a script, it does not need a graph. If it is used for fast nearest neighbor search, it must be indexed.

!
Cannot Change Later

The dimension count of an existing field cannot be changed. If you switch to a model with a different vector size, you must create a new index and re-embed your data. Plan for this before loading millions of documents.

Also note that vectors take room. In many recent versions, the raw vector values are left out of the returned source by default, so that responses stay small, while the vectors are still stored and searchable. If you need them back, there are options to retrieve them explicitly.

15The semantic_text Field: The Easy Path

If you want semantic search without plumbing, semantic text is the feature designed for you.

A semantic_text field hides the technical steps. You declare the field and, optionally, the inference endpoint. Then you simply index normal text into it. Elasticsearch takes care of splitting long text into chunks, calling the model for each chunk, and storing the resulting vectors in the right form, whether sparse or dense. At search time, you use a semantic query on the field with a plain text question, and Elasticsearch embeds the question with the same endpoint.

1

Declare the Field

Add a semantic text field to the mapping, and pick an inference endpoint or accept the default one.

2

Index Plain Text

Send documents as usual. The text goes to the field like any other text.

3

Automatic Embedding

Behind the scenes, the text is split into chunks, sent to the model, and stored with its vectors.

4

Search With a Question

Use a semantic query with the question text. Elasticsearch embeds it and finds the closest chunks.

TaskManual ApproachWith semantic_text
Choose and call a model at ingestBuild an ingest pipeline with an inference stepAutomatic
Split long textWrite your own chunking logicAutomatic chunking
Map vectors to the right field typeDefine dense or sparse fields and their optionsHandled for you
Embed the question at searchProvide a query vector or a vector builderJust send text
i
When to Prefer Manual Control

Choose the manual dense or sparse field route if you need to control chunk sizes yourself, provide vectors created elsewhere, or tune graph options carefully. Choose semantic text when you want the fastest and simplest path to good results.

16Chunking: Cutting Long Text Into Pieces

Models can only read a limited amount of text at once. Long documents must be cut into chunks.

Every embedding model has a maximum input length, measured in tokens, which are small pieces of words. Many models handle a few hundred tokens. If you feed a whole book chapter into such a model, it either refuses or quietly reads only the beginning and ignores the rest. Your search would then miss anything that appears later in the document.

The cure is chunking: splitting the document into smaller passages, embedding each passage separately, and searching over the passages. When a question matches a passage, the engine can return the parent document, and often the exact passage that matched, which is very useful for showing snippets or feeding answer generation.

flowchart TD
  DOC["Long document"] --> C1["Chunk 1"]
  DOC --> C2["Chunk 2"]
  DOC --> C3["Chunk 3"]
  C1 --> E1["Vector 1"]
  C2 --> E2["Vector 2"]
  C3 --> E3["Vector 3"]
  Q["Question vector"] -.->|"closest"| E2
  E2 --> R["Return document and best chunk"]
        
FIG 5 — Each chunk gets its own vector, and the closest chunk decides how the document ranks

Chunk Size

Chunks that are too small lose context, so a sentence about “it” no longer says what “it” is. Chunks that are too large blur many topics into one vector and reduce accuracy. A few hundred words is a common starting range, but the best size depends on your content.

Overlap

Letting neighboring chunks share a few sentences helps to avoid cutting an idea in half at the boundary.

Respect Structure

Where possible, cut at natural boundaries such as paragraphs and headings instead of at a fixed number of characters.

Simple Analogy

To make a book searchable, you would not stick one label on the whole book. You would label each chapter and section, so that someone looking for a recipe is sent to the right page, not just to the right shelf.

17Data Flow at Index Time

Let us follow one document from the moment it arrives to the moment it is searchable by meaning.

sequenceDiagram
  participant App as Application
  participant Co as Coordinating Node
  participant In as Ingest or Field Logic
  participant Mo as Model
  participant Sh as Shard
  App->>Co: Index a document with text
  Co->>In: Run ingest steps or semantic field logic
  In->>In: Split long text into chunks
  In->>Mo: Ask for embeddings of each chunk
  Mo->>In: Return vectors
  In->>Sh: Store text, vectors and metadata
  Sh->>Sh: Add vectors to the search graph at refresh and merge
  Sh->>App: Document is searchable
        
FIG 6 — Embedding happens before storage, so the model speed limits indexing throughput

What this means in practice

Indexing semantic data is slower than indexing plain text. Each chunk needs a model call, and the model may run on a machine learning node that has limited capacity. Bulk indexing at full speed can fill the model’s waiting line and cause rejections. Plan your indexing rate around the model throughput, not only around disk and network.

The search structures for dense vectors are also built during segment creation and merging, which uses extra processor time. A big initial load can keep merges busy for a long while after the last document arrives.

i
Load Smart

For a large first load, use moderate bulk sizes, add several model allocations, and consider a longer refresh interval during the load. Then return to normal settings and let merges finish before measuring search speed.

18Data Flow at Query Time

Now the reverse: a user types a question and expects the right documents back in a fraction of a second.

sequenceDiagram
  participant U as User
  participant Co as Coordinating Node
  participant Mo as Model
  participant Sh as Each Shard
  U->>Co: Question in plain text
  Co->>Mo: Embed the question
  Mo->>Co: Question vector
  Co->>Sh: Find nearest vectors, filtered if needed
  Sh->>Co: Top candidates per shard
  Co->>Co: Merge candidates from all shards
  Co->>U: Ranked results
        
FIG 7 — The question is embedded first, then each shard finds its nearest vectors, and results are merged

The extra step compared with keyword search is the model call for the question. It is one short text, so it is fast, but it still adds time, often tens of milliseconds for a local model and more for a remote service that is reached over the internet. It also creates a dependency: if the model service is down, semantic queries fail even though the index is healthy.

Cache Repeated Questions

Many searches repeat, especially popular ones. Caching the question vector or the final answer in your application avoids repeated model calls and keeps latency low.

Provide Your Own Vector

If your application already computes the question embedding, you can pass the vector directly, which skips the model call inside Elasticsearch.

!
Fallback Plan

Decide what should happen if the model is slow or unavailable. A common choice is to fall back to plain keyword search, so users still get results instead of an error.

19Exact Versus Approximate Nearest Neighbor Search

There are two ways to find the nearest vectors. One is perfect but slow, and the other is nearly perfect but fast.

Exact search, also called brute force, compares the question vector with every stored vector and keeps the best. It always finds the true nearest neighbors. But its cost grows with the number of vectors, so it is only practical for small sets, or when a filter has already reduced the candidates to a small number.

Approximate nearest neighbor search, shortened to ANN, uses a clever structure to visit only a small part of the vectors. It may miss a true neighbor once in a while, but it is much faster, even for millions of vectors. In Elasticsearch, ANN search uses a graph structure called HNSW, which comes from the Lucene engine.

PointExact SearchApproximate Search
AccuracyPerfectVery high, tunable, not perfect
Speed on millions of vectorsSlowFast
Extra structuresNoneA graph for each segment
Best forSmall sets or heavily filtered setsLarge collections
Simple Analogy

Finding the nearest ATM by checking every ATM in the country is exact but silly. Asking a local person, who points you towards the closest cluster of them, is approximate, and you will almost always reach a very near one in a few minutes.

i
Accuracy Is Called Recall

In this field, the share of true nearest neighbors that the approximate search finds is called recall. A recall of ninety-five percent means it found nineteen of every twenty true neighbors. You can tune the balance between recall and speed, as we will see.

20How the HNSW Graph Works

HNSW is the engine of fast vector search. Its idea is simple and beautiful.

HNSW stands for Hierarchical Navigable Small World. Every vector becomes a node in a graph, and each node is connected to a handful of its close neighbors. The graph has several layers. The top layer has only a few nodes with long-distance links, like highways. The lower layers have more nodes with shorter links, like local roads. The bottom layer contains every vector.

To search, the engine starts at the top layer and moves greedily toward the node closest to the question, following links. When it cannot get closer, it drops one layer down and continues from there. At the bottom, it explores the neighborhood around the best node and collects the closest candidates. The search touches only a tiny fraction of all vectors.

flowchart TD
  T["Top layer: few nodes, long jumps"] --> M["Middle layer: more nodes, medium jumps"]
  M --> B["Bottom layer: all vectors, short links"]
  B --> R["Collect the closest candidates"]
  Q["Question vector"] --> T
        
FIG 8 — The search descends through layers, from coarse jumps to fine local exploration
Simple Analogy

To reach a small village, you first take an air route to the right region, then a train to the right district, and finally walk the local lanes. Each level narrows the area, so you never wander through the whole country.

Graph settings that matter

Build

Connections per Node

More links per node improve accuracy and use more memory. The default is a balanced value.

Build

Build Effort

A higher effort during construction produces a better graph, at the price of slower indexing and merging.

Search

Candidates Explored

At query time, the number of candidates to consider controls the balance of recall and speed.

i
Per Segment

Each segment of each shard has its own graph. A search visits the graph in every segment and combines what it finds. This has consequences for speed, which we discuss soon.

21The Key kNN Parameters: k and num_candidates

Two numbers control most of what happens in an approximate vector search.

k: How Many Results You Want

The value k is the number of nearest neighbors to return overall. If your page shows ten results, k is at least ten, and often somewhat larger when results will be combined with other ranking steps.

num_candidates: How Hard Each Shard Looks

The value num_candidates is how many candidates each shard examines before picking its best. A larger number searches more of the graph, which improves recall but increases latency and cost. It should be at least as large as k, and is commonly several times larger.

similarity: A Minimum Closeness

You can set a threshold so that results that are not close enough are dropped. This avoids showing weak matches when nothing truly relevant exists.

filter: Limit the Candidates

A filter restricts the search to documents that pass some conditions, such as a category or a date range. The filter is applied while searching the graph, so you still receive k results when enough documents qualify.

ChangeEffect on RecallEffect on Speed
Raise num_candidatesImprovesSlower
Lower num_candidatesReducesFaster
Raise kMore results returnedSlightly slower
More shardsEach shard searches its own partMore parallel work, more overhead
!
Do Not Set It Too Low

A very small number of candidates makes searches fast, but quietly misses good documents. Always measure recall against an exact search on a sample before choosing a value.

22Filtering: Meaning Plus Metadata

Real searches are rarely pure meaning. Users also say things like “only in stock” or “from this year”.

Most applications need to combine semantic closeness with hard conditions: the product must be available, the document must belong to this customer, the date must be recent, the language must match. These conditions are called filters. In vector search, filtering has a special difficulty. If you first take the nearest vectors and then apply the filter, you may throw away most of them and be left with too few results.

Elasticsearch solves this by applying the filter while walking the graph, so that the search keeps looking until it has found enough vectors that pass the filter. Because of this, you can rely on receiving the requested number of results, as long as enough documents qualify.

flowchart LR
  A["Nearest first, filter after"] --> B["Few or no results left: bad"]
  C["Filter during graph search"] --> D["Enough matching results: good"]
        
FIG 9 — Filtering during the search keeps the result count reliable

Multi-Tenant Applications

A filter on a tenant identifier makes sure that one customer never sees another customer’s documents. This filter should be enforced by your application or by security rules, not left to the user.

Very Selective Filters

When a filter leaves only a small set of documents, the engine can switch to exact comparison of just those documents, which is both fast and perfectly accurate.

i
Design Habit

Store useful metadata such as category, language, date, and access level next to every chunk, so filters can be applied cleanly at search time.

23Shards, Segments, and Vector Search Speed

Because graphs live inside segments, the physical layout of your index changes the speed of vector search.

A shard is made of many segments, and each segment holds its own HNSW graph. A vector search must query the graph of every segment, then merge the results. If a shard has forty small segments, forty graphs are searched. If merges have combined them into five larger segments, only five graphs are searched, and each search is faster and often more accurate.

Also, a search runs on every shard of the index and merges the per-shard results. Too many shards therefore multiply the work, just as they do for other searches.

1

Keep Shard Counts Modest

Use as few shards as your size and throughput needs allow. Every extra shard adds another graph search per query.

2

Let Merges Work

Avoid setting the refresh interval so short that thousands of tiny segments pile up. Larger, fewer segments give faster vector search.

3

Merge Down Read-Only Indices

For data that no longer changes, merging to fewer segments improves both speed and memory use of the graphs.

4

Watch Updates and Deletes

Updating a vector means indexing a new one and marking the old one deleted. Heavy update workloads create churn in the graphs until merges clean them.

Simple Analogy

A phone directory split into forty small booklets is slower to search than one in five volumes. You must check every booklet for the name. Merging booklets is what segment merging does.

24Why Hybrid Search?

Semantic search is powerful but not perfect. Keyword search is limited but reliable. Together they are better than either alone.

Semantic search shines with long, natural questions and with paraphrases. But it can stumble on exact things: a product code such as “X200-B”, a person’s rare name, an error number, or a specific legal clause number. The embedding may blur exact strings into a general idea, and the results become vague. Keyword search handles such exact strings perfectly.

Keyword search, on the other hand, fails when users use different words than documents. So each method covers the weakness of the other. Hybrid search runs both and merges their results into one list. Studies and real-world experience repeatedly show that hybrid ranking beats either method alone on many kinds of content.

Query TypeKeyword SearchSemantic SearchHybrid
Exact code or identifierExcellentWeakExcellent
Natural language questionFairExcellentExcellent
Synonyms and paraphrasesWeakExcellentExcellent
Rare proper namesExcellentFairExcellent
Short one-word queryGoodFairGood
Simple Analogy

A doctor uses a blood test for exact numbers and a conversation to understand your symptoms. Neither is enough alone. Hybrid search uses both the precise instrument and the understanding listener.

25Combining Scores: Reciprocal Rank Fusion and Weights

Merging two ranked lists sounds easy, but their scores are not comparable. Rank fusion solves this problem.

Keyword search returns BM25 scores that might range from zero to thirty. A vector search returns similarity scores that are usually between zero and one. Adding them directly makes no sense, since one scale would dominate. One approach is to normalize each score and combine them with weights. Another, very popular approach, is Reciprocal Rank Fusion, or RRF.

RRF ignores the scores and looks only at ranks. Each document gets a small number of points from each list, based on its position: high positions give more points, lower positions fewer, using a simple formula where the points are one divided by a constant plus the rank. The points from all lists are added, and the documents are sorted by their total. A document that appears near the top of both lists wins clearly.

flowchart TD
  Q["User question"] --> K["Keyword search: ranked list A"]
  Q --> V["Vector search: ranked list B"]
  K --> F["Reciprocal rank fusion: add points by rank"]
  V --> F
  F --> R["One combined ranked list"]
        
FIG 10 — Rank fusion merges two lists by position, avoiding score scale problems
MethodHow It WorksStrengthWeakness
Reciprocal rank fusionCombines by rank positionNo score tuning needed, robustIgnores how big the score gaps were
Weighted linear combinationNormalizes scores and adds with weightsFine control of the balanceNeeds normalization and tuning
Boosting both queries in one requestAdds raw scores with boostsSimple to startScales may not match well
!
License and Version

Rank fusion features have changed status over versions and may require a paid subscription level. Check what your version offers before you design around it.

i
Window Size

Fusion only considers the top results of each list, up to a window size. Make the window comfortably larger than the page you show, so good documents deep in one list are not lost.

26Semantic Reranking

Fast retrieval finds a good candidate set. A stronger, slower model can then reorder the best few with more care.

The first stage of search must be very fast, because it looks at millions of documents. It uses simple comparisons of vectors or terms. The second stage, reranking, takes only the top few dozen or hundred results and examines each together with the question, using a more powerful model that reads both texts side by side. This kind of model, often called a cross-encoder, understands the relationship between the question and each passage much better than comparing two separate vectors.

flowchart LR
  A["Millions of documents"] -->|"fast retrieval: keyword, vector, or hybrid"| B["Top 100 candidates"]
  B -->|"slower, smarter reranking model"| C["Top 10 reordered results"]
        
FIG 11 — A funnel: cheap retrieval narrows the field, and expensive reranking polishes the top

Why Not Rerank Everything?

The reranking model must read each candidate in full, so its cost grows with the number of candidates. Running it on millions of documents would be far too slow and costly. It is used on a small shortlist only.

Where the Model Comes From

Reranking models can be provided by Elastic or by outside providers through the inference API. The rerank endpoint takes the question and the candidate texts and returns a relevance score for each.

Simple Analogy

A company first screens thousands of resumes with an automatic filter, then a senior manager reads the top twenty carefully and decides the final order. The manager is too expensive to read every resume, and the filter is too crude to make the final call.

i
Latency Budget

Reranking adds noticeable time. Choose the number of candidates to rerank by testing, and use it where precision at the top matters most, such as question answering, and less where speed is critical.

27The Retriever Framework

Retrievers let you describe a whole search pipeline as a tree of simple steps.

A retriever is a building block that produces a ranked list of documents. Some retrievers do the actual searching, such as the standard retriever for keyword queries and the kNN retriever for vector search. Others take lists from child retrievers and transform them, such as the rank fusion retriever, which merges lists, and the reranking retriever, which reorders the top results using a model.

Because retrievers nest, you can express a complete modern search in one readable structure: get candidates by keyword and by meaning, fuse them, and rerank the top. This is easier to read and maintain than hand-mixing many separate clauses and boosts.

flowchart TD
  RR["Reranking retriever"] --> FU["Rank fusion retriever"]
  FU --> ST["Standard retriever: keyword query"]
  FU --> KN["kNN retriever: vector query"]
        
FIG 12 — Retrievers nest: two searches are fused, and the fused list is reranked
Retriever KindRole
StandardRuns a normal query, such as a keyword or semantic query
kNNRuns a vector nearest neighbor search
Rank fusionCombines several child result lists by rank
RerankerReorders the top results using an inference model
Rule basedApplies promoted or pinned results according to rules
!
Maturity

Retrievers were introduced in stages and some parts began as previews. Confirm that the retrievers you need are generally available in your version before you depend on them in production.

28Semantic Search as the Base for Retrieval-Augmented Generation

Many teams adopt semantic search because they want a chat assistant that answers from their own documents.

Large language models write fluent answers, but they do not know your private documents, and they can invent facts. Retrieval-augmented generation, or RAG, fixes this. First, a retrieval step finds the passages of your own content that are most relevant to the user’s question. Then those passages are placed in the prompt of a language model, which writes an answer using only that material and can cite its sources.

Elasticsearch is a natural retrieval engine for this job. It stores your chunks, finds them by meaning and by keywords, filters them by permissions, and returns the best passages. The quality of the final answer depends heavily on the quality of the retrieval, which makes everything in this guide directly relevant.

sequenceDiagram
  participant U as User
  participant A as Application
  participant E as Elasticsearch
  participant L as Language model
  U->>A: Ask a question
  A->>E: Hybrid search with permission filters
  E->>A: Best passages
  A->>L: Question plus passages as context
  L->>A: Answer with citations
  A->>U: Show answer and sources
        
FIG 13 — Retrieval feeds the language model with grounded passages

Ground Answers in Sources

Show which passages were used, so that users can check the answer. This builds trust and makes errors easy to spot.

Respect Permissions

Retrieval must only return passages the user is allowed to see. Apply security filters at search time, before anything reaches the language model.

Pass Only the Best Few

Language models have limits on how much text they can read, and more text costs more. Retrieve widely, rerank, and send only the top few passages.

i
Garbage In, Garbage Out

If retrieval returns the wrong passages, even the best language model will answer wrongly. Invest in measuring and improving retrieval first.

29Quantization: Shrinking Vectors to Save Memory

Vectors are big. Quantization compresses them so more data fits in fast memory.

A vector of 768 numbers stored as 32-bit floats takes about three kilobytes. For ten million chunks, that is around thirty gigabytes for the raw vectors alone, before counting the graph. Fast search needs the vectors and the graph to sit in the operating system page cache, so memory is often the deciding cost of a semantic search system.

Quantization reduces the precision of each number. Instead of a 32-bit float, each number is stored in eight bits, four bits, or even a single bit. Accuracy drops only a little, because the original full-precision vectors can still be used to rescore the best candidates, while the memory needed for the main search falls dramatically.

Storage FormApproximate Size vs Full PrecisionAccuracy Effect
Full precision floats1xBest
8-bit integersAbout one quarterVery small loss
4-bit integersAbout one eighthSmall loss
Binary quantizationAbout one thirty-secondLarger loss, usually recovered by rescoring
Simple Analogy

Storing a photo at lower quality makes the file much smaller. You can still recognize the picture, and if you need fine detail, you open the original. Quantized vectors work the same way: a rough copy for quick search, the original for final checking.

i
Defaults Are Improving

Recent versions apply compression by default for larger vectors. Read the documentation of your version, and compare recall and speed on your own data before and after changing the storage form.

!
Disk Still Holds the Originals

Quantization saves memory used in searching. The original vectors may still be kept on disk for rescoring, so disk use can even grow slightly. Plan for both.

30Sizing and Capacity Planning

Semantic search adds new costs. Estimate them early so that the project does not surprise you.

1

Count the Chunks

Estimate the total number of chunks, not documents. A collection of a million long documents may become ten million chunks.

2

Compute Vector Size

Multiply chunks by dimensions by four bytes for full precision, and adjust for compression. Add room for the graph, which can add a substantial extra share.

3

Plan Memory for Hot Data

The vectors and graphs that are searched often should fit in the page cache of the data nodes. Memory outside the Java heap matters most here.

4

Plan Model Throughput

Work out how many chunks per second you must embed during ingest and how many questions per second at query time. Size model capacity to match, with headroom.

5

Add Replicas and Growth

Replicas copy vectors too, so they multiply storage and memory. Add a growth margin, since new content keeps arriving.

6

Test With a Real Sample

Index a realistic sample, measure size and latency, and extrapolate. Actual numbers beat any estimate.

Chunks
The real unit of storage, not documents
Memory
Page cache decides vector search speed
Model
Throughput limits ingest and query speed

31Node Roles and Semantic Search

Semantic search touches several node roles. Giving each its own resources keeps the cluster healthy.

Role

Machine Learning Nodes

Run the built-in models such as ELSER and dense embedding models. They need strong processors and memory, and often benefit from being dedicated.

Role

Ingest Nodes

Run pipelines that call inference during indexing. They wait on model calls, so they should have enough threads.

Role

Data Nodes

Hold vectors and graphs. Memory outside the heap is important, and fast storage helps merges.

Role

Coordinating Nodes

Receive questions, ask for the question embedding, and merge shard results. Keep them free from heavy background work.

The most important separation is between model work and shard work. A busy model can consume processors that data nodes need for searches, and heavy vector merges can slow down model responses. Putting models on their own machine learning nodes prevents them from fighting. Trained model deployments also let you control how many allocations, which are copies of the model, and how many threads per allocation, so you can scale throughput or latency according to your needs.

Simple Analogy

A restaurant has one team that translates foreign menus for guests and another that cooks. If the cooks also had to translate all day, the food would be late. Separate teams keep both jobs fast.

i
Scaling Model Capacity

More allocations increase throughput, the number of requests handled at the same time. More threads per allocation reduce the time of each single request. Choose according to whether you have a throughput problem, such as bulk indexing, or a latency problem, such as interactive search.

32Choosing an Approach

With so many options, a simple decision path helps you pick a starting point.

flowchart TD
  S["Start: need better search"] --> A{"Mostly English text and want quick results?"}
  A -->|"Yes"| B["semantic_text with ELSER"]
  A -->|"No: other languages or special domain"| C{"Want simplicity or full control?"}
  C -->|"Simplicity"| D["semantic_text with a multilingual dense endpoint"]
  C -->|"Full control"| E["dense_vector with your chosen model and settings"]
  B --> H["Add hybrid search with keyword"]
  D --> H
  E --> H
  H --> R{"Need the best precision at the top?"}
  R -->|"Yes"| RR["Add a reranker"]
  R -->|"No"| DONE["Evaluate and tune"]
  RR --> DONE
        
FIG 14 — A simple path from need to a starting design
SituationSuggested StartReason
English knowledge base, small teamsemantic_text with ELSER, plus keywordLeast work and strong quality
Many languagesMultilingual dense embedding endpointOne map of meaning across languages
Very large collection, tight memoryDense vectors with compression, or sparse vectorsControl memory footprint
Data must never leave the clusterModel hosted in the clusterPrivacy and compliance
Already have vectors from another systemdense_vector with those vectorsReuse existing pipeline
Exact identifiers matter a lotHybrid, keyword weighted stronglyExact strings need lexical matching

33Evaluating Relevance

You cannot improve what you cannot measure. Relevance needs numbers as much as speed does.

To evaluate search, you need a test set: a list of real questions, each with the documents that a human judged to be good answers. Even fifty to a hundred well-chosen questions are a great start. You then run each search method on the same questions and compute measures that reflect how high the good documents appear.

Metric

Precision at k

Of the top k results, what share are relevant. Shows how clean the top of the list is.

Metric

Recall at k

Of all relevant documents, what share appears in the top k. Shows what you are missing.

Metric

Mean Reciprocal Rank

How high the first relevant result appears, on average. Ideal for question answering.

Metric

NDCG

A score that rewards putting the most relevant documents at the very top and handles graded judgments.

Elasticsearch offers a ranking evaluation operation that runs a set of queries against judged documents and reports these metrics, so you can compare keyword, semantic, and hybrid setups on equal terms. Also measure the recall of the approximate vector search against exact search, since that tells you whether your candidate settings are too aggressive.

Include Hard Questions

Add questions with exact codes, rare names, misspellings, very short queries, and long paragraphs. Hybrid systems earn their value on such mixed traffic.

Use Real Logs

Sample real user queries from your search logs, and let domain experts judge the results. Made-up questions are usually too tidy.

i
Re-test After Every Change

New model, new chunk size, new fusion setting: each is a change that can help or hurt. Run the same test set after each one and keep a record.

34A Tuning Guide

When quality or speed is not good enough, work through these levers in order, from cheapest to most costly.

1

Check the Basics

Confirm the same model is used for indexing and searching, the similarity measure matches the model, and the text was actually embedded as expected.

2

Fix the Chunks

Try different chunk sizes and overlaps, and cut at natural boundaries. Chunking is often the biggest quality lever.

3

Add Hybrid

Combine keyword and semantic search with rank fusion. This alone fixes many failures on exact terms.

4

Tune Candidates

Raise the number of candidates until recall against exact search is high enough, then stop, since more only costs time.

5

Add Metadata Filters and Boosts

Use fields such as recency, category, and popularity to steer the results towards what users actually need.

6

Add a Reranker

Rerank the top results with a stronger model when top precision matters and you can afford the delay.

7

Change the Model

Only when the earlier steps are exhausted, try a different or domain-specific model. This needs re-embedding all data, so it is the most expensive change.

!
One Change at a Time

Change a single thing, run your evaluation set, and record the result. Changing many things at once makes it impossible to know which one helped.

35Security and Privacy

Embeddings are derived from your data, so they deserve the same protection as the data itself.

Risk

Data Leaves the Cluster

When you use an outside embedding service, your text is sent to that provider. Check contracts, regions, and retention rules, especially for personal or confidential content.

Risk

Vectors Reveal Information

Research shows that vectors can leak parts of the original text. Treat them as sensitive, and do not assume that numbers are anonymous.

Risk

Broken Access Control

Semantic search can surface documents a user should not see if permissions are not applied. Apply security filters at search time on every query.

Risk

Leaked API Keys

Keys for outside providers grant spending power. Store them as secrets, restrict them, and rotate them.

Controls

Use role based access control and document or field level security so that queries only see allowed data. Keep the model inside your cluster when the data is sensitive. Encrypt traffic to and from model services. Limit who can create inference endpoints and deploy models, because those actions can send data outside or consume large resources. Audit access to sensitive indices.

!
RAG and Permissions

When search feeds a language model, a permission mistake becomes an answer that reveals private content in fluent text. Test that filters work before the language model ever sees the passages.

i
Untrusted Text

Indexed documents may contain instructions aimed at a language model, such as text that tries to change its behavior. Treat retrieved passages as data, not commands, in any generation step.

36Monitoring, Logging, and Metrics

A semantic system has two health stories: the search cluster and the model. Watch both.

SignalWhere to LookWhat It Tells You
Inference count and average timeTrained model statisticsModel speed and load
Rejected inference requests and queue depthTrained model deployment statisticsModel capacity is too small for the traffic
Machine learning node memory and processor useNode statisticsRoom to add more model copies
Search latency by query typeSearch statistics and slow logsWhether vector, keyword, or fusion is slow
Page cache and disk reads on data nodesOperating system metricsWhether vectors fit in fast memory
Segment counts and merge activityIndex and segment statisticsGraph fragmentation and load after big ingests
Errors and rate limits from outside providersApplication logs and provider dashboardsQuota, network, or key problems
Relevance metrics over timeYour evaluation jobQuality drift after changes or data growth

Business level signals

Also watch how users behave. Track the share of searches that end with a click, searches that return nothing, and searches that users immediately rephrase. A rise in rephrasing often shows that results have become worse. Keep a sample of queries and results for periodic human review.

i
Alert Ideas

Alert on model queue rejections, on a rising average inference time, on data node disk reads, and on the failure rate of embedding calls. These warn you before users feel the slowdown.

37Failure Modes and Troubleshooting

Most problems come from a small set of causes. This table maps symptoms to first checks.

SymptomLikely CauseFirst Action
Indexing fails with a vector dimension errorModel output size does not match the mappingCheck the model dimensions and the field setting, recreate the index if needed
Semantic query returns an error about the modelModel not deployed or endpoint missingCheck deployment state and endpoint name
Bulk indexing gets rejections or timeoutsModel queue fullLower bulk rate, add allocations, add machine learning capacity
Results look randomDifferent models used at index and query timeUse one model for both, re-embed if needed
Exact codes are not foundPure semantic search usedAdd keyword search and hybrid fusion
End of long documents never matchesText was truncated by the modelAdd chunking so all text is embedded
Vector search is slowToo many segments or shards, or vectors not in cacheMerge segments, reduce shards, add memory, use compression
Recall is lowCandidate number too smallRaise candidates and compare with exact search
Filtered vector search returns few resultsFilter applied after search, or too few matchesUse the filter option inside the vector search
Non-English queries perform badlyEnglish-only modelUse a multilingual model
Sudden errors from an outside providerRate limit, quota, or expired keyCheck provider limits and rotate the key
Simple Analogy

Like a car dashboard, each warning points to one system. Learning the few common lights saves you from taking the whole engine apart.

38Design Patterns That Work

These habits show up in most successful semantic search projects.

Hybrid by Default

Start with keyword plus semantic search combined by rank fusion. Move to pure semantic only where evaluation proves it is better.

Funnel Architecture

Retrieve broadly with fast methods, fuse the lists, and rerank a small shortlist with a stronger model.

Chunk With Metadata

Store the title, source, section, date, and access level with each chunk, so results can be filtered, explained, and linked back to the original page.

Versioned Indices for Model Changes

Write embeddings from a new model into a new index, test it against the old one, and switch traffic with an alias. This makes model upgrades safe and reversible.

Evaluation as a Pipeline

Keep the judged test set in version control and run it automatically whenever models, chunking, or search definitions change.

Graceful Fallback

If the model is unavailable, fall back to keyword search, so that search keeps working and only the quality is reduced.

Separate Model Capacity

Run models on dedicated machine learning nodes, sized for both bulk ingest and interactive queries.

39Anti-Patterns to Avoid

These mistakes appear again and again in real projects.

ANTI-PATTERN-01 Avoid
Problem

Replacing keyword search completely with vector search without measuring.

Why It’s Harmful

Exact identifiers, names, and short queries often get worse. Users lose trust when they cannot find a document by its exact code.

Correct Approach

Run both, fuse them, and compare with a judged test set before removing anything.

ANTI-PATTERN-02 Avoid
Problem

Embedding whole long documents as one vector.

Why It’s Harmful

Models truncate long input, and one vector cannot represent many topics. Most of the document becomes unsearchable or blurred.

Correct Approach

Chunk the text into passages of sensible size and embed each one.

ANTI-PATTERN-03 Avoid
Problem

Mixing embedding models between indexing and querying, or between old and new documents in one index.

Why It’s Harmful

Vectors from different models are not comparable, so distances become meaningless and results look random.

Correct Approach

Record the model name with the data, use one model per index, and re-embed into a new index when changing models.

ANTI-PATTERN-04 Avoid
Problem

Setting the candidate number very low to make vector search fast, without measuring recall.

Why It’s Harmful

Good documents are silently missed, and no error tells you.

Correct Approach

Compare against exact search on a sample and choose the smallest value that keeps recall high.

ANTI-PATTERN-05 Avoid
Problem

Filtering vector results after retrieval in the application.

Why It’s Harmful

Most of the retrieved neighbors may be removed, leaving few or no results. It can also leak documents if the filter is forgotten.

Correct Approach

Apply the filter inside the vector search and enforce permissions in the query itself.

ANTI-PATTERN-06 Avoid
Problem

Running models on the same nodes that serve searches, with no capacity planning.

Why It’s Harmful

Bulk embedding competes with queries for processors, and both slow down unpredictably.

Correct Approach

Use dedicated machine learning nodes and size model allocations for the real workload.

ANTI-PATTERN-07 Avoid
Problem

Sending confidential text to an outside embedding provider without review.

Why It’s Harmful

It may violate privacy rules or contracts, and the data leaves your control.

Correct Approach

Use models inside your cluster for sensitive data, or complete a data protection review of the provider first.

40Best Practices and Common Mistakes

A checklist to keep beside you when building semantic search.

Best Practices

  • Start from real user questions and a judged test set
  • Use hybrid search as the default
  • Chunk documents, and store metadata with each chunk
  • Keep one model per index and version your indices
  • Tune candidates using recall against exact search
  • Plan memory for vectors, and consider compression
  • Run models on dedicated capacity
  • Enforce security filters inside every query
  • Monitor both model health and search health

Common Mistakes

  • Choosing a model by hype instead of testing
  • Forgetting that the model is needed at query time too
  • Ignoring exact match needs
  • Underestimating vector memory and storage
  • Changing the model without re-embedding
  • Tuning by feeling instead of measurement
  • Skipping a fallback when the model is down
  • Sending private data to outside services casually
i
A Good Question to Ask

Before adding any semantic feature, ask: what real user question fails today, and how will I know that it works better afterwards?

41Advantages and Trade-Offs

Semantic search is a strong tool, but it is not free.

Advantages

  • Finds relevant results even with no shared words
  • Handles natural language questions well
  • Works across languages with multilingual models
  • Reduces the manual work of synonym lists and rules
  • Combines with keyword search, filters, and reranking in one engine
  • Provides the retrieval base for answer generation over private content

Disadvantages / Trade-offs

  • More storage and memory for vectors and graphs
  • Slower indexing, since every chunk needs a model call
  • An extra dependency at query time for the question embedding
  • Harder to explain why a result matched, especially with dense vectors
  • Model changes require re-embedding all data
  • Can be weak on exact codes and rare names when used alone
  • Approximate search may miss some true neighbors

The trade is usually worth it where users ask questions in their own words and documents are written in many styles. It is less compelling for tiny catalogs with clean structured data, where good filters and keyword search already work well.

42Real-World Scenarios

These stories show semantic search at work in familiar settings.

Customer Support Knowledge Base

A support team has thousands of articles. Customers type problems in their own words, such as “my parcel shows delivered but I never got it”. Keyword search misses articles titled “Missing shipment claims”. With semantic search plus keyword search, the right article appears first, and support agents receive fewer duplicate tickets.

E-Commerce Discovery

Shoppers search for “shoes for wet weather” or “gift for a new dad”. Product titles do not use these phrases. A hybrid setup understands the intent, while exact model numbers still work through keyword matching. Filters on size, price, and availability are applied inside the vector search.

Internal Document Search

Employees look for policies across shared drives, wikis, and tickets. Permissions differ by document. The team indexes chunks with access group fields, applies filters in every query, and gets meaningful results without exposing restricted content.

Legal and Compliance Research

Lawyers search long contracts for clauses about “termination for convenience”. Exact clause numbers need keyword matching, while concepts need semantic matching. Chunks follow the contract structure, and a reranker ensures that the best clause is at the top.

A Question Answering Assistant

A company builds a chat assistant for its own manuals. Retrieval uses hybrid search with permission filters, rerank the top passages, and passes the best three to a language model, which answers with citations. When answers were wrong, the team fixed chunking and filters rather than changing the language model.

Multilingual Help Center

A global service stores articles in several languages. A multilingual model lets a customer ask in one language and find articles written in another, with the option to show the translated version.

“Keywords find the words you wrote. Semantic search finds the idea you meant.”

43Adding Semantic Search to an Existing Keyword Search

You do not need to rebuild everything. A step-by-step path keeps risk low.

1

Collect Failing Queries

Find searches with no results, quick rephrasing, or no clicks. These are the ones semantic search should help.

2

Build a Judged Test Set

Combine failing queries with typical successful ones, and have people judge good answers.

3

Create a New Index Beside the Old One

Copy the data into a new index with a semantic field or vector fields. Keep the old index in service.

4

Compare Methods Offline

Run keyword, semantic, and hybrid searches against the test set, and compare the metrics and the latency.

5

Roll Out to a Small Share of Traffic

Use an experiment with a portion of users. Watch click rate, rephrasing, and errors alongside speed.

6

Switch With an Alias

When results are better, move the alias to the new index. Keep the old index for a while, in case you need to go back.

7

Keep Improving

Monitor, expand the test set, and try reranking or better chunking as the next steps.

i
Low Risk Start

Because the old index stays live, and hybrid search still contains keyword results, the worst case of an experiment is that users see results as good as before.

44Myths About Semantic Search

Some beliefs about semantic search cause bad decisions. Let us test them.

MYTH-01 False
The Belief

Semantic search understands language like a human and is always better than keyword search.

The Reality

It measures closeness of meaning as learned by a model. It can miss exact terms and can be confidently wrong on unfamiliar topics.

What To Do

Evaluate on your own questions, and use hybrid search.

MYTH-02 False
The Belief

Once vectors are stored, the model is no longer needed.

The Reality

The question must be embedded at search time by the same model, unless your application supplies the vector.

What To Do

Plan model availability and capacity for query time as well as ingest time.

MYTH-03 False
The Belief

A bigger vector or a bigger model always gives better results.

The Reality

Bigger models cost more and are only better if they fit your language and domain. Chunking and hybrid design often matter more than model size.

What To Do

Test a few models on your data and pick the best value, not the biggest.

MYTH-04 False
The Belief

Approximate search is unreliable, so exact search should always be used.

The Reality

Well-tuned approximate search reaches very high recall at a tiny fraction of the cost. Exact search is only practical for small sets or heavily filtered sets.

What To Do

Measure recall against exact search and tune candidates to reach an acceptable level.

MYTH-05 False
The Belief

Vectors are just numbers, so they are safe from privacy concerns.

The Reality

Vectors derive from your text and can reveal information about it. They need the same access controls as the source documents.

What To Do

Apply security to vector indices and think carefully before using outside services.

45A Short Glossary of Semantic Search Terms

Keep these plain-language definitions handy. Shared vocabulary makes design discussions shorter and clearer.

Term

Embedding

A list of numbers created by a model that captures the meaning of a text.

Term

Vector

The mathematical name for that list of numbers, which can be compared with other vectors.

Term

Dimensions

The length of a vector, such as 384 or 768 numbers, decided by the model.

Term

Token

A small piece of text, often a word or part of a word, which is the unit that models read.

Term

Nearest Neighbor Search

Finding the stored vectors that are closest to a query vector.

Term

HNSW

The layered graph structure that makes approximate nearest neighbor search fast.

Term

Recall

The share of true nearest neighbors that an approximate search manages to find.

Term

Chunk

A passage cut from a longer document, embedded and searched on its own.

Term

Hybrid Search

Running keyword and semantic searches together and merging their results.

Term

Reranking

Reordering a short list of top results with a stronger model that reads the question and each passage together.

Term

Inference

The act of running a trained model on new input, such as turning a question into a vector.

Term

Quantization

Storing vector numbers with fewer bits to save memory, with a small cost in accuracy.

When a teammate says “our recall is low”, they mean the approximate search is missing true neighbors, and the candidate number may need to grow. When they say “we need to chunk”, they mean long documents are being cut off by the model. When they say “let us go hybrid”, they mean keyword and semantic results should be merged. Knowing these phrases turns long meetings into short ones.

i
Teach the Team

Share this short list with everyone who touches search: engineers, product owners, and support staff. People who use the same words find problems faster and argue less about what the words mean.

46Frequently Asked Questions

Q1What is semantic search in Elasticsearch in simple words?

It is search based on meaning. Text is turned into vectors by a model, and Elasticsearch finds the documents whose vectors are closest to the vector of the question, even if they share no words.

Q2What is an embedding?

An embedding is a list of numbers produced by a model that represents the meaning of a text. Texts with similar meanings get similar lists of numbers.

Q3What is the difference between dense and sparse vectors?

Dense vectors are fixed-length lists where nearly all values are used and are searched by nearest neighbor search. Sparse vectors are long lists with mostly zeros, where each position stands for a word, and they are searched with inverted index techniques.

Q4What is ELSER?

ELSER is Elastic’s learned sparse model for English text. It expands text into weighted related terms and works well out of the box without tuning.

Q5What is the semantic_text field?

It is a field type that automates chunking, embedding, and storage. You index plain text, and search with a semantic query using plain text, without building pipelines yourself.

Q6Do I still need keyword search?

Yes, in most cases. Keyword search is excellent for exact codes, names, and short queries. Hybrid search that combines both usually gives the best results.

Q7What is hybrid search and what is RRF?

Hybrid search runs keyword and vector searches and merges the results. Reciprocal rank fusion is a popular way to merge by rank position, which avoids comparing scores that are on different scales.

Q8What do k and num_candidates mean?

The value k is how many nearest neighbors you want returned overall. The value num_candidates is how many candidates each shard examines. More candidates give better recall but slower searches.

Q9Why must I chunk long documents?

Models read only a limited amount of text, and one vector cannot represent many topics well. Chunking makes every part of a document searchable and improves accuracy.

Q10Can I change the embedding model later?

Yes, but you must re-embed all your data into a new index, since vectors from different models cannot be compared. Use versioned indices and aliases to make the switch safe.

Q11How much memory does vector search need?

Enough for the vectors and graphs of the data you search often to sit in the operating system page cache. Estimate chunks times dimensions times bytes per number, adjust for compression, and add the graph overhead.

Q12Is my data sent outside when I use semantic search?

Only if you choose an outside embedding provider. Models that run inside your cluster keep the text within it. Check your provider terms for anything sensitive.

Q13What is reranking and when should I use it?

Reranking reorders the top results using a stronger model that reads the question and each passage together. Use it when top precision matters, such as question answering, and you can afford the extra delay.

Q14How do I know if semantic search improved my results?

Build a judged set of real questions, compute metrics such as precision, recall, and NDCG for each approach, and confirm with an experiment on real users.

Q15How does this relate to RAG?

Retrieval-augmented generation uses search to find relevant passages, and then a language model writes an answer from them. Elasticsearch supplies the retrieval, so good semantic and hybrid search directly improves answer quality.

Q16What happens if the model is unavailable?

Semantic queries and semantic indexing fail or slow down. Plan a fallback to keyword search, and monitor the model endpoints and their queues.

47Summary and Key Takeaways

Semantic search in Elasticsearch finds documents by meaning. A model turns text into vectors, either dense lists of numbers searched through a fast graph, or sparse weighted terms searched through the inverted index. The semantic text field makes the setup easy, the inference API connects many kinds of models, hybrid search with rank fusion combines meaning with exact words, and reranking polishes the top of the list. Around all of this sit the practical concerns of chunking, memory, model capacity, security, evaluation, and monitoring. Like the librarian in our opening story, a good search system understands what you mean, but still checks the shelf labels when you ask for a book by its exact title.

Key Takeaways

  • Meaning becomes numbers — embeddings place similar texts near each other, so search becomes a nearest neighbor problem.
  • Two shapes of vectors — dense vectors use graph-based nearest neighbor search, sparse vectors such as ELSER use inverted index style matching.
  • Start simple — the semantic text field handles chunking and embedding for you, and manual vector fields give full control when you need it.
  • Hybrid beats either alone — combine keyword and semantic results by rank fusion, then rerank the top when precision matters.
  • Chunk, filter, and keep one model — chunk long text, apply filters inside the vector search, and never mix vectors from different models.
  • Plan the resources — vectors need memory, models need dedicated capacity, and both indexing and querying depend on the model.
  • Measure, secure, and monitor — use a judged test set, protect vectors like the data itself, and watch model health together with search health.