A temporal join adds to each row of a stream the value of a versioned table that was
valid at the time of the row. Use it when a result must stay correct if a value changes later,
for example the currency rate at the time of an order.
An event-time temporal join needs the following:
A watermark on the time column of the stream.
A versioned table with a primary key and a watermark. A changelog source, such as an
upsert-kafka table, provides this.
The FOR SYSTEM_TIME AS OF clause with the time column of the
stream.
In the Streaming SQL Console, click Projects in the left
navigation pane, and click the name of your project.
The project opens, with the Explorer panel on the left.
To open the Streaming SQL Console, see Accessing Cloudera SQL Stream Builder.
In the Explorer, open the menu of Jobs,
and click New Job.
The Create New Job window opens.
Enter a Job Name, or click Generate Job
Name.
Click Create.
The job opens in a new tab, with an empty SQL editor.
Enter the following statements in the SQL editor:
CREATE TABLE orders (
order_id STRING,
price DECIMAL(10, 2),
currency STRING,
order_time TIMESTAMP(3),
WATERMARK FOR order_time AS order_time - INTERVAL '5' SECOND
) WITH (
'connector' = 'kafka',
'properties.bootstrap.servers' = '<broker>:9093',
'topic' = 'orders',
'scan.startup.mode' = 'earliest-offset',
'format' = 'json'
);
CREATE TABLE currency_rates (
currency STRING,
conversion_rate DECIMAL(10, 4),
update_time TIMESTAMP(3),
WATERMARK FOR update_time AS update_time,
PRIMARY KEY (currency) NOT ENFORCED
) WITH (
'connector' = 'upsert-kafka',
'properties.bootstrap.servers' = '<broker>:9093',
'topic' = 'currency_rates',
'key.format' = 'json',
'value.format' = 'json'
);
CREATE TABLE converted_orders (
order_id STRING,
converted_price DECIMAL(20, 4),
order_time TIMESTAMP(3)
) WITH (
'connector' = 'blackhole'
);
INSERT INTO converted_orders
SELECT o.order_id, o.price * r.conversion_rate, o.order_time
FROM orders AS o
LEFT JOIN currency_rates FOR SYSTEM_TIME AS OF o.order_time AS r
ON o.currency = r.currency;
Click the Execute job icon.
The job starts, and its status icon in the Explorer turns
green.
When you have finished, click Stop job.
Each order gets the rate that was valid at its order_time. An order that
arrives before the first rate of its currency gets a null rate, because of the
LEFT JOIN.
To use the latest value instead of the value at the time of the row, use a lookup join. For
more information, see Creating lookup joins.