Bag Tables
Bag tables store multiple values per key, but silently ignore duplicate key-value pairs. Use bags when you need to associate several distinct values with a single key — like tags, categories, or group memberships.
Opening a Bag Table
Section titled “Opening a Bag Table”import shelf/bag
let assert Ok(table) = bag.open(name: "tags", path: "data/tags.dets")For custom configuration, use open_config:
import shelfimport shelf/bag
let config = shelf.config(name: "tags", path: "data/tags.dets") |> shelf.write_mode(shelf.WriteThrough)
let assert Ok(table) = bag.open_config(config)Reading Data
Section titled “Reading Data”// Look up all values for a key (returns a list)let assert Ok(colors) = bag.lookup(from: table, key: "color")// colors: ["red", "blue"]
// Check if a key existslet assert Ok(True) = bag.member(of: table, key: "color")
// Get the total number of objects (not unique keys)let assert Ok(count) = bag.size(of: table)
// Get all entrieslet assert Ok(entries) = bag.to_list(from: table)Folding
Section titled “Folding”let assert Ok(all_values) = bag.fold(over: table, from: [], with: fn(acc, _key, value) { [value, ..acc] })Writing Data
Section titled “Writing Data”// Insert a key-value pairlet assert Ok(Nil) = bag.insert(into: table, key: "color", value: "red")let assert Ok(Nil) = bag.insert(into: table, key: "color", value: "blue")
// Duplicate key-value pairs are silently ignoredlet assert Ok(Nil) = bag.insert(into: table, key: "color", value: "red")// "color" still has ["red", "blue"]
// Insert multiple entries at oncelet assert Ok(Nil) = bag.insert_list(into: table, entries: [ #("shape", "circle"), #("shape", "square"),])Deleting Data
Section titled “Deleting Data”// Delete all values for a keylet assert Ok(Nil) = bag.delete_key(from: table, key: "color")
// Delete a specific key-value pair (other values for the same key are kept)let assert Ok(Nil) = bag.delete_object(from: table, key: "shape", value: "circle")// "shape" still has ["square"]
// Delete all entrieslet assert Ok(Nil) = bag.delete_all(from: table)Bag vs Set
Section titled “Bag vs Set”| Behavior | Set | Bag |
|---|---|---|
| Values per key | One (overwrites) | Many (distinct only) |
lookup returns | Single value | List(v) |
| Duplicate pairs | Overwrites | Silently ignored |
insert_new | ✅ | — |
update_counter | ✅ | — |