Use a key-value model to store values and counters
A key-value namespace stores small values by key, and each key can expire. Use one for sessions, feature flags, rate limits and high-traffic counters.
Before you start
- Morphic Pro is required. Without it, Key-value shows as locked under Models.
- You need the WordPress Administrator role to create a namespace.
Create a namespace
- Go to Morphic > Models.
- In the Key-value group, select New namespace.
- In Name, enter a name, for example
Sessions. - Select Create key-value namespace.
Result: Morphic opens the new namespace. Add keys to it from the Key-value page.
Add a key
- Go to the Key-value page.
- Select the namespace in the list.
- Select New key.
- In Key, enter the key.
- In Value (JSON), enter the value as JSON, for example
42,"text"or{"a": 1}. - In Expires after, enter a time such as
30m,2hor7d. Leave it empty to use the namespace default. - Select Save.
Result: the key appears in the table with its Key, Value, Rev and Expires. A key with no expiry shows never.
Store a key over the API
Write a key with PUT to kv/<namespace>/entry. The body holds key, value and ttl. A ttl such as 30m sets the expiry.
curl -u "$USER:$PASS" -X PUT "https://example.com/wp-json/morphic/v1/kv/sessions/entry" -H "Content-Type: application/json" -d '{"key":"user/42","value":{"cart":3},"ttl":"30m"}'
Increment a counter with POST to kv/<namespace>/incr. The body holds key and delta. If you leave out delta, Morphic adds 1.
curl -u "$USER:$PASS" -X POST "https://example.com/wp-json/morphic/v1/kv/views/incr" -H "Content-Type: application/json" -d '{"key":"art/1","delta":1}'
Use counter shards
A counter with shards spreads heavy traffic over several rows. Morphic adds the rows together when it reads the counter.
- On the Key-value page, select Namespace settings.
- In Counter shards, enter a number from 1 to 64.
A sharded namespace accepts only numeric values.