掌握 LangGraph Store 基础 API 中 put()(写入)和 get()(读取)方法的使用,分别在 InMemoryStore 和 PostgresStore 两种环境下进行实战演示,理解数据的写入、覆盖与更新机制。
| 参数 | 类型 | 说明 |
|---|
namespace | tuple[str, ...] | 命名空间(字符串元组) |
key | str | namespace 下的唯一标识 |
value | dict[str, Any] | 存储的字典数据 |
index | Literal[False] | list[str] | None | 语义检索索引配置(False=禁用,None=使用默认) |
ttl | float | None | Time To Live,数据存活时间(秒) |
- 覆盖行为:当
namespace + key 相同时,后续 put() 会覆盖之前的数据。
- 功能:基于
namespace + key 进行精确查询。 - 关键参数:
| 参数 | 类型 | 说明 |
|---|
namespace | tuple[str, ...] | 命名空间 |
key | str | 查找的键 |
refresh_ttl | bool | 是否刷新存活时间(默认 False) |
- 返回值:完整的
Item 对象,包含 namespace、key、value、created_at、updated_at 等字段 — 而非仅返回 value。
Item(
namespace=("users",),
key="user-1",
value={"username": "小明"},
created_at="2025-xx-xx ...",
updated_at="2025-xx-xx ..."
)
| 行为 | InMemoryStore | PostgresStore |
|---|
| 首次 put | created_at == updated_at | created_at == updated_at |
| 覆盖 put(同 namespace+key) | 视为全新写入,created_at 和 updated_at 均更新为当前时间,两者一致 | 视为数据库行更新,created_at 保持不变,仅 updated_at 更新 |
核心原因:InMemoryStore 每次 put() 都创建新的 Item 对象;PostgresStore 则是数据库层面的 UPDATE 操作,保留了原始创建时间。
put(namespace, key, value) ──▶ Store ──▶ get(namespace, key) ──▶ Item
│
同 namespace+key 再次 put
│
┌───────────┴───────────┐
▼ ▼
InMemoryStore PostgresStore
(全新 Item 对象) (UPDATE 数据库行)
created_at 更新 created_at 不变
updated_at 更新 updated_at 更新
from langgraph.store.memory import InMemoryStore
store = InMemoryStore()
namespace = ("users",)
user_id = "user-1"
user_name = {"username": "小明"}
store.put(namespace=namespace, key=user_id, value=user_name)
item = store.get(namespace=namespace, key=user_id)
print(item)
store.put(namespace=namespace, key=user_id, value={"username": "小红"})
item = store.get(namespace=namespace, key=user_id)
print(item.value)
from langgraph.store.postgres import PostgresStore
DB_URL = "postgresql://user:password@localhost:5432/langchadb"
with PostgresStore.from_conn_string(DB_URL) as store:
store.setup()
store.put(
namespace=("users",),
key="user-1",
value={"username": "小明"}
)
item = store.get(namespace=("users",), key="user-1")
print(item)
store.put(
namespace=("users",),
key="user-1",
value={"username": "小红"}
)
item = store.get(namespace=("users",), key="user-1")
print(item.value)
- get() 返回的是 Item 对象不是字典:取值需通过
item.value 而非直接使用 item["value"]。 - PostgresStore 需要先 setup():首次使用必须调用
store.setup() 创建数据库表,否则写入会报错。 - Postgres 服务必须开启:使用 PostgresStore 前确保 PostgreSQL 服务正常运行。
- namespace 元组末尾逗号:
("users",) 表示单元素元组,不能写成 ("users")(那会被当作字符串)。 - value 必须是 dict 类型:不能直接传字符串,必须用
{"key": "val"} 结构。
put() 和 get() 构成 Store 最基础的读写操作,是后续 search() 和 Agent 集成的前提。- 理解 InMemoryStore 和 PostgresStore 在覆盖行为上的差异很重要:前者每次 put 都相当于删除重建,后者是真正的数据库 UPDATE。
ttl 参数可用于实现自动过期的"会话级"长期记忆,结合 refresh_ttl 可实现"访问即续期"模式。- 下一节将介绍
search() 方法,支持基于 namespace 前缀、filter 过滤和语义搜索的灵活检索。