AAmit’s LibraryLEARN · PRACTISE · REFLECT

Information retrieval · Worked keyword lab

Which words brought this result? A first keyword index

Start here: You only need lists and counting. Python is optional for following the hand-worked search. These five invented notes come from a small event desk. The goal is to find information about a covered place to wait, not to generate an answer.

Five invented event-desk notes
IDNote
D1The rain shelter is open.
D2The rain closed the shelter.
D3The shelter is for bikes.
D4The covered pavilion is open.
D5Rain, rain cancels the tour.

Turn each note into searchable terms

For this toy, take each continuous run of ASCII letters (A–Z or a–z), then lowercase it. Spaces, punctuation and digits separate tokens. Use the same rule for the notes and searches. We keep words like “the”, do not trim word endings, and do not add synonyms. This simple rule is for the invented English examples, not a general tokenizer.

D5 becomes rain rain cancels the tour. Keep token order for phrase checks. For the index, add an ID once per term even if that term repeats in its note. An inverted index is a lookup from a term to the IDs that contain it. The ID lists are called postings. Here is part of the index:

Example terms and the notes containing them
TermPostings
rainD1, D2, D5
shelterD1, D2, D3
pavilionD4
theD1, D2, D3, D4, D5

Trace two searches by hand

Search 1: RAIN-shelter!. The query terms are rain and shelter. Look up both lists. Offer every note found in either list. Score each by the number of different query terms it contains. Higher score goes first; ties are broken by ID text order (D1 to D5 here). No shared term means no result, not a score-zero entry.

Scroll to see all columns of the ranking.

Search 1 results before requiring a phrase
RankNoteWhy it appearsScore
1D1rain, shelter2
2D2rain, shelter2
3D3shelter1
4D5rain1

D5 gets one point, not two, even though it repeats “rain”. D4 gets no point. If you require a phrase using the same two query tokens, keep only notes that contain rain followed immediately by shelter in their normalized token sequence. Only D1 remains. D2 has both tokens, but they are apart. The ID-only postings cannot settle adjacency; this example checks the stored token order.

The high overlap for D2 does not mean the shelter is open. D2 says it was closed. D3 is about a bike shelter. Read the note and check which claim it actually supports; no score here decides relevance or current status.

Search 2: canopy. The term is absent from the index, so the result is empty. D4 might still help the reader who wants cover, even though it says “covered pavilion”, not “canopy”. An empty result means this literal rule found no match, not that there was no relevant note.

Try it

What happens if you search rain rain? Compare ordinary ranking with phrase mode.

Check your answer

Ordinary ranking counts rain once as a query term. D1, D2 and D5 each score 1, in ID order. Phrase mode checks both token positions, so only D5 remains.

Check with Python

import re
from collections import defaultdict

notes = {
    "D1": "The rain shelter is open.",
    "D2": "The rain closed the shelter.",
    "D3": "The shelter is for bikes.",
    "D4": "The covered pavilion is open.",
    "D5": "Rain, rain cancels the tour.",
}

def tokens(text):
    return tuple(word.lower() for word in re.findall(r"[A-Za-z]+", text))

ordered = {doc: tokens(text) for doc, text in notes.items()}
postings = defaultdict(set)
for doc, words in ordered.items():
    for term in set(words):
        postings[term].add(doc)

def search(query, phrase=False):
    words = tokens(query)
    terms = set(words)
    candidates = set()
    for term in terms:
        candidates.update(postings.get(term, ()))

    scores = []
    for doc in candidates:
        doc_words = ordered[doc]
        if phrase and not any(
            doc_words[i:i + len(words)] == words
            for i in range(len(doc_words) - len(words) + 1)
        ):
            continue
        score = sum(doc in postings.get(term, ()) for term in terms)
        scores.append((doc, score))
    return sorted(scores, key=lambda item: (-item[1], item[0]))

print(search("RAIN-shelter!"))
print(search("RAIN-shelter!", phrase=True))
print(search("canopy"))
[('D1', 2), ('D2', 2), ('D3', 1), ('D5', 1)]
[('D1', 2)]
[]