Creating interval joins

An interval join combines the rows of two streams if the times of the rows are close to each other. Because Flink removes the rows that cannot match any more, the state stays small.

The join condition has an equality on a key and a condition on the time attributes. The time condition uses BETWEEN, or a comparison with an interval.

Use an interval join when the events of both streams happen almost at the same time. For example, use it for an order and its shipment event that arrives within a few hours.

  1. 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.
  2. In the Explorer, open the menu of Jobs, and click New Job.
    The Create New Job window opens.
  3. Enter a Job Name, or click Generate Job Name.
  4. Click Create.
    The job opens in a new tab, with an empty SQL editor.
  5. Enter the following statements in the SQL editor:
    CREATE TABLE orders (
      order_id INT,
      order_time AS LOCALTIMESTAMP,
      WATERMARK FOR order_time AS order_time - INTERVAL '5' SECOND
    ) WITH (
      'connector' = 'datagen',
      'rows-per-second' = '5',
      'fields.order_id.kind' = 'sequence',
      'fields.order_id.start' = '1',
      'fields.order_id.end' = '100000'
    );
    
    CREATE TABLE shipments (
      order_id INT,
      ship_time AS LOCALTIMESTAMP,
      WATERMARK FOR ship_time AS ship_time - INTERVAL '5' SECOND
    ) WITH (
      'connector' = 'datagen',
      'rows-per-second' = '5',
      'fields.order_id.kind' = 'sequence',
      'fields.order_id.start' = '1',
      'fields.order_id.end' = '100000'
    );
    
    CREATE TABLE shipped_orders (
      order_id INT,
      order_time TIMESTAMP(3),
      ship_time TIMESTAMP(3)
    ) WITH (
      'connector' = 'blackhole'
    );
    
    INSERT INTO shipped_orders
    SELECT o.order_id, o.order_time, s.ship_time
    FROM orders AS o, shipments AS s
    WHERE o.order_id = s.order_id
      AND o.order_time BETWEEN s.ship_time - INTERVAL '10' SECOND
                           AND s.ship_time + INTERVAL '10' SECOND;
  6. Click the Execute job icon.
    The job starts, and its status icon in the Explorer turns green.
  7. When you have finished, click Stop job.

In this example, an order matches a shipment with the same order_id when the order time is at most 10 seconds from the shipment time. For a real use, choose the interval from the delay that you expect between the two events.

To join a stream with a table that changes slowly, use a temporal join or a lookup join. For more information, see Creating temporal joins and Creating lookup joins.