s LearnSqueak.com

PRACTICAL SQUEAK WORKSHOP

Build a local document search index

Turn an explicit fictional corpus into a positional inverted index with AND queries, phrase matching, highlighted snippets and atomic updates.

9 construction stagesTested source & checkpointsNative screenshots & demos
Try the finished example

Run in the SqueakJS playground

The separate playground loads the real Smalltalk image on demand. This lesson keeps its native setup instructions; browser compatibility notes appear beside each demo.

Before you start

Turn an explicit fictional corpus into a positional inverted index with AND queries, phrase matching, highlighted snippets and atomic updates.

Each numbered source is complete and cumulative. Start with any checkpoint in a fresh image, then run its exact Workspace block. The displayed Browser method is an excerpt already installed by that checkpoint.

  • Comfort with classes, arrays, dictionaries and blocks
  • A working Squeak 6.1 image and the File List / Workspace tools

Classes and objects · Using Squeak’s tools

  • Save a copy of your image before experimenting. Download a checkpoint .st file beside that copy, select it in the File List, and choose fileIn.
  • Close the previous tutorial window before installing another checkpoint. Select the complete Workspace block and use Do it (Ctrl+D or Cmd+D).
  • Accept displayed method definitions only in the named class and instance-side Browser category; a Workspace expects expressions, not method definitions.
  • For final verification, file in LearningSearch.st and LearningSearchTests.st, then evaluate TestRunner openForSuite: LSSearchTest suite.

01 · Begin with a small explicit corpus

Search starts with a clearly defined collection. LSIndex stores each document under a stable string ID, with a title and body. The bundled corpus is deliberately fictional and supplied directly in source; there is no folder scan, upload or external service. Titles help people read results while only bodies will be indexed. A stable ID is different from a title: you can revise a title without creating a second document. Every checkpoint uses this same small corpus so you can predict and verify each new operation.

Where to run this

System Browser, LSIndex, instance side. This method is already installed by checkpoint 01.

Construction code · follow the run instructions above
putId: id title: title body: body
 self validateId: id title: title body: body.
 documents at: id copy put: {title copy. body copy}

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app showCorpus.
app
  • IDs choose replacement identity; titles are human-facing labels
  • Detached copies keep callers from altering the corpus through returned collections
  • Input validation bounds the corpus to 30 documents with 80-character titles and 12000-character bodies

The lower panel scrolls. Read the orchard and observatory bodies now: both contain blue and moon, but only one initially contains the adjacent phrase.

Expected result

The native scroll pane shows five fictional documents: kitchen, orchard, river, space and workshop. No terms are indexed yet.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Begin with a small explicit corpus in native Squeak 6.1
Native Squeak 6.1 checkpoint 01, rendered after executing the exact Workspace block above.

02 · Preserve source spans while normalizing words

A tokenizer defines what the search tool means by a word. This one groups ASCII letters and digits, lowercases the resulting term, and records its original character span. Punctuation and whitespace act as separators. Keeping both the normalized value and the span is important: searching should ignore case, while the final snippet should preserve the original spelling and punctuation. The cursor either advances over a word or advances over one separator, so an empty or punctuation-only input terminates cleanly with no tokens.

Where to run this

System Browser, LSTokenizer, instance side. This method is already installed by checkpoint 02.

Construction code · follow the run instructions above
tokens: text
 | result cursor start |
 text size > 12000 ifTrue: [self error: 'Limit: 12000 characters per document'].
 result := OrderedCollection new. cursor := 1.
 [cursor <= text size] whileTrue: [
  (self isWord: (text at: cursor)) ifTrue: [
   start := cursor. [cursor <= text size and: [self isWord: (text at: cursor)]] whileTrue: [cursor := cursor + 1].
   cursor - start > 64 ifTrue: [self error: 'Limit: 64 characters per token'].
   result size >= 3000 ifTrue: [self error: 'Limit: 3000 tokens per document'].
   result addLast: {(text copyFrom: start to: cursor - 1) asLowercase. start. cursor - 1}]
  ifFalse: [cursor := cursor + 1]]. ^ result asArray

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app query: 'Red, FOX! Blue-moon.'; showTokens.
app
  • A token is an array of normalized term, start character and end character
  • Hyphens, underscores and apostrophes separate tokens in this deliberately simple policy
  • The original body is retained so highlighting can use its exact character positions

This is an ASCII teaching tokenizer, not a multilingual segmenter or stemmer. apple and apples are different terms.

Expected result

The normalized words are red, fox, blue and moon, each paired with its original one-based start and end positions.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Preserve source spans while normalizing words in native Squeak 6.1
Native Squeak 6.1 checkpoint 02, rendered after executing the exact Workspace block above.

03 · Invert documents into positional postings

A forward view asks which terms occur in a document. An inverted index reverses that relationship: each term maps to document IDs, and each ID maps to an ordered collection of token positions. The index is built once from the explicit corpus. Term queries can then begin with the matching document IDs instead of scanning every body on every search. Positions cost more storage than a set of IDs, but enable phrases without running a separate substring search. indexFor: builds a new dictionary and returns it.

Where to run this

System Browser, LSIndex, instance side. This method is already installed by checkpoint 03.

Construction code · follow the run instructions above
indexFor: aDictionary
 | built | built := Dictionary new.
 aDictionary keys asSortedCollection do: [:id | | tokens |
  tokens := LSTokenizer new tokens: (aDictionary at: id) second.
  tokens withIndexDo: [:token :position | | byDocument |
   byDocument := built at: token first ifAbsentPut: [Dictionary new].
   (byDocument at: id ifAbsentPut: [OrderedCollection new]) addLast: position]].
 ^ built

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app query: 'moon'; showPostings.
app
  • The first dictionary maps term to a per-document dictionary
  • The second dictionary maps document ID to ascending token ordinals
  • Token positions are local to one body; they are not character positions

Click Postings for red, then fox. Their positions differ by one within orchard and river, which anticipates the phrase operation.

Expected result

moon maps to orchard at token position 19 and space at positions 4 and 11. The corpus contains 66 distinct terms.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Invert documents into positional postings in native Squeak 6.1
Native Squeak 6.1 checkpoint 03, rendered after executing the exact Workspace block above.

04 · Intersect documents that contain every term

The All words operation implements AND semantics. It starts with the document set for the first term, then intersects it with the set for each remaining term. A missing term naturally produces an empty set. Repeated query terms do not duplicate results. Sorting IDs before returning the result makes tests and the display predictable; this tutorial intentionally does not claim relevance ranking. An empty query returns no hits rather than unexpectedly dumping every document. Query length and term count are checked before the intersections begin.

Where to run this

System Browser, LSIndex, instance side. This method is already installed by checkpoint 04.

Construction code · follow the run instructions above
terms: query
 | terms candidates | terms := self queryTokens: query. terms isEmpty ifTrue: [^ #()].
 candidates := ((postings at: terms first ifAbsent: [Dictionary new]) keys) asSet.
 terms allButFirst do: [:term | candidates := candidates intersection: ((postings at: term ifAbsent: [Dictionary new]) keys asSet)].
 ^ candidates asSortedCollection asArray

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app query: 'blue moon'; searchTerms.
app
  • All words ignores order and distance; every normalized term simply must occur
  • Case and punctuation follow exactly the document tokenization policy
  • A query is limited to 160 characters and 12 terms

orchard is an All words hit because Blue butterflies and moon flowers occur at different positions. That does not make it a phrase match.

Expected result

All words returns orchard and space, in deterministic ID order.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Intersect documents that contain every term in native Squeak 6.1
Native Squeak 6.1 checkpoint 04, rendered after executing the exact Workspace block above.

05 · Require adjacent positions for a phrase

Phrase search first uses the AND result to obtain candidate documents. For every occurrence of the first term in a candidate, phraseStarts:in: checks that the second term occurs at start + 1, the third at start + 2, and so on. This uses whole normalized tokens, so red fo does not match red fox. Every position lookup stays inside a single document body, preventing a phrase from bridging two documents. Phrase is an explicit toolbar mode; quote characters are separators rather than a separate query language.

Where to run this

System Browser, LSIndex, instance side. This method is already installed by checkpoint 05.

Construction code · follow the run instructions above
phraseStarts: terms in: id
 terms isEmpty ifTrue: [^ #()].
 ^ (self positionsFor: terms first in: id) select: [:start |
  (1 to: terms size) allSatisfy: [:offset | (self positionsFor: (terms at: offset) in: id) includes: start + offset - 1]]

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app query: 'blue moon'; searchPhrase.
app
  • The same postings support both term and phrase search
  • A phrase requires the specified order and exact token adjacency
  • Punctuation separates tokens, so red, fox and red-fox satisfy the phrase red fox

Phrase matching here can cross punctuation or line breaks within a body. It does not model sentence boundaries, title/body joins, stemming or language-specific word rules.

Expected result

Phrase returns only Moon observatory. orchard no longer qualifies because blue and moon are not adjacent.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Require adjacent positions for a phrase in native Squeak 6.1
Native Squeak 6.1 checkpoint 05, rendered after executing the exact Workspace block above.

06 · Return readable highlighted snippets

A result needs enough context to judge whether it is useful. The snippet builder finds matching token ordinals, obtains their original character spans, and chooses a bounded excerpt around the earliest hit. It creates a Squeak Text value, adding bold and color attributes only to matching spans inside the excerpt. Ellipses indicate clipped context. Phrase mode highlights only tokens participating in a complete phrase; All words highlights occurrences of any query term. TextMorph displays the styled Text inside a native scrolling results pane.

Where to run this

System Browser, LSIndex, instance side. This method is already installed by checkpoint 06.

Construction code · follow the run instructions above
snippetFor: id query: query phrase: isPhrase
 | body tokens positions anchor start stop prefix text |
 body := (documents at: id) second. tokens := LSTokenizer new tokens: body.
 positions := self matchingTokenPositions: query in: id phrase: isPhrase.
 anchor := positions isEmpty ifTrue: [1] ifFalse: [(tokens at: positions asSortedCollection first) second].
 start := (anchor - 45) max: 1. stop := (start + 179) min: body size.
 prefix := start > 1 ifTrue: ['...'] ifFalse: [''].
 text := (prefix, (body copyFrom: start to: stop), (stop < body size ifTrue: ['...'] ifFalse: [''])) asText.
 positions do: [:position | | token from to | token := tokens at: position.
  from := token second max: start. to := token third min: stop.
  from <= to ifTrue: [
   text addAttribute: TextEmphasis bold from: from - start + 1 + prefix size to: to - start + 1 + prefix size.
   text addAttribute: (TextColor color: (Color fromString: '#B44719')) from: from - start + 1 + prefix size to: to - start + 1 + prefix size]]. ^ text

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app query: 'red fox'; searchPhrase.
app
  • Search normalization never rewrites the original body shown to the reader
  • Character offsets are translated into excerpt offsets after any leading ellipsis
  • The body excerpt is at most 180 characters, plus up to two three-character ellipses

Long-result tests verify centered excerpts and bounds. A snippet can cut a word at its edge; expanding to whole-word boundaries is a useful later refinement.

Expected result

The two hits preserve their original prose and highlight the adjacent words red fox in bold rust-colored text.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Return readable highlighted snippets in native Squeak 6.1
Native Squeak 6.1 checkpoint 06, rendered after executing the exact Workspace block above.

07 · Replace a document without stale postings

An update must remove the old document’s contributions as well as add the new ones. For this bounded teaching corpus, rebuilding the complete index is simpler to audit than subtracting individual postings. putId:title:body: validates the draft, copies the document dictionary, inserts the replacement into that candidate, and builds fresh postings from it. Only after tokenization and indexing succeed are documents and postings committed together. An oversized body or token therefore leaves both old structures intact. The Update button demonstrates replacing the stable orchard ID.

Where to run this

System Browser, LSIndex, instance side. This method is already installed by checkpoint 07.

Construction code · follow the run instructions above
putId: id title: title body: body
 | candidate rebuilt | self validateId: id title: title body: body.
 candidate := documents copy. candidate at: id copy put: {title copy. body copy}.
 rebuilt := self indexFor: candidate.
 documents := candidate. postings := rebuilt

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app updateSample.
app
  • The candidate document dictionary is private until rebuilding succeeds
  • Documents and postings are committed together after all validation
  • Replacing an existing ID does not increase the number of documents

Try searching apple after Update: kitchen remains, but orchard must disappear. Updating repeatedly stays at five documents.

Expected result

The revised orchard now contains blue moon, so Phrase returns orchard and space. The old orchard apple posting is gone.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Replace a document without stale postings in native Squeak 6.1
Native Squeak 6.1 checkpoint 07, rendered after executing the exact Workspace block above.

08 · Remove documents and rebuild deterministically

Deletion uses the same candidate-and-commit pattern as replacement. If the ID is absent, removeId: returns false without changing anything; otherwise it builds new postings for the remaining candidate corpus and commits both structures. Repeating the same removal is harmless. The UI reruns the current search in its current mode, which prevents a removed hit from lingering on screen. Reset creates a new index from the five original samples, rebuilds it and reruns the query. Rebuilding an unchanged corpus is idempotent.

Where to run this

System Browser, LSIndex, instance side. This method is already installed by checkpoint 08.

Construction code · follow the run instructions above
removeId: id
 | candidate rebuilt | (documents includesKey: id) ifFalse: [^ false].
 candidate := documents copy. candidate removeKey: id. rebuilt := self indexFor: candidate.
 documents := candidate. postings := rebuilt. ^ true

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app updateSample; removeSample.
app
  • Deleting a document removes every one of its term and position entries
  • Search mode and query survive removal and sample reset
  • A second removal returns false and leaves the corpus consistent

The lesson keeps data in memory. Close and reopen the app to start again; there is no crawling, filesystem persistence or personal-document access.

Expected result

Only Moon observatory remains for blue moon, and the corpus count is four. Reset restores the original five documents.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Remove documents and rebuild deterministically in native Squeak 6.1
Native Squeak 6.1 checkpoint 08, rendered after executing the exact Workspace block above.

09 · Verify input bounds and the native workflow

The complete search tool separates tokenization, indexing, query operations and display. Its SUnit suite tests case normalization, punctuation, repeated terms, adjacency, whole-token matching, document boundaries, snippet spans, update rollback, stale-posting removal, empty inputs and input limits. Native mouse-down/up events drive the toolbar in integration tests, including repeated removal, reset and recovery after rejection. The final source has no filesystem enumeration methods. The bundled corpus and explicit putId:title:body: API make the scope visible and reproducible in a fresh image.

Where to run this

System Browser, LSSearchApp, instance side. This method is already installed by checkpoint 09.

Construction code · follow the run instructions above
rejectHuge
 [index putId: 'oversize' title: 'Rejected sample' body: (String new: 12001 withAll: $x)]
 on: Error do: [:error | statusLabel contents: error messageText, '. Corpus unchanged.']. self refresh

After filing in this checkpoint, evaluate the complete block in a Workspace with Do it. It returns the open native application.

Workspace · run after installing this checkpoint
| app |
app := LSSearchApp open.
app query: 'blue moon'; searchPhrase; rejectHuge.
app
  • The tokenizer rejects tokens over 64 characters and documents over 3000 tokens
  • A failed update preserves both documents and postings
  • The final app and test source are separate files and load without earlier checkpoints

This teaching index is memory-resident and rebuilt on writes. A production system would need persistent storage, incremental updates, ranking, language-aware analysis and a much larger validation plan.

Expected result

The original observatory hit stays visible. The status reports the 12000-character document limit and confirms that the corpus is unchanged.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Verify input bounds and the native workflow in native Squeak 6.1
Native Squeak 6.1 checkpoint 09, rendered after executing the exact Workspace block above.

Watch the workflow

Every still is captured from a native Squeak 6.1 SystemWindow after loading that checkpoint into the unsaved baseline image. Animations combine PNG frames rendered by the running Morphic application while scripted native pointer events operate its actual controls. There are no reconstructed browser mockups.

NATIVE SQUEAK CAPTURE
Build a local document search index demonstration
Native toolbar execution: compare All words and Phrase, inspect postings, and highlight a complete red fox phrase.
NATIVE SQUEAK CAPTURE
Build a local document search index demonstration
Native toolbar execution: replace orchard, remove it, repeat removal, restore the original corpus, and reject an oversized update.

Practice with tested solutions

1. Separate all words from a phrase

Add a fictional note that contains fox before red. Compare the All words and Phrase results, then display the phrase search.

Hint

AND cares about membership; a phrase also cares about adjacency and order.

Show a tested solution

After filing in the final app, select this entire block in a Workspace and use Do it. It opens the app and raises an error if any assertion fails.

Exercise solution
| app |
app := LSSearchApp open.
app index putId: 'practice' title: 'Fictional field note' body: 'A fox rests beside a red gate.'.
app query: 'red fox'; searchTerms.
(app results includes: 'practice') ifFalse: [self error: 'AND missed the note'].
app searchPhrase.
(app results includes: 'practice') ifTrue: [self error: 'Phrase ignored order'].
app results = #('orchard' 'river') ifFalse: [self error: 'Unexpected phrase hits'].
app
Expected

All words includes practice; Phrase excludes it and returns orchard and river.

Download complete exercise solution

Positions distinguish two documents that contain the same words in different order. Each lookup is still scoped to one body.

This exact solution and its assertions were executed successfully in a fresh Squeak 6.1 image.

2. Replace every trace of an old term

Add a note containing amber, then replace the same ID with a cobalt note. Verify amber disappears from postings while cobalt points to the replacement.

Hint

Reuse the same ID. A new title alone does not determine identity.

Show a tested solution

After filing in the final app, select this entire block in a Workspace and use Do it. It opens the app and raises an error if any assertion fails.

Exercise solution
| app |
app := LSSearchApp open.
app index putId: 'practice' title: 'First draft' body: 'An amber lantern glows.'.
(app index terms: 'amber') = #('practice') ifFalse: [self error: 'Missing first version'].
app index putId: 'practice' title: 'Second draft' body: 'A cobalt lantern glows.'.
(app index terms: 'amber') isEmpty ifFalse: [self error: 'Stale amber posting'].
app index documentCount = 6 ifFalse: [self error: 'Replacement made a duplicate'].
app query: 'cobalt'; searchTerms.
app results = #('practice') ifFalse: [self error: 'Missing replacement'].
app
Expected

Only the replacement appears for cobalt; amber has no results and the corpus has six documents.

Download complete exercise solution

Rebuilding candidate postings removes obsolete contributions automatically. A production incremental index would need equally careful deletion of the old document’s postings.

This exact solution and its assertions were executed successfully in a fresh Squeak 6.1 image.

3. Delete one hit without damaging another

Add two fictional notes with the same phrase. Delete one, repeat the deletion and rebuild. Prove the other hit remains.

Hint

The second removal should return false. Rebuilding must not duplicate positions or revive removed documents.

Show a tested solution

After filing in the final app, select this entire block in a Workspace and use Do it. It opens the app and raises an error if any assertion fails.

Exercise solution
| app |
app := LSSearchApp open.
app index putId: 'practiceA' title: 'First fictional note' body: 'silver bell'.
app index putId: 'practiceB' title: 'Second fictional note' body: 'silver bell'.
(app index removeId: 'practiceA') ifFalse: [self error: 'First deletion failed'].
(app index removeId: 'practiceA') ifTrue: [self error: 'Second deletion claimed a change'].
app index rebuild; rebuild.
app query: 'silver bell'; searchPhrase.
app results = #('practiceB') ifFalse: [self error: 'Deletion damaged a different document'].
app
Expected

Only practiceB appears for silver bell after repeated deletion and two rebuilds.

Download complete exercise solution

The stable document ID is the unit of removal. Rebuilding from the remaining corpus is deterministic and cannot recover data that is no longer there.

This exact solution and its assertions were executed successfully in a fresh Squeak 6.1 image.

When something looks wrong

Message not understood after loading an earlier checkpoint

Close the prior window and load the complete checkpoint source in a fresh Squeak 6.1 image. Earlier checkpoints intentionally expose fewer controls and grammar/query features.

A method definition fails in the Workspace

Use the File List to file in the downloaded source. The displayed method belongs in its named class in the System Browser. Only the separate Workspace block is meant for Do it.

The displayed result differs after editing the text

Click Run in the language app, or All words / Phrase in the search app. Each action reads the editor’s current buffer, including unaccepted text.

Verification, cleanup and next steps

39 SUnit tests passed in Squeak 6.1; zero failures and errors.

Token spans, punctuation/case, postings, AND/phrase semantics, whole-token and cross-document boundaries, snippets, atomic update rollback, removal, rebuild, corpus/query limits, native toolbar routes, repeated actions and recovery.

Close the tutorial windows when finished. The apps keep session data only in memory. The downloads contain source and verification notes so you can recreate them in a fresh image.

Explore more working examples · Return to the learning path

Scope of this example

  • Only explicitly supplied synthetic document bodies are indexed; titles and IDs label results
  • ASCII letters/digits define tokens; punctuation and line breaks separate them, and phrases can cross those separators
  • No ranking, stemming, personal-folder crawling, external service or persistent index is included