nyx-kv hashes
Hashes store field-value pairs under a single key, perfect for user profiles or structured data. HSET can set multiple fields in one command.
Code
// nyx-kv hashes -- HSET, HGET, HGETALL for structured data
fn resp_cmd(parts: Array) -> String {
var sb: StringBuilder = StringBuilder.new()
sb.append("*")
sb.append(int_to_string(parts.length()))
sb.append("\r\n")
var i: int = 0
while i < parts.length() {
let p: String = parts[i]
sb.append("$")
sb.append(int_to_string(p.length()))
sb.append("\r\n")
sb.append(p)
sb.append("\r\n")
i = i + 1
}
return sb.to_string()
}
fn main() -> int {
let fd: int = tcp_connect("127.0.0.1", 6380)
if fd < 0 {
print("connection failed")
return 1
}
// Store a user profile as a hash
tcp_write(fd, resp_cmd(["HSET", "user:1", "name", "Alice", "age", "30", "city", "Buenos Aires"]))
let hset_reply: String = tcp_read_line(fd)
print("HSET -> " + hset_reply.trim())
// Get a single field
tcp_write(fd, resp_cmd(["HGET", "user:1", "name"]))
let hget_hdr: String = tcp_read_line(fd)
let name: String = tcp_read_line(fd)
print("HGET name -> " + name.trim())
// Check if a field exists
tcp_write(fd, resp_cmd(["HEXISTS", "user:1", "age"]))
let exists: String = tcp_read_line(fd)
print("HEXISTS age -> " + exists.trim())
// Get the number of fields
tcp_write(fd, resp_cmd(["HLEN", "user:1"]))
let hlen: String = tcp_read_line(fd)
print("HLEN -> " + hlen.trim())
tcp_close(fd)
return 0
}
Output
HSET -> :3 HGET name -> Alice HEXISTS age -> :1 HLEN -> :3
Explanation
A hash is a key that maps to an inner Map of field -> string. HSET user:1 name Alice age 30 city "Buenos Aires" writes three fields in a single command — more efficient than three separate SET calls and keeps the profile grouped under one key.
Use hashes when you'd otherwise flatten nested structure into keys like user:1:name, user:1:age. A single hash is easier to delete (DEL user:1 drops everything), easier to enumerate (HGETALL, HKEYS, HVALS), and uses less memory server-side because the top-level key is stored once.
Common patterns: user profiles, feature flags per account, configuration bundles, and shopping carts where each field is a product id and each value is the quantity.