Encode a small local collection and query with the same Sentence Transformers model, then rank the normalized vectors by similarity. Keep the original source IDs with the ranked snippets. Test a clear paraphrase, a misleading near match, and an unrelated query before relying on the search.
Define what a result is allowed to mean
Build this as a document lookup tool. The output can point you to likely passages. It gives you an ordered list, and you still open the source when the meaning matters. Define the unit you will search. A small paragraph with a stable source ID is enough for a first version. An entire mixed-topic document can make it harder to understand which part supports the result. Start with short passages that each have a clear purpose.
Use three invented records. Let BIRCH-01 say “The front desk lends video adapters for the projector.” Let ALDER-02 say “Replacement projector lamps are stored in the maintenance cabinet.” Let CEDAR-03 say “The print lab collects proof sheets at noon.” Test with “Where can I borrow a connector for the display?” The best intended passage is BIRCH-01, because it describes borrowing a connector. ALDER-02 has a device-related overlap but gives a different action and supplies. The model may still rank them unexpectedly. Write down your expected best source before running the test.
Pick a second query that matches none of the records, such as “When does the bicycle workshop close?” A similarity ranking will still have a first row when there is no useful result. Keep this case to test what the application should show when it needs human review rather than an automatic answer. You can start with a top-results display and let the reader decide. A numeric threshold requires separate checks with your own model and material.
Load a complete local embedding model
Use a Python environment with Sentence Transformers available and a model stored in a local directory. Review the model’s input conventions and choose one intended for text similarity. Some models use different query and document prefixes or encoding methods. The small example below assumes a model whose documentation supports using the same encode method for query and passages. Use the recommended model-specific method in a real project. Sentence Transformers model and encoding API
Before going offline, confirm the local model directory holds the files your installed package expects. An incomplete path can lead to a missing resource or a request for a download in other configurations. This example explicitly uses a local directory and asks the library to restrict file lookup to local resources. It also leaves remote model code disabled. If your model requires additional reviewed local code, check those requirements separately before changing that behavior.
Use a plain JSON file with a list of objects holding id and text. Add the three sample passages or your own short collection. Keep IDs unique within the file. You can include additional review information elsewhere, such as a document title or a link to a location on your own Mac. Use those fields for display and provenance. The model only needs the actual text for this exercise.
Encode and rank without a separate index service
Install the library in the Python environment you use for the project, following its current installation documentation. Save this script as localsearch.py. It uses the CPU for the exercise, so it does not depend on a specific acceleration setting. Files are read locally, and it prints a ranking without changing the collection.
import json
import sys
from pathlib import Path
from sentence_transformers import SentenceTransformer
def main():
if len(sys.argv) != 4:
raise SystemExit("Usage: localsearch.py MODEL_DIR DATA.json QUERY")
model_dir = Path(sys.argv[1]).expanduser()
if not model_dir.is_dir():
raise SystemExit("Use an existing local model directory")
entries = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))
query = sys.argv[3].strip()
if not entries or not query:
raise SystemExit("A nonempty collection and query are required")
ids = [entry["id"] for entry in entries]
if len(ids) != len(set(ids)):
raise SystemExit("Every source ID must be distinct")
model = SentenceTransformer(
str(model_dir), device="cpu", local_files_only=True, trust_remote_code=False
)
passages = model.encode(
[entry["text"] for entry in entries],
normalize_embeddings=True, convert_to_numpy=True
)
needle = model.encode(
[query], normalize_embeddings=True, convert_to_numpy=True
)[0]
scores = passages @ needle
order = sorted(range(len(entries)), key=lambda i: (-float(scores[i]), ids[i]))
for i in order[:3]:
print(f"{ids[i]} {scores[i]:.4f} {entries[i]['text']}")
if __name__ == "__main__":
main()
Quote the query as one command-line argument when running the script. Substitute your own model path and collection. The normalized embeddings let the dot product serve as cosine similarity for the ranking. The code keeps the source array in the same order as the passage matrix, then returns the source ID and text for each row. Two equal scores use ID order as a deterministic tie-breaker. Sentence Transformers semantic search documentation
Inspect the returned passages
Start with the projector connector question from the practice set. Open the highest ranked passage and check whether it actually gives a borrowing location. If ALDER-02 leads, the model may be focusing on equipment nouns instead of the lending action. Keep the unexpected order in your notes and try a second query with borrow adapter. A clear result for one wording and a poor result for the paraphrase tells you where the lookup needs work.
Use a query that directly repeats one entire sample passage. It should ordinarily retrieve that passage well for an encoding approach where query and passage use the same representation. If it instead displays text from an unrelated record, inspect how rows are paired with vectors. A useful debugging step is to print the source ID immediately before encoding and immediately after sorting. Confirm that each displayed text actually belongs to the label beside it.
Next, run the unrelated bicycle question. The script will rank a result because it calculates an order for every available entry. Decide how to present that result in a real interface. A panel can explicitly show possible matches with snippets, while a fact-answer feature should ask the user to review a real source. Do not treat a high-looking score as a probability that the passage answers the question. Compare values from unrelated and appropriate cases within the same model before considering any threshold.
Choose passage boundaries that give a reviewer enough evidence
One sentence can be an excellent reference when its subject is explicit. An isolated pronoun can be useless. For example, the sentence “It is available at the front desk” is a weak separate result without the preceding line naming the adapter. Store both sentences in that passage or add a concise source-subject label as part of the text when that fits your retrieval design. Give the reviewer a path to the original location so they can see which words are yours.
For a packet with distinct sections, use source IDs that reflect the document and a location inside it, such as DESK-GUIDE-04. Keep the displayed paragraph short enough to read. When an item contains a table and the retrieval route uses text, check that rows and headings were kept together during extraction. A matched phrase from the wrong column supplies a familiar term without the needed facts. Keep a small sample with a similar heading and a different rule to test how useful the retrieved passages are.
Try two more queries with values that can collide. One asks where to borrow a display adapter. The other asks where a spare projector bulb is stored. Each should lead to a different practice passage. Check both snippets even if the score order appears reasonable. If changing one word repeatedly retrieves the same item, look at the exact document phrasing and the model’s expected input conventions. It may need a documented query instruction or a different model chosen for your collection.
Verify a rebuild against the same source IDs
Add a new passage PINE-04 about borrowing a tool from a service desk. Rerun the ranking and see whether the connector query still brings a useful candidate to the top. Write down what changed. If your interface presents three results instead of one, check how many useful choices show up without overwhelming a reader. The exact numeric order depends on the local model, and the output is useful only if a person can inspect the relevant text.
When the collection changes, update its source files first and rebuild the complete small matrix. If a source was removed, check both the current file list and the ranking output. A cached vector from a removed source must not still point to an old document the user can no longer open. For a positive control, retain one unchanged reference and confirm that it still appears for its exact query. This is particularly useful when a list of sources was sorted between loading and display.
For an embedding model that has an explicit query encoding route, follow its documentation and keep the distinction in your run notes. Test that reruns use the same two encoders rather than one generic path. A mismatch can produce vectors with valid-looking shapes and an unhelpful ranking. Configuring the two sides from the model’s supported procedure gives you another concrete thing to inspect when a familiar source moves down the list.
Keep a source mapping as the collection changes
A larger library can store vectors separately so you do less work at query time. Keep the embedding model identifier, configuration and exact source ID order with the stored vectors. When a paragraph changes, replace its vector and preserve the source relationship. If you switch models, rebuild the collection with the new model and avoid mixing vectors from different spaces. Check one known result after any rebuild.
Give a second reader only the returned ID and passage. Ask them to locate the corresponding original text and decide whether it supports the query. If they cannot find it, strengthen your source metadata before adding more documents. The search is ready to expand when clear cases retrieve reviewable sources, misleading near matches are documented, and unrelated queries have a safe presentation.
For a collection used by two teams, include one query that could have two useful results. A question such as What is available at the front desk? might reasonably show both adapters and borrowing procedures. Check whether the first results offer different relevant options or duplicate nearly identical text from successive revisions. When several rows are equivalent, merge them at display time only after preserving the underlying source IDs. If they correspond to different locations or rules, let the reader see the distinction.
When a reader clicks a result, display a quiet human-readable source title and a page or section if you can. For an excerpt that spans pages, include both positions. Confirm a click still opens the correct source after rebuilding the collection. Mistakes can happen in a separate display layer even when the vector ranking is mathematically correct. A useful source-check exercise tests the path from input query through the visible result and back to the passage in its own document.
Before changing the model, keep one small query group that represents the main way people will search. Ask a reader to write the question in their own words. Review the relevant sources manually. Then compare how each result helps them find evidence. An exact phrase match should not be the only success case. The advantage of this route is that a query and passage can use different words while still leading to the same underlying subject. Keep one result with a legitimate alternative to test how your layout handles uncertainty.