Search Tutorials
--Ads--How Text Embeddings Work: Word, Sentence, Document and Query Embeddings
From word vectors to sentence and document embeddings, and why queries and documents are embedded differently.
You have used embeddings as a black box: text goes in, a vector comes out, similar meanings give similar vectors. This lesson opens the box a little. It explains how word embeddings became sentence embeddings, how a model turns a whole passage into one vector, and why queries and documents are often embedded differently. Understanding this helps you choose models, chunk sizes and prefixes wisely.
What you will learn
- The difference between word, sentence and document embeddings
- How transformer models produce one vector for a whole text (pooling)
- How embedding models are trained to place similar meanings close together
- Why queries and documents are embedded differently (asymmetric search)
Prerequisites
Word embeddings
Early methods such as word2vec (2013) and GloVe learned one fixed vector per word from how words co-occur in large text collections. Words used in similar contexts ("doctor", "nurse") got similar vectors, and some relationships became directions in the space (king − man + woman ≈ queen).
Their limitation: one vector per word, regardless of context. "Bank" in "river bank" and "bank loan" has the same vector.
Contextual token embeddings
Transformers fixed this. Their self-attention layers produce a vector for every token in context, so "bank" gets different vectors in different sentences. These are contextual token embeddings.
Sentence and document embeddings: pooling
For search we need one vector per piece of text. An embedding model runs the text through a transformer and then pools the token vectors into a single vector, most often by averaging them (mean pooling) or by taking a special summary token (CLS pooling), then normalises the result. You can see the token vectors and the pooled vector with sentence-transformers:
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") # uses mean pooling
text = "The bank raised interest rates."
token_vectors = model.encode(text, output_value="token_embeddings") # one vector per token
token_vectors = token_vectors.cpu().numpy() if hasattr(token_vectors, "cpu") else np.asarray(token_vectors)
sentence_vector = model.encode(text, normalize_embeddings=True)
manual = token_vectors.mean(axis=0)
manual /= np.linalg.norm(manual)
print("tokens:", token_vectors.shape, " sentence:", sentence_vector.shape)
print("mean pooling reproduces the sentence vector:", np.allclose(manual, sentence_vector, atol=1e-4))
tokens: (9, 384) sentence: (384,)
mean pooling reproduces the sentence vector: True
(Token count includes special start and end tokens. Models that use CLS pooling would not match the mean.)
How embedding models learn meaning
Embedding models start from a pre-trained transformer and are then trained with contrastive learning on huge numbers of pairs that belong together: question and answer, title and article, two paraphrases. The training objective pulls each pair's vectors together and pushes unrelated texts apart. After training, distance in the vector space reflects similarity of meaning, which is exactly what semantic search needs. The same recipe is used when you fine-tune an embedding model on your own data.
Document embeddings and length
A document embedding is simply a text embedding of a longer passage. Two limits apply:
- Maximum input length: text beyond the model's limit (often 512 tokens) is cut off silently.
- Dilution: pooling many topics into one vector blurs them. A vector for a 30-page document sits "between" all its topics and matches no specific question well.
That is why RAG embeds chunks rather than whole documents (Why Chunking Matters).
Query embeddings: symmetric and asymmetric search
| Symmetric search | Asymmetric search | |
|---|---|---|
| Inputs | Similar kinds of text on both sides | Short query vs longer passage |
| Example | Find duplicate support tickets | Question → document chunk (RAG) |
| Typical handling | Embed both sides the same way | Mark queries and documents differently |
RAG is asymmetric: a 10-word question must match a 300-word passage that answers it. Many models are trained to handle this with a marker on one or both sides, and they perform worse if you leave it out:
- BGE v1.5: an instruction prefix on queries only.
- E5:
query:andpassage:prefixes. - Nomic:
search_query:andsearch_document:. - Hosted APIs often use an input-type parameter (for example
input_type="query"or"document") or documented text prefixes.
from sentence_transformers import SentenceTransformer
e5 = SentenceTransformer("intfloat/e5-base-v2")
docs = ["passage: Employees get 18 days of paid leave in their first year.",
"passage: Laptops must use full-disk encryption."]
q_good = e5.encode("query: how much vacation do new hires get", normalize_embeddings=True)
q_bare = e5.encode("how much vacation do new hires get", normalize_embeddings=True)
d = e5.encode(docs, normalize_embeddings=True)
print("with prefix :", (d @ q_good).round(3))
print("without prefix:", (d @ q_bare).round(3))
The ranking may stay the same on toy data, but on real collections the correct prefixes measurably improve retrieval. Always read the model card.
Key takeaways
- Word embeddings give one vector per word; transformers give context-dependent vectors per token.
- Sentence and document embeddings pool token vectors into one normalised vector.
- Contrastive training places related texts close together.
- Long texts are truncated and diluted, so embed chunks; use the model's query and document prefixes.
Frequently asked questions
Can I use an LLM's internal vectors as embeddings?
Not directly with good results. Dedicated embedding models are trained specifically so that distances reflect meaning; some recent embedding models are built from LLMs and then contrastively trained.
Why are my scores all between 0.6 and 0.9?
Many models use only part of the similarity range. Compare scores relatively, within one model.
Practice exercises
- Embed "bank" in three sentences with different meanings and compare the token vectors for "bank".
- Embed one long document whole and as chunks, and compare similarity to five specific questions.