Skip to content

constants

rel.constants(status: "active")
rel.constants(version: 1, source: "api")

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.

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.

No special requirements. Works on any relation.

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}]
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"}]
OperatorUse caseValues
constantsAdd fixed metadataSame value for all tuples
extendCompute new attributesDifferent value per tuple
# constants: same value everywhere
rel.constants(version: 1)
# extend: computed per tuple
rel.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.