kv
Key-value namespaces.
Declare
local visits = kv "visits"
Top level only. Scoped to the project, so two scripts in one project
declaring kv "visits" share it.
Methods
ns:get("hits") -- value, or nil
ns:set("hits", 41)
ns:set_batch({ hits = 41, banner = { text = "back at 09:00" } })
ns:delete("hits")
ns:list({ limit = 100 }) -- one page, ascending by key
| Method | Returns |
|---|---|
get(key) | the value, or nil |
set(key, value) | nothing; a nil value is a delete |
set_batch(table) | nothing; writes every pair, deletes the nil ones |
delete(...keys) | nothing; several keys go in one call |
list(options?) | one page: { entries, cursor } |
Listing
One page per call, in ascending key order. entries is an array of
{ key, value }; cursor names where the next page starts, and a
page without one is the last. limit defaults to 100; a value outside
1 to 1000 is refused, not clamped. The options are { limit, cursor }.
local cursor
repeat
local page = ns:list({ cursor = cursor })
for _, entry in page.entries do
print(entry.key, entry.value)
end
cursor = page.cursor
until not cursor
A page is a snapshot of a range, not a lock: writes that land between pages appear or not depending on where their keys sort.
Types
kv stores the type you wrote and returns it.
| You write | You get back |
|---|---|
| string | string |
| integer | integer |
| number | number |
| boolean | boolean |
| table | table, through JSON |
Example
local cache = kv "cache"
on "fetch" (function(request)
local hits = (cache:get("hits") or 0) + 1
cache:set("hits", hits)
return { body = tostring(hits) }
end)
Gotchas
- Listing pages by key order; there is no query by value. Anything richer than a key range wants a database.
- Functions and userdata cannot be stored. Tables go through JSON, so what comes back is a copy, not the table you put in.
- A nil value in
setorset_batchis a delete, not a stored nil. - A value has no fixed size limit.
state.storeon an object caps at 64 KB; kv does not. - A namespace name starting with
__is reserved for the platform and refused.
Related
- Where data goes compares kv with databases and objects.
- state.store is the same surface on a durable object's own storage: kv for state one object owns.