Portable Data Store for efficient storage and retrieval of JSON-serializable objects with Zstandard compression.
Project description
PDS - Portable Data Store
PDS (Portable Data Store) is a Python class for efficiently storing and retrieving large amounts of key-value data, where keys are hierarchical strings and values are arbitrary JSON-serializable Python objects. It leverages Zstandard (zstd) compression, including optional dictionary-based compression, to minimize storage space, particularly for datasets with repetitive structures or content (like collections of JSON objects, log entries, etc.).
It's designed for scenarios where you need to store structured data persistently in a single object but want faster random access and potentially better compression than simply storing individual JSON files or using less specialized formats.
Table of Contents
- Features
- Installation
- Basic Usage
- Compression Options
- API Reference
- File Format (
.pds) - Considerations and Limitations
- Contributing
- License
Features
- Hierarchical Keys: Use lists of strings (e.g.,
["logs", "2025-05-02", "errors"]) to organize data. - JSON-Serializable Values: Store any Python object that can be serialized to JSON (dictionaries, lists, strings, numbers, booleans, etc.).
- Metadata Storage: Attach a JSON-serializable dictionary as metadata to the entire store.
- Efficient Compression: Utilizes Zstandard (zstd) for fast and effective compression.
- No Compression: Option to store data uncompressed.
- Standard Zstd: Compress values using zstd without a dictionary.
- Dictionary Compression: Automatically train a zstd dictionary based on data samples during
savefor potentially significant size reduction on repetitive datasets.
- Random Access Reads: Retrieve individual values efficiently using their key path via an internal index, without needing to scan the entire file.
- Data Modification: Add, update (by adding with the same key), and remove keys. Changes are initially stored in temp files and consolidated during
save. - Context Manager Support: Use
with PDS(...) as store:for automatic resource cleanup (dispose). - Temporary File Management: Handles temporary storage for added/modified data transparently before saving.
Installation
You can install python-pds directly from PyPI using pip:
pip install python-pds
This will automatically install the required zstandard dependency as well.
Note: The package is installed as python-pds, but you import it in your Python code as pds:
from pds import PDS
# Now you can use the PDS class
store = PDS()
Basic Usage
Creating and Saving
# Make sure to install first: pip install python-pds
from pds import PDS # Import the class from the 'pds' package
import os
filename = "my_data_store.pds"
# Remove old file if it exists
if os.path.exists(filename):
os.remove(filename)
# Use zstd_dict mode (will train a dictionary on save if data warrants it)
# Use context manager for automatic cleanup
try:
with PDS(compression_mode='zstd_dict') as pds:
# Set some metadata
pds.set_meta_data({
"project": "Web Scraper",
"version": "1.0",
"timestamp": "2025-05-02T11:00:00Z"
})
# Add data using hierarchical keys
pds.add_key(
["articles", "example.com", "article1"],
{"title": "Example Article", "content": "Lots of text...", "tags": ["news", "example"]}
)
pds.add_key(
["articles", "example.com", "article2"],
{"title": "Another Example", "content": "More text data...", "tags": ["tech"]}
)
pds.add_key(
["logs", "scraper1", "errors"],
[{"error": "Timeout", "url": "..."}, {"error": "404", "url": "..."}]
)
pds.add_key(
["config", "settings"],
{"retry_count": 3, "timeout": 30}
)
# Data is held in temp files until save
print(f"Saving data to {filename}...")
pds.save(filename)
print("Save complete.")
except Exception as e:
print(f"An error occurred: {e}")
Opening and Reading
from pds import PDS
import json
filename = "my_data_store.pds"
try:
# Open an existing PDS file (no mode needed for opening)
with PDS() as pds:
print(f"Opening {filename}...")
pds.open(filename)
print("File opened.")
# Read metadata
print("\nMetadata:")
print(json.dumps(pds.meta_data, indent=2))
# Get the structure of keys
print("\nKey Structure:")
print(json.dumps(pds.get_keys(), indent=2))
# Note: The actual values in the key structure are internal value IDs,
# not the data itself. This just shows the hierarchy.
# Read specific values
print("\nReading specific keys:")
article1_data = pds.read_key(["articles", "example.com", "article1"])
print(f"Article 1 Title: {article1_data.get('title')}")
error_logs = pds.read_key(["logs", "scraper1", "errors"])
print(f"Number of errors logged: {len(error_logs)}")
# Attempt to read a non-existent key
try:
non_existent = pds.read_key(["non", "existent", "key"])
except KeyError as ke:
print(f"\nCorrectly caught error for non-existent key: {ke}")
except FileNotFoundError:
print(f"Error: File not found - {filename}")
except Exception as e:
print(f"An error occurred: {e}")
Modifying Data
You can open an existing store, add/remove keys, and then save (usually to a new file, but you can also overwrite the existing one).
from pds import PDS
import os
filename_v1 = "my_data_store.pds"
filename_v2 = "my_data_store_v2.pds"
# Ensure v1 exists from previous example
if not os.path.exists(filename_v1):
print(f"Error: {filename_v1} not found. Run the creation example first.")
else:
try:
# Open the existing store
with PDS() as pds:
pds.open(filename_v1)
print(f"Opened {filename_v1} for modification.")
# Add a new key
pds.add_key(["status", "progress"], {"completed": 0.75, "state": "running"})
print("Added new key ['status', 'progress']")
# Remove an existing key
try:
pds.remove_key(["logs", "scraper1", "errors"])
print("Removed key ['logs', 'scraper1', 'errors']")
except KeyError:
print("Key ['logs', 'scraper1', 'errors'] not found for removal.")
# Update an existing key by adding it again
pds.add_key(
["config", "settings"],
{"retry_count": 5, "timeout": 60, "user_agent": "PDS Bot"} # Overwrites previous value
)
print("Updated key ['config', 'settings']")
# Save changes to a new file
print(f"\nSaving modified data to {filename_v2}...")
pds.save(filename_v2)
print("Save complete.")
# You can now read from filename_v2
except Exception as e:
print(f"An error occurred during modification: {e}")
Compression Options
The compression_mode parameter in the PDS() constructor determines the intended compression strategy used when save() is called next.
none
- Description: No compression is applied to the values.
- Pros: Fastest save/load times if disk I/O is not the bottleneck. Simple.
- Cons: Results in the largest file sizes.
- Use When: File size is not a concern, absolute maximum speed is needed, and data does not compress well anyway.
zstd_no_dict
- Description: Compresses values using standard Zstandard (level 5) without a dictionary.
- Pros: Good balance of compression speed and ratio. Generally fast. Good default choice.
- Cons: May not achieve optimal compression for datasets with high repetition across many small records.
- Use When: You need good compression without the overhead of dictionary training, or when your data consists of larger chunks with good internal repetition.
zstd_dict
- Description: Compresses values using Zstandard (level 5) with a dictionary automatically trained on a sample of the data during the
save()operation. - Pros: Can achieve significantly better compression ratios than
zstd_no_dictfor datasets containing many small records with shared patterns (e.g., JSON keys, log formats, common strings). - Cons:
save()operation incurs overhead for sampling data and training the dictionary, making it slower than other modes, sometimes significantly so for very large datasets. Dictionary training requires memory to hold samples (configurable viadict_sample_size, default 2GB). - Use When: Minimizing file size is crucial, and the dataset contains significant repetitive elements across different keys/values. Suitable for collections of structured records like logs, JSON objects, configuration snippets, etc.
- Configuration:
dict_sample_size: Max bytes of (decompressed) value data to sample for training (default: 2GB).dict_target_size: Target size for the trained dictionary (default: ~110KB).
Choosing a Mode
- Start with
zstd_no_dictfor a good general baseline. - If your data consists of many small items with clear repetition (lots of similar JSON keys, repeated text snippets), try
zstd_dictand compare the file size and save time. - Use
noneonly if compression provides negligible benefit or speed is paramount above all else.
API Reference
PDS(compression_mode: str = "zstd_dict", dict_sample_size: int = ..., dict_target_size: int = ...):- Constructor. Sets the intended compression mode for the next
save(). Does not affectopen().
- Constructor. Sets the intended compression mode for the next
add_key(keys_list: List[str], value: Any):- Adds or updates a value at the specified hierarchical key path.
valuemust be JSON-serializable.
- Adds or updates a value at the specified hierarchical key path.
read_key(keys_list: List[str]) -> Any:- Retrieves the value associated with the key path. Raises
KeyErrorif not found.
- Retrieves the value associated with the key path. Raises
remove_key(keys_list: List[str]):- Removes the key and its associated value reference. Raises
KeyErrorif not found.
- Removes the key and its associated value reference. Raises
save(filename: str):- Writes the entire data store (metadata, values, index) to the specified file using the intended compression mode set during
__init__. Consolidates temporary changes. Trains dictionary if mode iszstd_dict.
- Writes the entire data store (metadata, values, index) to the specified file using the intended compression mode set during
open(filename: str):- Loads an existing PDS file into memory (metadata and index). Values are read on demand via
read_key. Detects the compression mode used when the file was saved.
- Loads an existing PDS file into memory (metadata and index). Values are read on demand via
set_meta_data(meta_data: Dict[str, Any]):- Sets the metadata for the store. Must be a JSON-serializable dictionary.
get_keys() -> Union[List, Dict]:- Returns a deep copy of the keys index structure (containing internal value IDs, not the actual data). Useful for exploring the hierarchy.
dispose():- Closes the file handle (if open) and cleans up temporary directories. Automatically called when exiting a
PDScontext (withstatement).
- Closes the file handle (if open) and cleans up temporary directories. Automatically called when exiting a
File Format (.pds)
The PDS file format is structured sequentially as follows:
-
Metadata Block:
[UINT4: Length M]- 4 bytes, unsigned integer, little-endian: Length of the metadata JSON bytes.[Bytes: Metadata]- M bytes: UTF-8 encoded JSON string containing the store's metadata.
-
Dictionary Information Block:
[INT4: Dictionary Length D]- 4 bytes, signed integer, little-endian:D > 0: Length of the Zstandard dictionary data that follows. Compression mode waszstd_dict.D == -1(_ZSTD_NO_DICT): No dictionary data follows. Compression mode waszstd_no_dict.D == -2(_NO_COMPRESSION): No dictionary data follows. Compression mode wasnone.
[Bytes: Zstd Dictionary]- D bytes: The Zstandard dictionary data. Only present if D > 0.
-
Value Blocks: (Variable number of blocks, stored sequentially)
- Repeated for each value stored:
[UINT8: Value Length V]- 8 bytes, unsigned integer, little-endian: Length of the value data that follows.[Bytes: Value Data]- V bytes: The actual value data. This data is compressed according to the mode indicated by the Dictionary Information Block (none,zstd_no_dict, orzstd_dictusing the stored dictionary).
- Repeated for each value stored:
-
Keys Index Block: (Stored at the end)
[Bytes: Compressed Index Data K]- K bytes: The Zstandard compressed (level 5) representation of the keys index. The index is a JSON structure mirroring the key hierarchy, but leaf nodes contain strings"|offset:length"pointing to the start (offset) and size (length) of the corresponding Value Data block within the file. Theoffsetpoints after the[UINT8: Value Length V]prefix for that value.[UINT4: Index Length K]- 4 bytes, unsigned integer, little-endian: Length of the compressed index data (K bytes) that immediately precedes it.
Note: The Keys Index itself is always compressed using zstd (level 5) during save, regardless of the compression_mode chosen for the main values.
Considerations and Limitations
- Memory Usage:
- Opening a file loads the metadata and the (decompressed) keys index into memory. Index size depends on the number of keys and the depth of the hierarchy.
read_keyloads the entire requested (decompressed) value into memory.savewithzstd_dictrequires memory to hold data samples (up todict_sample_size) during dictionary training.- Saving large datasets involves reading temporary files or existing value blocks, potentially leading to high memory usage if many large values are processed simultaneously.
- Performance:
add_keyperforms a simple zstd compression and writes to a temporary file - relatively fast but involves I/O.read_keyperforms a file seek, read, potentially zstd decompression, and JSON parsing. Generally fast for random access.saveis the most intensive operation. It reads all data (from temp files or the original file), potentially decompresses, re-compresses according to the target mode (including dictionary training if applicable), and writes everything sequentially. Can be slow for large datasets.
- Concurrency: The
PDSclass is not thread-safe for concurrent write operations (add_key,remove_key,saveon the same instance). Reading from the same instance in multiple threads might work depending on the underlying file handle's behavior but is not explicitly designed or tested for. Use separatePDSinstances (potentially opening the same file read-only) for concurrent reads. - Atomicity: The
saveoperation is not atomic. If the process is interrupted duringsave, the output file may be incomplete or corrupted. For critical applications, consider saving to a temporary file and then atomically renaming it upon successful completion (this logic is not currently implemented within thePDSclass). - Error Handling: Uses standard Python exceptions. File corruption, resource exhaustion (memory/disk), or invalid data can lead to errors (
IOError,MemoryError,zstd.ZstdError,json.JSONDecodeError,ValueError, etc.). - Large Individual Values: While the format supports large values (
UINT8for length), extremely large individual values (approaching or exceeding available RAM) could causeMemoryErrorduring reading, saving, or dictionary sampling.
Contributing
Contributions are welcome! Please see the Contributing Guidelines for details on how to set up your development environment, report bugs, suggest features, and submit pull requests.
License
This project is licensed under the MIT License - see the LICENSE file for details
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file python_pds-0.1.1.tar.gz.
File metadata
- Download URL: python_pds-0.1.1.tar.gz
- Upload date:
- Size: 25.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3fb95c5389bbc22ffacfa261eb25b9122a48ab574f6a5670845731b5feaf31a1
|
|
| MD5 |
9b22e4710b55b47e5a0320b968e6b1ad
|
|
| BLAKE2b-256 |
5313c8a931308ea9e2d3e1156b378440077030f6a5dbc0a61ce3c9f9e3ca68f2
|
Provenance
The following attestation bundles were made for python_pds-0.1.1.tar.gz:
Publisher:
publish.yml on kiss-oliver/PDS
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
python_pds-0.1.1.tar.gz -
Subject digest:
3fb95c5389bbc22ffacfa261eb25b9122a48ab574f6a5670845731b5feaf31a1 - Sigstore transparency entry: 206489820
- Sigstore integration time:
-
Permalink:
kiss-oliver/PDS@0f7a909fd7f948432232afb1666f118ef48e2e31 -
Branch / Tag:
refs/tags/v0.1.1 - Owner: https://github.com/kiss-oliver
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@0f7a909fd7f948432232afb1666f118ef48e2e31 -
Trigger Event:
push
-
Statement type:
File details
Details for the file python_pds-0.1.1-py3-none-any.whl.
File metadata
- Download URL: python_pds-0.1.1-py3-none-any.whl
- Upload date:
- Size: 19.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
20ec58cdecf91e1ef9f39c79c1950fd3a84c7e8ff8ad1d62ae75ff6e71035920
|
|
| MD5 |
eb3500d6aeb49120528e85d393dbb1e0
|
|
| BLAKE2b-256 |
8b32a3406c3e54f0578361d089bb97e484d9c5c8fdf22939223f2831f0885647
|
Provenance
The following attestation bundles were made for python_pds-0.1.1-py3-none-any.whl:
Publisher:
publish.yml on kiss-oliver/PDS
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
python_pds-0.1.1-py3-none-any.whl -
Subject digest:
20ec58cdecf91e1ef9f39c79c1950fd3a84c7e8ff8ad1d62ae75ff6e71035920 - Sigstore transparency entry: 206489821
- Sigstore integration time:
-
Permalink:
kiss-oliver/PDS@0f7a909fd7f948432232afb1666f118ef48e2e31 -
Branch / Tag:
refs/tags/v0.1.1 - Owner: https://github.com/kiss-oliver
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@0f7a909fd7f948432232afb1666f118ef48e2e31 -
Trigger Event:
push
-
Statement type: