# Agent long-term memory on Upstash Redis Search
## 1. Create the index once
This is a setup script, not request code. Make it idempotent so
re-runs are safe:
from upstash_redis import Redis
redis = Redis.from_env()
redis.search.create_index(
name="memories",
data_type="json",
prefixes="memory:",
exists_ok=True,
schema={
"text": "TEXT",
"userId": "KEYWORD",
"kind": "KEYWORD",
"createdAt": "F64",
},
)
Schema choices: text is full-text searchable, userId and kind are
exact-match keywords for scoping, createdAt is a sortable number
for recency.
## 2. Write facts
On each turn, extract durable facts (preferences, decisions,
events) and store them as JSON under memory:FACTID with the
userId, kind, text, and createdAt fields the schema expects.
## 3. Recall per turn
Query the index scoped to the user, sorted by recency, and feed
the top hits into the prompt alongside the working-memory chat
history. Working memory is the separate TTL-key pattern: one key
per session, one-hour expiry.
## Notes
- Upstash Search indexes JSON, hash, string, and stream keys via
its own SEARCH commands, separate from RediSearch FT commands.
- Keep the index name stable across deploys: the SDK command
references cover typed helpers, but the index itself persists in
the database.
## Verify
Store a test fact, query it back scoped to the right user and
wrong user (wrong user must not see it), and re-run setup to
confirm idempotency.