Lecture: Lecture 20 - ElasticSearch
Related: ElasticSearch Data Model Inverted Index Analyzers and Query DSL · Similarity Dissimilarity and Correlation · ElasticSearch Sharding Clusters and Optimistic Concurrency Control
Relevance scoring overview (Slides 39–43)
Full-text search rarely has a single binary “correct” answer; instead, ElasticSearch computes a floating-point _score for every matching document and sorts results in descending _score order (Slide 40). Scoring proceeds in three phases (Slide 41):
- Compute matching results and assign relevance
_scoreto all matching documents. - Select top hits (default: 10 documents).
- (Optional) Rescore those top hits using a more computationally expensive algorithm.
Under the hood, relevance score computation combines three models (Slide 43):
- Boolean model: Fast selection of documents matching the query terms.
- TF/IDF scoring: Evaluates the weight (importance) of each term in a document.
- Vector Space Model (VSM): Represents both query and document as term vectors and measures their similarity.
TF/IDF scoring function (Slides 44–48)
Each term’s weight in a document combines three factors calculated and stored at index time (Slides 44–48):
| Factor | Source Formula (Slides 45–47) | Plain-language meaning |
|---|---|---|
Term Frequency (TF) | frequency = times term appears in document . Appears more often → more relevant. | |
Inverse Document Frequency (IDF) | numDocs = total docs in index; docFreq = docs containing . Appears in more docs → less relevant (rare words carry higher weight). | |
Field-length norm (norm) | numTerms = total terms in the field. Longer field → lower weight per matched term (a hit in a short title beats one buried in a long document). |
Vector Space Model (VSM) and Cosine Similarity (Slides 49–52)
To combine multiple query terms, the Vector Space Model represents both the query and each document as vectors whose dimension equals the number of terms in the query, where each component holds the term’s TF/IDF weight (Slide 49). Similarity is measured via Cosine similarity—the smaller the angle between a document vector and the query vector, the higher the relevance _score (Slide 50; see Similarity Dissimilarity and Correlation).
Worked source example: "happy hippopotamus" (Slides 51–52)
- Query:
"happy hippopotamus"→"happy"is common (low IDF weight =2),"hippopotamus"is rare (high IDF weight =5) → Query vector . - Three documents:
- D1: “I am happy in summer.” → (points straight up on the
"happy"axis; large angle from → lowest score). - D2: “After Christmas I’m a hippopotamus.” → (points along the
"hippopotamus"axis; smaller angle to than D1, so D2 outranks D1!). - D3: “The happy hippopotamus helped Harry.” → (aligned at with → highest
_score).
- D1: “I am happy in summer.” → (points straight up on the
happy ▲
│ D1 [2,0]
│ ▲ ⟋ Q = D3 [2,5] (0° angle → highest score)
│ │ ⟋
│ │ ⟋ (smaller angle to D2 than D1!)
└──┴──────────────► hippopotamus
D2 [0,5]From Lexical search to Semantic Embeddings and Hybrid Search (Slides 53–59)
Why lexical search is limited (Slides 53–54)
Lexical search only counts literal word matches (plus stemming/synonyms)—it does not understand meaning. Querying "nice german teacher" returns documents containing “A german shepherd watches the house”, “I’m a English teacher”, and “We’re going on holidays to Nice” (the French city) (Slide 53). Beyond text, images, audio, and video also carry unstructured semantic meaning (Slide 54).
Semantic embeddings (Slides 55–57)
Semantic embeddings use ML models trained on large datasets—such as BERT / OpenAI Embeddings for text (capturing contextual meaning across whole sentences) and CLIP for images aligned with text descriptions—to map each item into a fixed-size dense vector in a high-dimensional space, where similar meanings sit close together and different meanings sit far apart (Slides 55–56).
VSM vs. Dense Semantic Embeddings (Slides 57–58)
| Dimension | Traditional Lexical / VSM | Dense Semantic Embeddings |
|---|---|---|
| Vector size & timing | Depends on the user query (size = query terms); recomputed on every query and ignores non-query words in the document | Fixed size (e.g., 769 BERT features), generated once at index time, independent of the user query |
| Iliad example (Slide 57) | Query “Proemio dell’Iliade, lite tra Achille e Agamennone” vs. “Cantami o diva del Pelide Achille l’Ira funesta” → [0, 0, 0, 8, 0, 0] (matches only "Achille") | Dense vector [0.02, 0.034, ..., 0.012] captures full contextual similarity |
| Preprocessing (Slide 58) | 1. Word tokenization → 2. Normalization (case, stemming, synonyms) → 3. Inverted index → 4. Query-time vector | 1. Light normalization (lowercase, bad chars; no stemming or synonyms) → 2. Sub-word tokenization for embedding model → 3. Store embedding once → 4. Compare query embedding |
Hybrid Search in Elastic (Slide 59)
Elastic supports Hybrid Search, combining traditional lexical / sparse vector search (e.g., ELSER sparse vectors over a 30,000+ term vocabulary) with dense vector semantic search (e.g., MSMARCO 384-dimensional vectors)—for example, by linearly combining their scores so queries capture both exact keyword matches and semantic meaning.
Common confusions
- Thinking matching more query terms always ties when counts are equal:
D1andD2each match 1 word of"happy hippopotamus", yetD2([0, 5]) beatsD1([2, 0]) because"hippopotamus"has higher IDF weight (5 > 2), giving a smaller angle to[2, 5]. - Confusing VSM term vectors with dense ML embeddings: VSM vectors have one dimension per query term (sparse, query-dependent), whereas semantic embeddings have a fixed number of learned latent features computed once per document (query-independent).
- Applying stemming and synonym expansion before dense embeddings: Slide 58 explicitly removes stemming and manual synonym lists for dense search—sub-word tokenizers and transformer models already handle word forms and synonyms from context.
Retrieval questions with answers
1. In the "happy hippopotamus" VSM example, why does Document 2 (“After Christmas I’m a hippopotamus”, [0, 5]) outrank Document 1 (“I am happy in summer”, [2, 0]) even though both contain only one query word?
Because "hippopotamus" is much rarer across the index than "happy", giving it a higher IDF weight (5 vs. 2). That tilts the query vector [2, 5] closer in angle to [0, 5] than to [2, 0], producing a higher cosine similarity (_score).
2. Why did lexical search on "nice german teacher" misfire on “We’re going on holidays to Nice” and “A german shepherd watches the house”?
Lexical search only scores literal token matches (nice, german, teacher) without understanding context or meaning, so "Nice" (a city) and "german shepherd" (a dog breed) still match.
3. How do ElasticSearch’s VSM vectors differ from BERT semantic embeddings in when they are built and what their dimensions represent?
VSM vectors are query-dependent (built at query time, one dimension per query word, ignoring all other words in the document), whereas semantic embeddings are query-independent fixed-size dense vectors computed once at index time by an ML model to encode contextual meaning.