Search is not a WHERE clause: relevance, TF-IDF and the inverted index

After this lesson you will turn the lecture's eight book titles into TF-IDF vectors by hand, rebuild its ranking down to the score 0.159, say why a title can score exactly zero, and explain how an inverted index answers a query in tenths of a second.

Eight books, known only by their titles (p. 557). A customer is interested in Building data mining applications for CRM, and the system recommends the closest of the other seven (p. 564). First comes Data Mining Your Website. Third comes Mastering Data Mining: The Art and Science of Customer Relationship Management — although it shares with the query exactly the same two words as the winner: data and mining.

Further down, Customer knowledge management is "Not recommended": its score is exactly 0. Yet CRM stands for customer relationship management, and the third title spells those three words out. They earn it nothing.

Why do the same two words count for more in the shorter title, and why can the system not see what CRM means? By the end of the lesson you will compute the whole ranking by hand — 0.159, 0.102, 0.094 and four zeros — and answer both.

Turning a title into numbers

How does a program compare two texts? Page 556 answers in two lines: "A textual document is scanned and parsed" and "Word occurrences are counted (may be stemmed)".

Bag of words — a document represented only by how many times each term occurs in it; the order of the words is thrown away.

Figure 2 runs T2 through it.

title, as printed tokens bag of words Accelerating Customer Relationships: Using CRM and Relationship Technologies accelerating customer relationship using crm and relationship technology accelerating 1 and 1 crm 1 customer 1 relationship 2 technology 1 using 1 two forms, one term
Fig. 2. T2 through the bag of words: lower-cased, punctuation dropped, plurals stemmed (Technologies → technology), then counted. "Relationships" and "Relationship" become one term with count 2 — the only 2 in the table of p. 558. The word order is gone.

Do it for all eight titles and you get the "Word count" table of p. 558: one row per term, one column per title, 29 terms in all. Six of its rows, plus a column you will need soon — the number of titles containing the term, its document frequency df:

Six rows of the word-count table of p. 558 (blank = 0), plus the document frequency.
termT1T2T3T4T5T6T7T8df
crm112
customer1113
data1113
mining1113
relationship212
the11

Notice what the table did without a word of explanation. It lower-cased everything, so "Data" and "data" are one term. It dropped the punctuation. It stemmed three plurals — applications, relationships and technologies became application, relationship and technology — which is why relationship counts 2 in T2. And it kept every short word: a, and, for, of, the, to and your all have rows of their own.

Then comes the "Problem: importance of words" (p. 556). In raw counts "the" weighs as much as "mining", a word three titles share as much as a word only one title has, and a long title overlaps with anything by sheer bulk. Three questions, three fixes: how loud is the term in this document (TF), how rare in the collection (IDF), how long is the document (normalisation).

Loud here, rare elsewhere: TF × IDF

Page 559 gives the plan: "Each document is transformed into a normed TFIDF vector, size N" — one coordinate per term of the vocabulary, N = 29 here, most of them 0. Each non-zero coordinate is the product of two factors.

TF: how loud the term is in this document

Term frequency is local, one document at a time. Page 560 defines it as a fraction:

\[ \mathrm{tf}_{i,j} = \frac{n_{i,j}}{|d_j|} \]
\(n_{i,j}\)
number of times term \(i\) appears in document \(j\)
\(|d_j|\)
number of terms in document \(j\)

The "Actual formula" of p. 562 uses a different one:

\[ TF = \log(\mathit{count} + 1) \]

Both are standard. The fraction makes an occurrence count less in a longer document; the logarithm damps repetition — a term seen twice is not twice as telling: \(\log 3 = 1.099\) against \(\log 2 = 0.693\). Natural logarithms throughout; another base multiplies every weight by one constant, which the normalisation below removes.

IDF: how rare the term is in the collection

Inverse document frequency is global. Page 561 calls it a measure of "how common a term is across the collection of documents, the lower the less important that term is": the more documents contain the term, the lower its IDF.

\[ \mathrm{idf}_i = \log \frac{|D|}{|\{d : i \in d\}|} \]
\(|D|\)
number of documents in the collection
\(|\{d : i \in d\}|\)
number of documents containing term \(i\): its document frequency, df

The "Actual formula" of p. 562 differs again, slightly:

\[ IDF = \log\left( \frac{\#\mathit{docs} + 1}{\begin{gathered} \#\mathit{docs}\text{-}\mathit{the}\text{-}\mathit{term}\text{-} \\ \mathit{occurs}\text{-}\mathit{in} \end{gathered}} \right) \]

The +1 matters at the edge: a term in all eight titles gets \(\log(8/8) = 0\) from p. 561 but \(\log(9/8) = 0.118\) from p. 562 — still the weakest, never exactly zero, so no document becomes a vector of zeros that cannot be normalised. Here df is 1, 2 or 3, so IDF takes three values:

IDF of p. 562 on the eight titles (#docs = 8).
dftermsIDF
3customer, data, mininglog(9/3) = 1.099
2and, crm, management, marketing, relationshiplog(9/2) = 1.504
1the other 21 termslog(9/1) = 2.197

Rarity is measured in this collection, not in English: "a" and "the" occur in one title each, so they get the top IDF, 2.197, like "website". The weight of a term is the product of the two factors — loud here times rare elsewhere (p. 561):

\[ (\text{tf-idf})_{i,j} = \mathrm{tf}_{i,j} \times \mathrm{idf}_i \]

Page 560 says what the product is for: it "Measures the relevance of a term inside a document" and "Penalizes the words that appear too often across different documents". Relevance in a loose sense here: the weight of a term, not the user's judgement of p. 554.

IDF comes from Karen Spärck Jones, in a short 1972 paper in the Journal of Documentation: terms "should be weighted according to collection frequency, so that matches on less frequent, more specific, terms are of greater value than matches on frequent terms".

Normalisation: every document gets length 1

The last fix is length. The formula of p. 559, boxed in red on p. 562, divides every weight of a document by the length of its whole vector:

\[ TFIDF = \frac{TF \times IDF}{\sqrt{\sum_N (TF \times IDF)^2}} \]
\(TF \times IDF\)
the raw weight of one term in this document
\(\sum_N\)
sum over the N terms of the vocabulary (here 29), for the same document
\(\sqrt{\cdots}\)
the Euclidean length (norm) of the document's raw vector

This normalisation makes every document a vector of length 1. Long titles lose their bulk advantage, and the same raw weight ends up lighter in a long title, which shares the unit length among more terms — why p. 563 circles two different numbers for one word (Figure 3).

length 2.41 length 4.07 same raw weight 0.76 0.76 T4: 4 terms T3: 11 terms

Before: TF × IDF

length 1 length 1 short title wins 0.316 0.187 T4: 4 terms T3: 11 terms

After: each title divided by its length

Fig. 3. Left: "data" (the solid bar) has the same raw weight in T4 and in T3. Right: dividing each title by its own length, 2.41 and 4.07, leaves 0.316 in the short title and 0.187 in the long one — the two cells circled on p. 563. Each panel is drawn to its own scale.

Now compute T4's column by hand, then T1's, the query book's.

  1. Count. T4, "Data Mining Your Website", has four terms, each once, so all get the same TF:

    \[ TF = \log(1 + 1) = 0.693 \]
  2. Look up df: data and mining are in T1, T3 and T4, your and website only in T4. With #docs = 8:

    \[ IDF_{\text{data}} = \log \tfrac{9}{3} = \log 3 = 1.099 \] \[ IDF_{\text{website}} = \log \tfrac{9}{1} = \log 9 = 2.197 \]
  3. Multiply, for data and mining, then for your and website — with unrounded logarithms (0.693 × 1.099 would give 0.7616):

    \[ \log 2 \times \log 3 = 0.7615 \] \[ \log 2 \times \log 9 = 1.523 \]
  4. The length of T4's vector is the square root of the sum of the squared weights:

    \[ \sqrt{2 \times 0.7615^2 + 2 \times 1.523^2} \] \[ = \sqrt{5.799} = 2.408 \]
  5. Divide every weight by the length — the cells printed on p. 563:

    \[ \text{data:}\quad 0.7615 / 2.408 = 0.316 \] \[ \text{website:}\quad 1.523 / 2.408 = 0.632 \]
  6. Same recipe for T1: the unique terms building, application and for weigh 1.523 each, data and mining 0.7615, and crm, in two titles, gets \(\log 2 \times \log 4.5 = 1.043\). The length:

    \[ \sqrt{3 \times 1.523^2 + 2 \times 0.7615^2 + 1.043^2} \] \[ = \sqrt{9.206} = 3.034 \]
  7. Divide: data and mining 0.251, crm 0.344, the unique words 0.502 — again the printed cells.

    \[ 0.7615 / 3.034 = 0.251 \] \[ 1.043 / 3.034 = 0.344 \]

Check T4 without a calculator: since \(\log 9 = 2 \log 3\), its vector is proportional to (1, 1, 2, 2), of length \(\sqrt{10}\), so data \(= 1/\sqrt{10} = 0.316\) and website \(= 2/\sqrt{10} = 0.632\).

"TF-IDF is one formula." No: the deck prints two TFs and two IDFs, and the table of p. 563 follows p. 562's pair only. With p. 560's fraction, relationship in T2 would be 0.556, not 0.468; with p. 561's IDF, data in T4 would be 0.302, not 0.316. At the exam, say which variant you use.

From vectors to a ranking

The third line of p. 559 says "The distance between any pair of vectors is computed". Which distance? For unit vectors the Euclidean distance and the cosine similarity give the same ranking — four short steps show why.

θ query q document d distance both have length 1 distance² = 2 − 2 cos θ cos θ = q · d the dot product smaller angle, closer
Fig. 4. The query \(\vb{q}\) and a document \(\vb{d}\) as unit vectors. The chord between their tips is the distance, and it grows with the angle: distance² = 2 − 2 cos θ. Rank by the shortest chord or by the largest cosine — the order is the same.
  1. Write the squared distance between the query \(\vb{q}\) and a document \(\vb{d}\) as a dot product:

    \[ \lVert \vb{q} - \vb{d} \rVert^2 = (\vb{q} - \vb{d}) \cdot (\vb{q} - \vb{d}) \]
  2. Expand it as you would \((a - b)^2\):

    \[ = \vb{q} \cdot \vb{q} - 2\, \vb{q} \cdot \vb{d} + \vb{d} \cdot \vb{d} \]
  3. Both vectors are normed, so \(\vb{q} \cdot \vb{q} = \vb{d} \cdot \vb{d} = 1\); and for unit vectors the dot product is the cosine of the angle between them:

    \[ \lVert \vb{q} - \vb{d} \rVert^2 = 2 - 2 \cos\theta \]
  4. The distance falls exactly when the cosine rises. Ranking by the smallest distance or by the largest cosine gives the same order, and the one number to compute is \(\vb{q} \cdot \vb{d}\).

So the score is the dot product, and for sparse vectors it is short: only terms both documents contain survive, every other product has a 0 in it. T1 and T4 share data and mining, each contributing \(0.251 \times 0.316\):

\[ \begin{aligned} s(T_1, T_4) &= 2 \times (0.251 \times 0.316) \\ &= 0.159 \end{aligned} \]

Repeat it for the other six titles and you get the ranking of p. 564:

The ranking of p. 564 with the scores computed from the table of p. 563 (the slide prints only the order).
ranktitledot productscore
#1T4 Data Mining Your Websitedata, mining: 2 × 0.251 × 0.3160.159
#2T2 Accelerating Customer…crm: 0.344 × 0.2960.102
#3T3 Mastering Data Mining…data, mining: 2 × 0.251 × 0.1870.094
—Not recommended: T5, T6, T7, T8none0

The computed scores reproduce the printed order exactly. Now take the computation apart yourself.

The TF-IDF lab: eight titles, one query

The collection is the eight titles of p. 557; the query is any text you type, analysed like the titles (lower-cased, plurals stemmed). The bars rank the titles by the dot product of their normed vectors with the query's; the table below them shows each step for all 29 terms, with the explained title's column next to the query's and the cells of their shared terms highlighted. The three switches are the slides' other variants.

  1. Leave the query at title 1 and the table at "normed TF-IDF". T3 and T4 share the same two words with it. Before you read the bars, predict which of the two scores higher. Then set "explain the score of" to T4 and to T3, and switch the table to "TF × IDF, before normalising".
    What you should see

    T4: 0.251 × 0.316 + 0.251 × 0.316 = 0.159. T3: 0.251 × 0.187 + 0.251 × 0.187 = 0.094. Before normalising, data shows the same 0.762 (0.7615 to four decimals) in both columns; the last row gives the lengths, 2.408 for T4 and 4.074 for T3. The division by the length is the whole difference.

  2. Pick the query "customer relationship management" — what CRM stands for. Predict the #1 title, and the score of T1, the book whose title says CRM.
    What you should see

    #1 is T8, Customer knowledge management, with 0.503 (customer and management), then T3 with 0.407 and T2 with 0.393. T1 scores 0: its "crm" is another token. This is what the lab is built to show: a score is a sum over shared tokens, so a meaning that is not spelled the same way does not exist for it.

  3. Back to title 1. Switch on "remove stop words, as p. 559 says". Predict: does the order of p. 564 — T4, T2, T3 — survive?
    What you should see

    No. T4 0.237, T3 0.134, T2 0.123: #2 and #3 swap, and the check readout no longer matches p. 563. The slide's own ranking is computed with every stop word kept.

  4. Switch "remove stop words" off again, then switch on the TF of p. 560 and watch the readout "normed table vs p. 563". Switch it off and do the same with the IDF of p. 561. Which columns change each time?
    What you should see

    With p. 560's TF, 7 of the 232 printed cells differ, all in column T2 (relationship 0.556 instead of 0.468): in every other title each term occurs once, and the \(1/|d|\) cancels in the normalisation. With p. 561's IDF, 38 cells differ, in every column but T6, whose two words have the same df; data in T4 becomes 0.302. Only p. 562's pair reproduces the printed table.

Back to the puzzle

Both questions of the opening now have answers. The same two words count for more in T4 because normalisation spreads each title's unit length over its terms, four in T4 and eleven in T3: 0.316 against 0.187 per word, 0.159 against 0.094 in total.

And CRM stays invisible because the system compares tokens, not meanings: "crm" and "customer relationship management" are different strings. T3's three spelled-out words earn it nothing, and T8's score is a sum over an empty set, exactly 0. Type the expansion into the lab and the picture turns over — T8 rises to #1 with 0.503, and the book that says "CRM" drops to 0 (Figure 5).

query: T1 T8 building data mining application for crm customer knowledge management score 0 nothing shared

Before: the query T1

expanded query T8 customer relationship management customer knowledge management score 0.503 two shared

After: CRM spelled out

Fig. 5. The score is a sum over the lines, one line per shared term. Left: T1 and T8 have no token in common, so the sum is empty and the score is exactly 0, although CRM stands for customer relationship management. Right: spell CRM out and the query shares customer and management with T8 — 0.503, the top score in the lab.

Seeing that two strings mean the same thing needs a representation of meaning: embeddings, which place related texts close together whatever their spelling (lesson 27). If you have met word embeddings in deep learning, this is where they come back — compared with the same cosine.

A lexical score is a sum over the shared terms: no shared token, no score — whatever the meaning.

What a real engine computes

Page 560 opens by saying where TF-IDF is used: in the scoring function of Lucene, the search library inside Elasticsearch. The idea is right; the name is out of date.

In Elasticsearch you never compute these weights yourself: a match query (lesson 26) returns the titles that share a term with the query, sorted by BM25 score — T8 would not even be listed.

Under the hood: an index turned inside out

So far you looked at every title. "On the internet, time affects attention", p. 565 warns: "attention is money", and "search engines need to respond in tenths of a second". Reading every document at query time is out of the question; the answer must be prepared before the query arrives.

The preparation is the inverted index, "the building blocks of search engines", "made of mappings: TermIDs => DocumentIDs" (p. 566). It is the index at the back of a textbook: you do not read four hundred pages to find "mitochondria", you look the word up and get a list of pages.

Inverted index — for every term, the list of the documents that contain it, called its posting list. "Inverted" because a document naturally lists its words; the index lists, for each word, its documents.

Page 568 builds one from "The quick brown fox jumped over the lazy dog" and "Quick brown foxes leap over lazy dogs in summer". The index "Lists every unique word from every document and identifies which documents a word appears in": "quick" -> D1,D2, "fox" -> D1, "summer" -> D2… Two entries reveal what the slide does not say. "quick" -> D1,D2, though D2 writes Quick: the index lower-cased. "fox" -> D1 only, though D2 has foxes: no stemming, so foxes is another term. An index finds exactly the token it stored, so the query must be cut the same way — what Elasticsearch calls analysis (lesson 25).

Build an inverted index and join two posting lists

Three short documents: the two of p. 568 and a third that is yours. The two switches decide how text is cut into terms, for the documents and for the query alike. The drawing shows the posting list of each query term and the joined result; the table below it is the whole index, as the engine stores it.

  1. With the slide's settings (lower-case on, stemming off), predict the answer to "quick fox" before you look.
    What you should see

    D1 only. quick -> D1, D2, but fox -> D1: D2 says "foxes", which this index keeps as a different term. The engine answered from two posting lists without opening a document — and it found exactly the tokens it stored. That is the insight of this widget.

  2. Switch on stemming. Which posting lists change, and what does "quick fox" return now?
    What you should see

    fox gains D2 (foxes → fox) and dog gains D2 (dogs → dog); the index shrinks from 13 terms to 11, and "quick fox" returns D1 and D2. The query was stemmed too: documents and query must be analysed the same way.

  3. Switch stemming off again and lower-casing off. Predict the posting list of "quick".
    What you should see

    quick -> D1 only, and a separate term Quick -> D2; The and the split as well, both in D1. "quick fox" still returns D1, but a user who types "Quick fox" gets nothing: Quick is only in D2, fox only in D1.

  4. Lower-case on, stemming off. Type a third document, "A quick dog", then ask "quick dog" with AND and with OR.
    What you should see

    AND gives D1 and D3 (quick -> D1, D2, D3; dog -> D1, D3); OR gives all three, the union. Switch stemming on and the AND gives all three as well, because "dogs" in D2 becomes dog.

A query is a join of posting lists

"Computing retrieval function involves: finding all documents containing set of terms, i.e. computing a join over the posting lists" (p. 567). For "quick fox" the engine intersects two short lists, D1, D2 and D1: the answer is D1 — in SQL terms, a join on the document id. With both lists sorted by document id, one pass over each suffices, and no document is opened (background, not on the slide). OR takes the union; only its documents get scored.

Small enough to stay in memory

The lists must be small and quick to read. Page 566: they are "compressed with integer compression algorithms that allow for fast decompression, take statistics of text into account, are in blocks to allow for easy reading" — and "why compressed? to reduce the amount of space in memory". An index that fits in RAM is read at memory speed, and decompressing a block costs less than fetching it from disk.

One common trick (background, not on the slide) shows what "statistics of text" can mean: store a sorted id list as the gaps between ids. A frequent term's ids lie close together, so the gaps are small numbers needing few bits (Figure 6, left).

Stopping early

Page 567 adds a second speed-up: "Entries in the posting list are sorted from most important documents (with highest term counts) to least", which "allows for early termination". The engine computes "bounds on scores" — the best score an unread document could still reach — and when that bound cannot beat the results found, it skips the rest: "lower ranked documents dropped as early as possible". The last bullet adds index pruning techniques, which "get rid of documents that would never be retrieved for a certain query": their entries are never read at all. The top 10 of a billion cost a small fraction of the billion.

document ids, increasing data 3 7 8 15 21 22 stored as gaps: id − previous id 3 4 1 7 6 1 block block small numbers, few bits read and decoded a block at a time

Sorted by document id: small gaps

highest term count first data D7 D2 D9 D4 D1 D5 count 5 4 2 1 1 1 stop here top 3 wanted: the entries left have lower counts, so they are skipped

Sorted by importance: early stop

Fig. 6. Two ways to store one posting list. Left: ids in increasing order, stored as gaps — small integers that compress well, kept in blocks that are read as a unit (p. 566). Right: the slide's order (p. 567), most important documents first — once the entries still unread cannot beat the results found, the engine stops reading. One query term here; with several, the engine keeps a bound for each.
Sorted by importance, or by document id?

Document-id order gives small gaps and one-pass intersections; importance order brings the best documents first. Lucene, inside Elasticsearch, keeps document-id order and stores per block the best score a document in it could reach, skipping blocks that cannot reach the top — both ideas at once (background, not on the slide). At the exam write the slide's version, knowing it is one of two layouts.

The inverted index answers from term lists, never from the documents: the lists are joined, compressed to stay in memory, and ordered so that the engine can stop early.

Exam-style questions

Theory questions in the forms the readme of the past papers names — multiple choice, true/false and open answers; wrong answers may carry a penalty — plus a short computation of the kind the slides make, and one practical exercise in the wording of a past paper.

Which pairing of a search query with its intent type agrees with the definitions of the lecture?

  • "buy new iPhone 16 now" — commercial/investigational The user is ready to complete an action, buying: transactional.
  • "Facebook login page" — informational The user wants to go to a specific website: navigational.
  • "best laptop for students" — commercial/investigational The user is considering a purchase and wants to compare options or research products (p. 553).
  • "How does user intent work?" — navigational The user wants to learn something: informational.
Show model answer

The third. A user searching "best laptop for students" is considering a purchase and wants to compare options or research products: commercial/investigational intent. The other three queries are transactional ("buy new iPhone 16 now"), navigational ("Facebook login page") and informational ("How does user intent work?").

These are the slide's own four examples, shuffled. The trap is telling commercial (still comparing) from transactional (ready to act). Wrong answers may carry a penalty: tick only what you can justify.

True or false: with the normed TF-IDF vectors of the lecture, ranking documents by their Euclidean distance from the query vector gives the same order as ranking them by cosine similarity.

  • True For unit vectors the squared distance is 2 − 2 cos θ: it shrinks exactly when the cosine grows.
  • False That would hold for raw vectors of different lengths, where a long document is far from everything; normalisation removes the length.
Show model answer

True. After normalisation every vector has length 1, so

\[ \lVert \vb{q} - \vb{d} \rVert^2 = \vb{q} \cdot \vb{q} - 2\, \vb{q} \cdot \vb{d} + \vb{d} \cdot \vb{d} \] \[ = 2 - 2\cos\theta . \]

A smaller distance means a larger cosine, so both criteria give the same ranking, and the score to compute is the dot product of the normed vectors.

If the question comes as an open one, write the one-line derivation, not only the verdict. Without normalisation the two orders can differ: a long document is far from every short query even when it points the same way.

Consider the Dish entity of the restaurant ER diagram of the exam of 6 Sept 2024: Dish (Dish_ID, Name, Price, Recipe, Description). Three dishes are named D1 "grilled salmon", D2 "salmon tartare with avocado" and D3 "grilled octopus". Treat each name as a document (lower-case, no stemming, every word kept) and use the formulas of the lecture: TF = log(count + 1), IDF = log((#docs + 1) / #docs-the-term-occurs-in), then normalise each vector to length 1. Which dish is the most similar to D1? Enter its similarity score with three decimals.

Show model answer

#docs = 3. df: grilled 2, salmon 2, tartare 1, with 1, avocado 1, octopus 1. IDF: df 2 gives log(4/2) = log 2, df 1 gives log 4 = 2 log 2. Every count is 1, so TF = log 2 for every term, and each raw weight is (log 2)² times 1 (df 2) or times 2 (df 1); the common factor cancels in the normalisation.

D1 is proportional to (grilled 1, salmon 1): 0.707 each. D2 is proportional to (salmon 1, tartare 2, with 2, avocado 2), length √13: salmon 0.277. D3 is proportional to (grilled 1, octopus 2), length √5: grilled 0.447.

sim(D1, D2) = 0.707 × 0.277 = 0.196; sim(D1, D3) = 0.707 × 0.447 = 0.316. D3 is the most similar, with 0.316.

The scenario comes from the paper; the question does not — no past paper asks for a TF-IDF computation. Show the order TF, IDF, normalisation, and let the dot product run over the shared terms only. Both rivals share one word with D1; the shorter name keeps more weight per word — T4's advantage on p. 563 again. The base of the logarithm cancels.

Using the formulas of the lecture (TF = log(count + 1), IDF = log((#docs + 1) / #docs-the-term-occurs-in), then normalisation), explain why the word "data" has weight 0.316 in the title "Data Mining Your Website" but 0.187 in "Mastering Data Mining: The Art and Science of Customer Relationship Management". What would the second weight become if the word "the" were removed from that title?

Show model answer

In both titles "data" occurs once, so TF = log 2, and it occurs in 3 of the 8 titles, so IDF = log(9/3) = log 3: the raw weight is the same, log 2 × log 3 = 0.7615. The difference comes from the normalisation, which divides each weight by the Euclidean length of the whole title vector: 2.408 for the four-term title, 4.074 for the eleven-term one. So 0.7615 / 2.408 = 0.316 and 0.7615 / 4.074 = 0.187: the same word counts for more in a short document. Removing "the" removes one raw weight of 1.523 from the sum under the square root: the length drops to √(16.598 − 2.320) = 3.779, and "data" rises to 0.7615 / 3.779 = 0.202, although its TF and IDF do not change.

Three things to say: same TF, same IDF, different length. The trap in the second part is to think the weight of "data" cannot change because nothing about "data" changed — normalisation couples every word of a document.

What is an inverted index? Explain how a search engine uses it to answer a query with several terms, and why, according to the lecture, its posting lists are compressed and sorted from the most important documents to the least.

Show model answer

An inverted index is the building block of a search engine: a mapping from each term (TermID) to the list of the documents that contain it (DocumentIDs), its posting list. It is called inverted because it turns the natural direction, document to words, into word to documents. To answer a query with several terms, the engine finds all documents containing the set of terms by computing a join over their posting lists — the intersection for AND, the union for OR — without reading the documents. Search engines must respond in tenths of a second, so the lists are compressed with integer compression algorithms that allow fast decompression, take the statistics of text into account and are organised in blocks for easy reading; the reason is to reduce the space in memory, so that the index is kept and read in RAM. Sorting each posting list from the most important documents (highest term counts) to the least allows early termination: the engine computes bounds on the scores that the remaining documents could reach and drops lower-ranked documents as early as possible, while index pruning removes entries that would never be retrieved for a query.

Four things to cover: the mapping, the join, why compression (memory, hence speed) and early termination. With time to spare, add the hidden assumption of the slide's example: "fox" -> D1 only, because the index did not stem "foxes".

Exam of 24 June 2024, exercise 1. Consider the ER diagram representing a data structure for tracking Disney's digital products. Company Section (ID, Name, Description, Number of Employees); Digital Content (Title, Release Date, Duration, Production Cost, Minimum Age), with the sub-entities Series (Number of Episodes, …) and Movie (Sequence Number, Nominated for Award (Yes/No), …), (T, E), and Animated Movie (…), a sub-entity of Movie, (P, O); Character (Name, Nickname, Age); Actor (Personal ID, Name, Surname, Age, Birth Date, Career Description), with the sub-entity Voice Actor (Voice Tone, Voice Strength (from -5 to 5)), (P, O); Script (ID, Length, Duration, Title); Location (ID, Name, Description, Furniture (Text), Indoor (Yes/No)); Line (ID, Sequence Number, Text). Relationships: Play, Character (1:1) – Actor (1:N); Involve, Character (1:N) – Digital Content (1:N); Produce, Company Section (1:N) – Digital Content (1:N), with Starting Date and End Date; Describe, Digital Content (1:N) – Script (1:1); Include, Script (1:N) – Line (1:1); Perform, Actor (1:N) – Line (1:1), with Recording Date; Located, Script (1:N) – Location (1:1).

Which DB technology would be the best to store the entities/rel. of the ER diagram? [you may not need all the rows of the table] (1 PT) — ENTITIES / REL. | DB TYPE | MOTIVATION

Show model answer
ENTITIES / REL.DB TYPEMOTIVATION
Character, Actor, Voice Actor, Line; Play, PerformGraph DB (Neo4j)Many links traversed and counted (lines an actor performed, characters an actor played); the (P, O) Voice Actor is a second label on the same node; Recording Date is an edge property.
Company Section, Digital Content, Series, Movie, Animated Movie, Script; Produce, DescribeDocument DB (MongoDB)A digital content is read as one aggregate with its scripts embedded (each script describes exactly one content); the sub-entities have different attributes, which schema-less documents hold without empty fields; Produce, with its dates, is a sub-collection of each content.
Location (Name, Description, Furniture)Search-based DB (Elasticsearch)Description and Furniture are free text, queried by words and ranked by relevance: an inverted index finds the locations that contain the words, and a TF-IDF-family score orders them; Indoor is an exact value for counting.

Involve, Include and Located cross the groups: keep them as identifiers inside the documents or nodes they connect.

The grouping follows the paper's own later exercises: Neo4j on Character, Actor, Voice Actor and Line; MongoDB on Company Section, Digital Content with its sub-entities and Script; Elasticsearch on Location. Its exercise 4 asks for the Locations whose description includes "Stadium" and "Basketball", "assigning a higher score" to those whose furniture includes "Planet" and description "Space": a ranking, not a WHERE clause. That is the motivation the third row must give — free text, an inverted index, a relevance score.

Check yourself

You delete the word "the" from T3 and recompute the normed vectors. What happens to the weight of "data" in T3?

  • It stays 0.187: the count and the IDF of "data" did not change TF and IDF are unchanged, but the length of T3's vector shrinks, and every weight is divided by that length.
  • It grows, to about 0.202 One raw weight fewer under the square root: the length falls from 4.074 to 3.779, and 0.7615 / 3.779 = 0.202.
  • It drops, because T3 now has fewer words in common with T1 A weight inside T3 does not depend on T1 at all; and T1 never contained "the".
  • It becomes 0.316, as in T4 T3 still has ten weighted terms against T4's four, so its length stays larger.

Suppose every one of the eight titles also contained the word "book". Which IDF does "book" get?

  • 0 with both formulas: a word in every document carries no information That is p. 561's value only, log(8/8) = 0. The +1 of p. 562 gives log(9/8).
  • 2.197 with both, the highest IDF on the shelf 2.197 = log 9 belongs to a term in a single title; "book" is in all eight.
  • 0.118 with p. 562's formula and 0 with p. 561's log(9/8) = 0.118 and log(8/8) = 0: the +1 keeps a universal term small but never exactly zero.
  • 1 with both, since it occurs in 8 of 8 titles IDF is the logarithm of a ratio, not a frequency; 8 of 8 gives log 1 = 0 in p. 561's formula.

Which changes would give T8, Customer knowledge management, a score above 0 against the query T1, Building data mining applications for CRM? Select all that apply.

  • Removing the stop words from all titles T8 has no stop word and shares no token with T1 either way.
  • Expanding "crm" in the query into "customer relationship management" before scoring Then the query shares customer and management with T8, so T8 scores above 0 (in the lab, the query "customer relationship management" alone puts T8 first, with 0.503).
  • Using the TF of p. 560 instead of p. 562's Whatever the TF, a term T8 does not contain is multiplied by 0 in the dot product.
  • Comparing embeddings of the two titles instead of their words Embeddings place texts with related meanings close together, whatever their spelling (lesson 27).
  • Scoring with BM25 instead of TF-IDF BM25 is lexical too: a sum over the shared terms, and there are none.

Only a change of what counts as "the same term" helps: an expansion of the query or a representation of meaning.

T3 and T4 share exactly the same two words with the query, data and mining. Why does T4 score 0.159 and T3 only 0.094?

  • "data" and "mining" occur more often in T4 Once each, in both titles.
  • Their IDF is higher in T4 IDF belongs to the term, not to the document: log 3 in both titles.
  • T3 also shares "customer" and "relationship" with the query, which lowers its score The query T1 contains neither word; and with non-negative weights an extra shared term could only add to a dot product.
  • T4 is shorter, so after normalisation each of its terms keeps a larger share of the length 1 Lengths 2.408 against 4.074, hence 0.316 against 0.187 per word.

On the index of p. 568 — lower-cased, not stemmed — the query "quick fox" with AND returns…

  • D1 quick -> D1, D2 and fox -> D1: the intersection is D1.
  • D1 and D2 That needs a stemmer: D2 says "foxes", which this index keeps as another term.
  • D2 D2 contains quick (from "Quick") but not fox.
  • nothing, because "Quick" and "quick" differ This index lower-cased: "quick" -> D1,D2 is printed on the slide.

Why does the lecture compress posting lists (p. 566)?

  • To hide their content from whoever reads the disk Compression is not encryption.
  • To save disk space; reading them gets slower, but that is the price The slide lists compression under "engineered to be fast", with codes chosen for fast decompression.
  • To reduce the amount of space in memory, so the index can be kept and read in RAM "why compressed? to reduce the amount of space in memory" — and memory is what makes tenths of a second possible.
  • Because posting lists are stored as text They store integers — document ids — hence "integer compression algorithms".

A posting list is sorted from the documents with the highest term counts to the lowest (p. 567). How does that let the engine stop early when it needs only the top 10?

  • It reads the first 10 entries and stops, whatever their scores With several query terms a document can score high through another term; the engine stops when a bound says nothing left can enter the top 10, not after a fixed count.
  • It keeps a bound on the best score the unread documents could still reach, and stops when that bound falls below the 10th best score found "compute bounds on scores", "lower ranked documents dropped as early as possible".
  • It deletes the low-count entries from the index while answering Nothing is deleted while a query runs: early termination only skips the rest of the list for this query. Getting rid of entries for good is index pruning, the last bullet of p. 567.
  • It reads the list backwards, from the least important documents The order exists so that the most important entries come first.

Key take-aways

What to watch and read