Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Langchain ai Langgraph SqliteStore

From Leeroopedia
Knowledge Sources
Domains Store, SQLite
Last Updated 2026-02-11 16:00 GMT

Overview

`SqliteStore` is a synchronous SQLite-backed key-value store with optional vector search via `sqlite-vec`, full-text search, TTL-based item expiration, and filter support.

Description

`SqliteStore` extends both `BaseSqliteStore` and `BaseStore` to provide a synchronous interface for storing, retrieving, and searching key-value data in SQLite. Items are organized by namespace tuples (stored as dot-separated text prefixes) and identified by string keys. Values are serialized as JSON using `orjson` for high-performance encoding and decoding. The store supports transactional operations through its cursor management with explicit `BEGIN`/`COMMIT` boundaries.

The store provides a comprehensive filtering system that supports comparison operators (`$eq`, `$gt`, `$gte`, `$lt`, `$lte`, `$ne`) applied to JSON-extracted fields within stored values. Filters are validated against a safe character pattern to prevent SQL injection. Optional vector search is available through the `sqlite-vec` extension, enabling semantic similarity search with configurable distance metrics (cosine, L2, inner product). When configured, the store maintains a `store_vectors` table with embeddings linked to store items via foreign keys with cascade deletes.

`SqliteStore` also supports TTL (time-to-live) for automatic item expiration. Items can be assigned `expires_at` timestamps and `ttl_minutes` values. A background sweeper thread, started via `start_ttl_sweeper()`, periodically removes expired items. The TTL feature supports refresh-on-read behavior, extending an item's expiration each time it is accessed. Thread safety is ensured through a `threading.Lock`, and the class uses autocommit mode (`isolation_level=None`) for explicit transaction control.

Usage

Use `SqliteStore` when you need a synchronous, lightweight key-value store for LangGraph applications. It is ideal for development, testing, CLI tools, and single-threaded deployments where async is not required. For async applications, use `AsyncSqliteStore` instead. For production workloads with high concurrency, consider `PostgresStore`.

Code Reference

Source Location

Signature

class SqliteStore(BaseSqliteStore, BaseStore):
    def __init__(
        self,
        conn: sqlite3.Connection,
        *,
        deserializer: Callable[[bytes | str | orjson.Fragment], dict[str, Any]] | None = None,
        index: SqliteIndexConfig | None = None,
        ttl: TTLConfig | None = None,
    ):

Import

from langgraph.store.sqlite import SqliteStore

I/O Contract

Inputs

Name Type Required Description
conn sqlite3.Connection Yes A standard library sqlite3 database connection.
deserializer None No Optional custom deserializer for stored values. Defaults to `orjson.loads`.
index None No Optional vector search configuration with dims, embed model, and fields.
ttl None No Optional time-to-live configuration for automatic item expiration.

Outputs

Name Type Description
SqliteStore SqliteStore An instance of the synchronous SQLite store, ready for use after calling `setup()`.

Key Methods

Method Description
setup() Creates store tables, applies migrations, loads sqlite-vec extension, and sets up vector tables if configured.
batch(ops) Executes a batch of store operations (Get, Put, Search, ListNamespaces) synchronously within a transaction.
from_conn_string(conn_string, ...) Classmethod context manager that creates an instance from a SQLite file path or `":memory:"`.
sweep_ttl() Deletes expired store items based on TTL. Returns the number of deleted items.
start_ttl_sweeper() Starts a background daemon thread that periodically removes expired items. Returns a `Future`.
stop_ttl_sweeper(timeout) Gracefully stops the TTL sweeper thread.

Database Schema

The store manages the following tables:

Table Description
store Main key-value table with prefix (namespace), key, JSON value, timestamps, expires_at, and ttl_minutes columns.
store_migrations Tracks applied migration versions.
store_vectors Stores vector embeddings linked to store items (created only when index config is provided).
vector_migrations Tracks applied vector migration versions (created only when index config is provided).

Usage Examples

from langgraph.store.sqlite import SqliteStore

# Basic key-value storage using context manager
with SqliteStore.from_conn_string(":memory:") as store:
    store.setup()

    store.put(("users", "123"), "prefs", {"theme": "dark"})
    item = store.get(("users", "123"), "prefs")

# With vector search
from langchain.embeddings import OpenAIEmbeddings

with SqliteStore.from_conn_string(
    ":memory:",
    index={
        "dims": 1536,
        "embed": OpenAIEmbeddings(),
        "fields": ["text"],
    },
) as store:
    store.setup()

    store.put(("docs",), "doc1", {"text": "Python tutorial"})
    store.put(("docs",), "doc2", {"text": "TypeScript guide"})
    store.put(("docs",), "doc3", {"text": "Other guide"}, index=False)

    results = store.search(("docs",), query="programming guides", limit=2)

# Direct connection usage
import sqlite3

conn = sqlite3.connect(":memory:")
store = SqliteStore(conn)
store.setup()

store.put(("users", "123"), "prefs", {"theme": "dark"})
item = store.get(("users", "123"), "prefs")

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment