constants
rel.constants(status: "active")rel.constants(version: 1, source: "api")rel.constants({ status: "active" })rel.constants({ version: 1, source: "api" })Problem
Section titled “Problem”Add fixed-value attributes to every tuple in a relation.
Example: I want to tag all records from a particular data source with a constant identifier.
Description
Section titled “Description”The constants operator extends each tuple with new attributes that have the same value for every tuple. This is a specialized form of extend optimized for static values rather than computed ones.
Unlike extend, which can compute values from other attributes, constants simply merges the provided values into each tuple. This makes it more efficient when you just need to add fixed metadata or tags.
Requirements
Section titled “Requirements”No special requirements. Works on any relation.
Examples
Section titled “Examples”Adding a single constant
Section titled “Adding a single constant”data = Bmg::Relation.new([ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }])
data.constants(active: true).to_a
=>[{:id=>1, :name=>"Alice", :active=>true}, {:id=>2, :name=>"Bob", :active=>true}]const data = Bmg([ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }])
data.constants({ active: true }).toArray()
// =>// [{ id: 1, name: "Alice", active: true },// { id: 2, name: "Bob", active: true }]Multiple constants
Section titled “Multiple constants”records = Bmg::Relation.new([ { id: 1, value: 100 }, { id: 2, value: 200 }])
records.constants( source: "import", version: 2, processed_at: "2024-01-15").to_a
=>[{:id=>1, :value=>100, :source=>"import", :version=>2, :processed_at=>"2024-01-15"}, {:id=>2, :value=>200, :source=>"import", :version=>2, :processed_at=>"2024-01-15"}]const records = Bmg([ { id: 1, value: 100 }, { id: 2, value: 200 }])
records.constants({ source: "import", version: 2, processed_at: "2024-01-15"}).toArray()
// =>// [{ id: 1, value: 100, source: "import", version: 2, processed_at: "2024-01-15" },// { id: 2, value: 200, source: "import", version: 2, processed_at: "2024-01-15" }]Comparison with extend
Section titled “Comparison with extend”| Operator | Use case | Values |
|---|---|---|
constants | Add fixed metadata | Same value for all tuples |
extend | Compute new attributes | Different value per tuple |
# constants: same value everywhererel.constants(version: 1)
# extend: computed per tuplerel.extend(doubled: ->(t) { t[:value] * 2 })// constants: same value everywhererel.constants({ version: 1 })
// extend: computed per tuplerel.extend({ doubled: t => t.value * 2 })Use constants when adding static values - it’s simpler and may be more efficient than extend with a constant function.