Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Create a Personal Knowledge Base That Searches Notes Instantly in Python

Build a lightweight personal knowledge base with JSON storage and instant case-insensitive full-text search across note titles and content.

Easy Python 3.9+ Jun 27, 2026 Files & data 3 views 0 copies

Python code

47 lines
Python 3.9+
import json
import re
import sys

class PersonalKnowledgeBase:
    def __init__(self, file_path="kb_notes.json"):
        self.file_path = file_path
        self.notes = self._load_notes()

    def _load_notes(self):
        try:
            with open(self.file_path, "r") as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return {}

    def _save_notes(self):
        with open(self.file_path, "w") as f:
            json.dump(self.notes, f, indent=2)

    def add_note(self, title, content):
        self.notes[title] = content
        self._save_notes()

    def search(self, query):
        query_lower = query.lower()
        results = {}
        for title, content in self.notes.items():
            if (query_lower in title.lower() or 
                query_lower in content.lower()):
                results[title] = content
        return results

if __name__ == "__main__":
    kb = PersonalKnowledgeBase()
    kb.add_note("Python tips", "Use pathlib for file paths, not os.path.")
    kb.add_note("Flask setup", "Install Flask with pip, define routes.")
    kb.add_note("Git commands", "git commit -m, git push origin main")
    
    query = "git"
    found = kb.search(query)
    if found:
        print(f"Found {len(found)} note(s) for '{query}':")
        for title, content in found.items():
            print(f"  {title}: {content}")
    else:
        print(f"No notes found for '{query}'.")

Output

stdout
Found 1 note(s) for 'git':
  Git commands: git commit -m, git push origin main

How it works

The class uses a JSON file as persistent storage, loading and saving notes with the standard library's json module. The search method performs a case-insensitive substring match on both titles and content by converting the query and note fields to lowercase. The try-except block handles missing or corrupted files on startup, returning an empty dictionary as a fallback. This design keeps dependencies minimal and the knowledge base portable with zero configuration.

Common mistakes

  • Forgetting to call `_save_notes()` after adding a note, so changes are lost on exit.
  • Assuming the JSON file is always present – the fallback handles missing files but not permission errors.
  • Using case-sensitive matching, which misses notes when query casing doesn't match.
  • Overwriting the entire JSON file on every save – fine for small note sizes but not large-scale use.

Variations

  1. Use SQLite via the standard `sqlite3` module for faster queries on large note collections.
  2. Add keyword tagging and a `filter_by_tag` method for categorized search.

Real-world use cases

  • A developer saving daily code snippets with a quick CLI to find them later.
  • A student curating lecture notes that need instant lookup during exam prep.
  • A technical writer maintaining a local glossary of terms and seeing searchable results in a terminal.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.