pcx_content_type | title | sidebar | ||
---|---|---|---|---|
concept |
Read key-value pairs |
|
To get the value for a given key, call the get()
method of the KV binding on any KV namespace you have bound to your Worker code:
env.NAMESPACE.get(key);
The get()
method returns a promise you can await
on to get the value.
If you request a single key as a string, you will get a single response in the promise. If the key is not found, the promise will resolve with the literal value null
.
Instead of a single key, you can also request an array of keys. In this case, the response is a map with the key-value pairs.
An example of reading a key from within a Worker:
export default {
async fetch(request, env, ctx) {
try {
const value = await env.NAMESPACE.get("first-key");
if (value === null) {
return new Response("Value not found", { status: 404 });
}
return new Response(value);
} catch (e) {
return new Response(e.message, { status: 500 });
}
},
};
Or if you request multiple keys:
export default {
async fetch(request, env, ctx) {
try {
const value = await env.NAMESPACE.get(["first-key", "second-key"]);
return new Response("values: " + value.get("second-key") + " " + value.get("second-key"));
} catch (e) {
return new Response(e.message, { status: 500 });
}
},
};
The following methods are provided to read from KV:
Use the get()
method to get a single value, or multiple values if given multiple keys.
To get the value for a single key, call the get()
method on any KV namespace you have bound to your Worker code with:
env.NAMESPACE.get(key, type?);
// OR
env.NAMESPACE.get(key, options?);
key
:string
- The key of the KV pair.
type
:"text" | "json" | "arrayBuffer" | "stream"
- Optional. The type of the value to be returned.
text
is the default.
- Optional. The type of the value to be returned.
options
:{ cacheTtl?: number, type?: "text" | "json" | "arrayBuffer" | "stream" }
- Optional. Object containing the optional
cacheTtl
andtype
properties. ThecacheTtl
property defines the length of time in seconds that a KV result is cached in the global network location it is accessed from (minimum: 60). Thetype
property defines the type of the value to be returned.
- Optional. Object containing the optional
response
:Promise<string | Object | ArrayBuffer | ReadableStream | null>
- The value for the requested KV pair. The response type will depend on the
type
parameter provided for theget()
command as follows:text
: Astring
(default).json
: An object decoded from a JSON string.arrayBuffer
: AnArrayBuffer
instance.stream
: AReadableStream
.
- The value for the requested KV pair. The response type will depend on the
The get()
method may return stale values. If a given key has recently been read in a given location, writes or updates to the key made in other locations may take up to 60 seconds (or the duration of the cacheTtl
) to display.
To get the values for multiple keys, call the get()
method on any KV namespace you have bound to your Worker code with:
env.NAMESPACE.get(keys, type?);
// OR
env.NAMESPACE.get(keys, options?);
keys
:string[]
- The keys of the KV pairs. Max: 100 keys
type
:"text" | "json"
- Optional. The type of the value to be returned.
text
is the default.
- Optional. The type of the value to be returned.
options
:{ cacheTtl?: number, type?: "text" | "json" }
- Optional. Object containing the optional
cacheTtl
andtype
properties. ThecacheTtl
property defines the length of time in seconds that a KV result is cached in the global network location it is accessed from (minimum: 60). Thetype
property defines the type of the value to be returned.
- Optional. Object containing the optional
:::note
The .get()
function to read multiple keys does not support arrayBuffer
or stream
return types. If you need to read multiple keys of arrayBuffer
or stream
types, consider using the .get()
function to read individual keys in parallel.
:::
response
:Promise<Map<string, string | Object | null>
- The value for the requested KV pair. The response type will depend on the
type
parameter provided for theget()
command as follows:text
: Astring
(default).json
: An object decoded from a JSON string.
- The value for the requested KV pair. The response type will depend on the
When requesting multiple keys, the promise will never resolve to a null value. It may, however, resolve to a map that contains a key that corresponds to a null value, similar to what happens for a single get.
You cannot request over 25 MB of data. If you do, the request will fail with a 413
Error.
The get()
method may return stale values. If a given key has recently been read in a given location, writes or updates to the key made in other locations may take up to 60 seconds (or the duration of the cacheTtl
) to display.
Use the getWithMetadata()
method to get a single value, or multiple values if given multiple keys.
To get the value for a given key along with its metadata, call the getWithMetadata()
method on any KV namespace you have bound to your Worker code:
env.NAMESPACE.getWithMetadata(key, type?);
// OR
env.NAMESPACE.getWithMetadata(key, options?);
Metadata is a serializable value you append to each KV entry.
key
:string
- The key of the KV pair.
type
:"text" | "json" | "arrayBuffer" | "stream"
- Optional. The type of the value to be returned.
text
is the default.
- Optional. The type of the value to be returned.
options
:{ cacheTtl?: number, type?: "text" | "json" | "arrayBuffer" | "stream" }
- Optional. Object containing the optional
cacheTtl
andtype
properties. ThecacheTtl
property defines the length of time in seconds that a KV result is cached in the global network location it is accessed from (minimum: 60). Thetype
property defines the type of the value to be returned.
- Optional. Object containing the optional
-
response
:Promise<{ value: string | Object | ArrayBuffer | ReadableStream | null, metadata: string | null }>
- An object containing the value and the metadata for the requested KV pair. The type of the value attribute will depend on the
type
parameter provided for thegetWithMetadata()
command as follows:text
: Astring
(default).json
: An object decoded from a JSON string.arrayBuffer
: AnArrayBuffer
instance.stream
: AReadableStream
.
- An object containing the value and the metadata for the requested KV pair. The type of the value attribute will depend on the
If there is no metadata associated with the requested key-value pair, null
will be returned for metadata.
The getWithMetadata()
method may return stale values. If a given key has recently been read in a given location, writes or updates to the key made in other locations may take up to 60 seconds (or the duration of the cacheTtl
) to display.
An example of reading a key with metadata from within a Worker:
export default {
async fetch(request, env, ctx) {
try {
const { value, metadata } =
await env.NAMESPACE.getWithMetadata("first-key");
if (value === null) {
return new Response("Value not found", { status: 404 });
}
return new Response(value);
} catch (e) {
return new Response(e.message, { status: 500 });
}
},
};
To get the values for a given set of keys along with their metadata, call the getWithMetadata()
method on any KV namespace you have bound to your Worker code with:
env.NAMESPACE.getWithMetadata(keys, type?);
// OR
env.NAMESPACE.getWithMetadata(keys, options?);
keys
:string[]
- The keys of the KV pairs. Max: 100 keys
type
:"text" | "json"
- Optional. The type of the value to be returned.
text
is the default.
- Optional. The type of the value to be returned.
options
:{ cacheTtl?: number, type?: "text" | "json" }
- Optional. Object containing the optional
cacheTtl
andtype
properties. ThecacheTtl
property defines the length of time in seconds that a KV result is cached in the global network location it is accessed from (minimum: 60). Thetype
property defines the type of the value to be returned.
- Optional. Object containing the optional
:::note
The .get()
function to read multiple keys does not support arrayBuffer
or stream
return types. If you need to read multiple keys of arrayBuffer
or stream
types, consider using the .get()
function to read individual keys in parallel.
:::
-
response
:Promise<Map<string, { value: string | Object | null, metadata: string | Object | null }>
- An object containing the value and the metadata for the requested KV pair. The type of the value attribute will depend on the
type
parameter provided for thegetWithMetadata()
command as follows:text
: Astring
(default).json
: An object decoded from a JSON string.
- The type of the metadata will just depend on what is stored, which can be either a string or an object.
- An object containing the value and the metadata for the requested KV pair. The type of the value attribute will depend on the
If there is no metadata associated with the requested key-value pair, null
will be returned for metadata.
You cannot request over 25MB of data. If you do, the request will fail with a 413
Error .
An example of reading a key with metadata from within a Worker:
export default {
async fetch(request, env, ctx) {
try {
const response = await env.NAMESPACE.getWithMetadata(["first-key"]);
const firstValue = response.get("first-key");
return new Response("value: " + firstValue?.value + " metadata: " + firstValue?.metadata);
} catch (e) {
return new Response(e.message, { status: 500 });
}
},
};
For simple values, use the default text
type which provides you with your value as a string
. For convenience, a json
type is also specified which will convert a JSON value into an object before returning the object to you. For large values, use stream
to request a ReadableStream
. For binary values, use arrayBuffer
to request an ArrayBuffer
.
For large values, the choice of type
can have a noticeable effect on latency and CPU usage. For reference, the type
can be ordered from fastest to slowest as stream
, arrayBuffer
, text
, and json
.
cacheTtl
is a parameter that defines the length of time in seconds that a KV result is cached in the global network location it is accessed from.
Defining the length of time in seconds is useful for reducing cold read latency on keys that are read relatively infrequently. cacheTtl
is useful if your data is write-once or write-rarely.
:::note[Hot and cold read]
A hot read means that the data is cached on Cloudflare's edge network using the CDN, whether it is in a local cache or a regional cache. A cold read means that the data is not cached, so the data must be fetched from the central stores. Both existing key-value pairs and non-existent key-value pairs (also known as negative lookups) are cached at the edge. :::
cacheTtl
is not recommended if your data is updated often and you need to see updates shortly after they are written, because writes that happen from other global network locations will not be visible until the cached value expires.
The cacheTtl
parameter must be an integer greater than or equal to 60
, which is the default.
The effective cacheTtl
of an already cached item can be reduced by getting it again with a lower cacheTtl
. For example, if you did NAMESPACE.get(key, {cacheTtl: 86400})
but later realized that caching for 24 hours was too long, you could NAMESPACE.get(key, {cacheTtl: 300})
or even NAMESPACE.get(key)
and it would check for newer data to respect the provided cacheTtl
, which defaults to 60 seconds.
You can read key-value pairs from the command line with Wrangler and from the REST API.