SQLTrie
SQLTrie is a Python library that implements a SQL-based prefix tree (trie) data structure, drawing inspiration from `pygtrie` and `python-diskcache`. It enables efficient storage and retrieval of key-value pairs where keys are sequences (e.g., strings) and operations like prefix-based lookups are optimized. The current version, 0.11.2, was released in February 2025. Given its 'Development Status :: 1 - Planning', the release cadence is irregular and the API is evolving.
Warnings
- breaking The library is currently in 'Development Status :: 1 - Planning' (Alpha) as per its PyPI classifier. This indicates a highly unstable API that is subject to frequent and significant breaking changes without prior notice. It is not recommended for production environments.
- gotcha Official documentation, particularly for usage examples and API specifics, is minimal. The 'Usage' section in the PyPI description and GitHub README is marked as 'TODO'. Users will likely need to infer functionality from the source code or common patterns of similar trie implementations.
- gotcha As `sqltrie` is backed by SQLite, ensuring data persistence requires proper closing of the trie instance. Failing to do so (e.g., due to unhandled exceptions or abrupt program termination outside of a context manager) may result in data loss or corruption. Always use a context manager (`with Trie(...)`) or explicitly call a `close()` method if available.
Install
-
pip install sqltrie
Imports
- Trie
from sqltrie import Trie
Quickstart
import os
from sqltrie import Trie
db_path = 'my_sqltrie.db'
# Ensure a clean slate for the example
if os.path.exists(db_path):
os.remove(db_path)
# Initialize a SQLTrie instance, typically taking a filename for SQLite storage.
# Using a context manager ensures proper closing and data persistence.
with Trie(filename=db_path) as trie:
trie["apple"] = 100
trie["apricot"] = 200
trie["banana"] = 300
trie["bandana"] = 400
trie["applepie"] = 50
print(f"Value for 'apple': {trie['apple']}")
print(f"'banana' exists: {'banana' in trie}")
print(f"'grape' exists: {'grape' in trie}")
print("\nItems with prefix 'ap':")
for key, value in trie.items(prefix="ap"):
print(f" {key}: {value}")
print("\nAll items:")
for key, value in trie.items():
print(f" {key}: {value}")
# Data is persisted after exiting the 'with' block.
# To verify, load the trie again from the same file.
with Trie(filename=db_path) as loaded_trie:
print(f"\nValue for 'apricot' after reload: {loaded_trie['apricot']}")
print(f"'applepie' exists after reload: {'applepie' in loaded_trie}")
# Clean up the database file
os.remove(db_path)
print(f"\nCleaned up database file '{db_path}'.")