use arrow::{
array::{ArrayRef, Float32Array, Float64Array, UInt64Builder},
compute,
};
use arrow::{
array::{TimestampMicrosecondArray, TimestampNanosecondArray, UInt32Builder},
datatypes::TimeUnit,
};
use std::sync::Arc;
use std::time::Instant;
use std::{any::Any, collections::HashSet};
use async_trait::async_trait;
use futures::{Stream, StreamExt, TryStreamExt};
use hashbrown::HashMap;
use tokio::sync::Mutex;
use arrow::array::Array;
use arrow::datatypes::DataType;
use arrow::datatypes::{Schema, SchemaRef};
use arrow::error::Result as ArrowResult;
use arrow::record_batch::RecordBatch;
use arrow::array::{
Int16Array, Int32Array, Int64Array, Int8Array, StringArray, UInt16Array, UInt32Array,
UInt64Array, UInt8Array,
};
use super::expressions::col;
use super::{
hash_utils::{build_join_schema, check_join_is_valid, JoinOn, JoinType},
merge::MergeExec,
};
use crate::error::{DataFusionError, Result};
use super::{ExecutionPlan, Partitioning, RecordBatchStream, SendableRecordBatchStream};
use crate::physical_plan::coalesce_batches::concat_batches;
use ahash::RandomState;
use log::debug;
type JoinHashMap = HashMap<Vec<u8>, Vec<u64>, RandomState>;
type JoinLeftData = Arc<(JoinHashMap, RecordBatch)>;
#[derive(Debug)]
pub struct HashJoinExec {
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: Vec<(String, String)>,
join_type: JoinType,
schema: SchemaRef,
build_side: Arc<Mutex<Option<JoinLeftData>>>,
}
struct ColumnIndex {
index: usize,
is_left: bool,
}
impl HashJoinExec {
pub fn try_new(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: &JoinOn,
join_type: &JoinType,
) -> Result<Self> {
let left_schema = left.schema();
let right_schema = right.schema();
check_join_is_valid(&left_schema, &right_schema, &on)?;
let schema = Arc::new(build_join_schema(
&left_schema,
&right_schema,
on,
&join_type,
));
let on = on
.iter()
.map(|(l, r)| (l.to_string(), r.to_string()))
.collect();
Ok(HashJoinExec {
left,
right,
on,
join_type: *join_type,
schema,
build_side: Arc::new(Mutex::new(None)),
})
}
pub fn left(&self) -> &Arc<dyn ExecutionPlan> {
&self.left
}
pub fn right(&self) -> &Arc<dyn ExecutionPlan> {
&self.right
}
pub fn on(&self) -> &[(String, String)] {
&self.on
}
pub fn join_type(&self) -> &JoinType {
&self.join_type
}
fn column_indices_from_schema(&self) -> ArrowResult<Vec<ColumnIndex>> {
let (primary_is_left, primary_schema, secondary_schema) = match self.join_type {
JoinType::Inner | JoinType::Left => {
(true, self.left.schema(), self.right.schema())
}
JoinType::Right => (false, self.right.schema(), self.left.schema()),
};
let mut column_indices = Vec::with_capacity(self.schema.fields().len());
for field in self.schema.fields() {
let (is_primary, index) = match primary_schema.index_of(field.name()) {
Ok(i) => Ok((true, i)),
Err(_) => {
match secondary_schema.index_of(field.name()) {
Ok(i) => Ok((false, i)),
_ => Err(DataFusionError::Internal(
format!("During execution, the column {} was not found in neither the left or right side of the join", field.name()).to_string()
))
}
}
}.map_err(DataFusionError::into_arrow_external_error)?;
let is_left =
is_primary && primary_is_left || !is_primary && !primary_is_left;
column_indices.push(ColumnIndex { index, is_left });
}
Ok(column_indices)
}
}
#[async_trait]
impl ExecutionPlan for HashJoinExec {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
vec![self.left.clone(), self.right.clone()]
}
fn with_new_children(
&self,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
match children.len() {
2 => Ok(Arc::new(HashJoinExec::try_new(
children[0].clone(),
children[1].clone(),
&self.on,
&self.join_type,
)?)),
_ => Err(DataFusionError::Internal(
"HashJoinExec wrong number of children".to_string(),
)),
}
}
fn output_partitioning(&self) -> Partitioning {
self.right.output_partitioning()
}
async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
let left_data = {
let mut build_side = self.build_side.lock().await;
match build_side.as_ref() {
Some(stream) => stream.clone(),
None => {
let start = Instant::now();
let merge = MergeExec::new(self.left.clone());
let stream = merge.execute(0).await?;
let on_left = self
.on
.iter()
.map(|on| on.0.clone())
.collect::<HashSet<_>>();
let initial = (JoinHashMap::default(), Vec::new(), 0);
let (hashmap, batches, num_rows) = stream
.try_fold(initial, |mut acc, batch| async {
let hash = &mut acc.0;
let values = &mut acc.1;
let offset = acc.2;
update_hash(&on_left, &batch, hash, offset).unwrap();
acc.2 += batch.num_rows();
values.push(batch);
Ok(acc)
})
.await?;
let single_batch =
concat_batches(&batches[0].schema(), &batches, num_rows)?;
let left_side = Arc::new((hashmap, single_batch));
*build_side = Some(left_side.clone());
debug!(
"Built build-side of hash join containing {} rows in {} ms",
num_rows,
start.elapsed().as_millis()
);
left_side
}
}
};
let stream = self.right.execute(partition).await?;
let on_right = self
.on
.iter()
.map(|on| on.1.clone())
.collect::<HashSet<_>>();
let column_indices = self.column_indices_from_schema()?;
Ok(Box::pin(HashJoinStream {
schema: self.schema.clone(),
on_right,
join_type: self.join_type,
left_data,
right: stream,
column_indices,
num_input_batches: 0,
num_input_rows: 0,
num_output_batches: 0,
num_output_rows: 0,
join_time: 0,
}))
}
}
fn update_hash(
on: &HashSet<String>,
batch: &RecordBatch,
hash: &mut JoinHashMap,
offset: usize,
) -> Result<()> {
let keys_values = on
.iter()
.map(|name| Ok(col(name).evaluate(batch)?.into_array(batch.num_rows())))
.collect::<Result<Vec<_>>>()?;
let mut key = Vec::with_capacity(keys_values.len());
for row in 0..batch.num_rows() {
create_key(&keys_values, row, &mut key)?;
hash.raw_entry_mut()
.from_key(&key)
.and_modify(|_, v| v.push((row + offset) as u64))
.or_insert_with(|| (key.clone(), vec![(row + offset) as u64]));
}
Ok(())
}
struct HashJoinStream {
schema: Arc<Schema>,
on_right: HashSet<String>,
join_type: JoinType,
left_data: JoinLeftData,
right: SendableRecordBatchStream,
column_indices: Vec<ColumnIndex>,
num_input_batches: usize,
num_input_rows: usize,
num_output_batches: usize,
num_output_rows: usize,
join_time: usize,
}
impl RecordBatchStream for HashJoinStream {
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
}
fn build_batch_from_indices(
schema: &Schema,
left: &RecordBatch,
right: &RecordBatch,
left_indices: UInt64Array,
right_indices: UInt32Array,
column_indices: &Vec<ColumnIndex>,
) -> ArrowResult<RecordBatch> {
let mut columns: Vec<Arc<dyn Array>> = Vec::with_capacity(schema.fields().len());
for column_index in column_indices {
let array = if column_index.is_left {
let array = left.column(column_index.index);
compute::take(array.as_ref(), &left_indices, None)?
} else {
let array = right.column(column_index.index);
compute::take(array.as_ref(), &right_indices, None)?
};
columns.push(array);
}
RecordBatch::try_new(Arc::new(schema.clone()), columns)
}
pub(crate) fn create_key(
group_by_keys: &[ArrayRef],
row: usize,
vec: &mut Vec<u8>,
) -> Result<()> {
vec.clear();
for col in group_by_keys {
match col.data_type() {
DataType::Float32 => {
let array = col.as_any().downcast_ref::<Float32Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::Float64 => {
let array = col.as_any().downcast_ref::<Float64Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::UInt8 => {
let array = col.as_any().downcast_ref::<UInt8Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::UInt16 => {
let array = col.as_any().downcast_ref::<UInt16Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::UInt32 => {
let array = col.as_any().downcast_ref::<UInt32Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::UInt64 => {
let array = col.as_any().downcast_ref::<UInt64Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::Int8 => {
let array = col.as_any().downcast_ref::<Int8Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::Int16 => {
let array = col.as_any().downcast_ref::<Int16Array>().unwrap();
vec.extend(array.value(row).to_le_bytes().iter());
}
DataType::Int32 => {
let array = col.as_any().downcast_ref::<Int32Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::Int64 => {
let array = col.as_any().downcast_ref::<Int64Array>().unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::Timestamp(TimeUnit::Microsecond, None) => {
let array = col
.as_any()
.downcast_ref::<TimestampMicrosecondArray>()
.unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::Timestamp(TimeUnit::Nanosecond, None) => {
let array = col
.as_any()
.downcast_ref::<TimestampNanosecondArray>()
.unwrap();
vec.extend_from_slice(&array.value(row).to_le_bytes());
}
DataType::Utf8 => {
let array = col.as_any().downcast_ref::<StringArray>().unwrap();
let value = array.value(row);
vec.extend_from_slice(&value.len().to_le_bytes());
vec.extend_from_slice(value.as_bytes());
}
_ => {
return Err(DataFusionError::Internal(format!(
"Unsupported GROUP BY for {}",
col.data_type(),
)));
}
}
}
Ok(())
}
fn build_batch(
batch: &RecordBatch,
left_data: &JoinLeftData,
on_right: &HashSet<String>,
join_type: JoinType,
schema: &Schema,
column_indices: &Vec<ColumnIndex>,
) -> ArrowResult<RecordBatch> {
let (left_indices, right_indices) =
build_join_indexes(&left_data.0, &batch, join_type, on_right).unwrap();
build_batch_from_indices(
schema,
&left_data.1,
batch,
left_indices,
right_indices,
column_indices,
)
}
fn build_join_indexes(
left: &JoinHashMap,
right: &RecordBatch,
join_type: JoinType,
right_on: &HashSet<String>,
) -> Result<(UInt64Array, UInt32Array)> {
let keys_values = right_on
.iter()
.map(|name| Ok(col(name).evaluate(right)?.into_array(right.num_rows())))
.collect::<Result<Vec<_>>>()?;
let mut key = Vec::with_capacity(keys_values.len());
let mut left_indices = UInt64Builder::new(0);
let mut right_indices = UInt32Builder::new(0);
match join_type {
JoinType::Inner => {
for row in 0..right.num_rows() {
create_key(&keys_values, row, &mut key)?;
if let Some(indices) = left.get(&key) {
left_indices.append_slice(&indices)?;
for _ in 0..indices.len() {
right_indices.append_value(row as u32)?;
}
}
}
Ok((left_indices.finish(), right_indices.finish()))
}
JoinType::Left => {
let mut is_visited = HashSet::new();
for row in 0..right.num_rows() {
create_key(&keys_values, row, &mut key)?;
if let Some(indices) = left.get(&key) {
is_visited.insert(key.clone());
left_indices.append_slice(&indices)?;
for _ in 0..indices.len() {
right_indices.append_value(row as u32)?;
}
};
}
for (key, indices) in left {
if !is_visited.contains(key) {
left_indices.append_slice(&indices)?;
for _ in 0..indices.len() {
right_indices.append_null()?;
}
}
}
Ok((left_indices.finish(), right_indices.finish()))
}
JoinType::Right => {
for row in 0..right.num_rows() {
create_key(&keys_values, row, &mut key)?;
match left.get(&key) {
Some(indices) => {
left_indices.append_slice(&indices)?;
for _ in 0..indices.len() {
right_indices.append_value(row as u32)?;
}
}
None => {
left_indices.append_null()?;
right_indices.append_value(row as u32)?;
}
}
}
Ok((left_indices.finish(), right_indices.finish()))
}
}
}
impl Stream for HashJoinStream {
type Item = ArrowResult<RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
self.right
.poll_next_unpin(cx)
.map(|maybe_batch| match maybe_batch {
Some(Ok(batch)) => {
let start = Instant::now();
let result = build_batch(
&batch,
&self.left_data,
&self.on_right,
self.join_type,
&self.schema,
&self.column_indices,
);
self.num_input_batches += 1;
self.num_input_rows += batch.num_rows();
if let Ok(ref batch) = result {
self.join_time += start.elapsed().as_millis() as usize;
self.num_output_batches += 1;
self.num_output_rows += batch.num_rows();
}
Some(result)
}
other => {
debug!(
"Processed {} probe-side input batches containing {} rows and \
produced {} output batches containing {} rows in {} ms",
self.num_input_batches,
self.num_input_rows,
self.num_output_batches,
self.num_output_rows,
self.join_time
);
other
}
})
}
}
#[cfg(test)]
mod tests {
use crate::{
physical_plan::{common, memory::MemoryExec},
test::{build_table_i32, columns, format_batch},
};
use super::*;
use std::collections::HashSet;
use std::sync::Arc;
fn build_table(
a: (&str, &Vec<i32>),
b: (&str, &Vec<i32>),
c: (&str, &Vec<i32>),
) -> Arc<dyn ExecutionPlan> {
let batch = build_table_i32(a, b, c);
let schema = batch.schema();
Arc::new(MemoryExec::try_new(&vec![vec![batch]], schema, None).unwrap())
}
fn join(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: &[(&str, &str)],
join_type: &JoinType,
) -> Result<HashJoinExec> {
let on: Vec<_> = on
.iter()
.map(|(l, r)| (l.to_string(), r.to_string()))
.collect();
HashJoinExec::try_new(left, right, &on, join_type)
}
fn assert_same_rows(result: &[String], expected: &[&str]) {
let result = result.iter().cloned().collect::<HashSet<_>>();
let expected = expected
.iter()
.map(|s| s.to_string())
.collect::<HashSet<_>>();
assert_eq!(result, expected);
}
#[tokio::test]
async fn join_inner_one() -> Result<()> {
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 5]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = &[("b1", "b1")];
let join = join(left, right, on, &JoinType::Inner)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "c2"]);
let stream = join.execute(0).await?;
let batches = common::collect(stream).await?;
let result = format_batch(&batches[0]);
let expected = vec!["2,5,8,20,80", "3,5,9,20,80", "1,4,7,10,70"];
assert_same_rows(&result, &expected);
Ok(())
}
#[tokio::test]
async fn join_inner_one_no_shared_column_names() -> Result<()> {
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 5]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b2", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = &[("b1", "b2")];
let join = join(left, right, on, &JoinType::Inner)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
let stream = join.execute(0).await?;
let batches = common::collect(stream).await?;
let result = format_batch(&batches[0]);
let expected = vec!["2,5,8,20,5,80", "3,5,9,20,5,80", "1,4,7,10,4,70"];
assert_same_rows(&result, &expected);
Ok(())
}
#[tokio::test]
async fn join_inner_two() -> Result<()> {
let left = build_table(
("a1", &vec![1, 2, 2]),
("b2", &vec![1, 2, 2]),
("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a1", &vec![1, 2, 3]),
("b2", &vec![1, 2, 2]),
("c2", &vec![70, 80, 90]),
);
let on = &[("a1", "a1"), ("b2", "b2")];
let join = join(left, right, on, &JoinType::Inner)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b2", "c1", "c2"]);
let stream = join.execute(0).await?;
let batches = common::collect(stream).await?;
assert_eq!(batches.len(), 1);
let result = format_batch(&batches[0]);
let expected = vec!["1,1,7,70", "2,2,8,80", "2,2,9,80"];
assert_same_rows(&result, &expected);
Ok(())
}
#[tokio::test]
async fn join_inner_one_two_parts_left() -> Result<()> {
let batch1 = build_table_i32(
("a1", &vec![1, 2]),
("b2", &vec![1, 2]),
("c1", &vec![7, 8]),
);
let batch2 =
build_table_i32(("a1", &vec![2]), ("b2", &vec![2]), ("c1", &vec![9]));
let schema = batch1.schema();
let left = Arc::new(
MemoryExec::try_new(&vec![vec![batch1], vec![batch2]], schema, None).unwrap(),
);
let right = build_table(
("a1", &vec![1, 2, 3]),
("b2", &vec![1, 2, 2]),
("c2", &vec![70, 80, 90]),
);
let on = &[("a1", "a1"), ("b2", "b2")];
let join = join(left, right, on, &JoinType::Inner)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b2", "c1", "c2"]);
let stream = join.execute(0).await?;
let batches = common::collect(stream).await?;
assert_eq!(batches.len(), 1);
let result = format_batch(&batches[0]);
let expected = vec!["1,1,7,70", "2,2,8,80", "2,2,9,80"];
assert_same_rows(&result, &expected);
Ok(())
}
#[tokio::test]
async fn join_inner_one_two_parts_right() -> Result<()> {
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 5]), ("c1", &vec![7, 8, 9]),
);
let batch1 = build_table_i32(
("a2", &vec![10, 20]),
("b1", &vec![4, 6]),
("c2", &vec![70, 80]),
);
let batch2 =
build_table_i32(("a2", &vec![30]), ("b1", &vec![5]), ("c2", &vec![90]));
let schema = batch1.schema();
let right = Arc::new(
MemoryExec::try_new(&vec![vec![batch1], vec![batch2]], schema, None).unwrap(),
);
let on = &[("b1", "b1")];
let join = join(left, right, on, &JoinType::Inner)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "c2"]);
let stream = join.execute(0).await?;
let batches = common::collect(stream).await?;
assert_eq!(batches.len(), 1);
let result = format_batch(&batches[0]);
let expected = vec!["1,4,7,10,70"];
assert_same_rows(&result, &expected);
let stream = join.execute(1).await?;
let batches = common::collect(stream).await?;
assert_eq!(batches.len(), 1);
let result = format_batch(&batches[0]);
let expected = vec!["2,5,8,30,90", "3,5,9,30,90"];
assert_same_rows(&result, &expected);
Ok(())
}
#[tokio::test]
async fn join_left_one() -> Result<()> {
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]), ("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]),
("c2", &vec![70, 80, 90]),
);
let on = &[("b1", "b1")];
let join = join(left, right, on, &JoinType::Left)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "c2"]);
let stream = join.execute(0).await?;
let batches = common::collect(stream).await?;
let result = format_batch(&batches[0]);
let expected = vec!["1,4,7,10,70", "2,5,8,20,80", "3,7,9,NULL,NULL"];
assert_same_rows(&result, &expected);
Ok(())
}
#[tokio::test]
async fn join_right_one() -> Result<()> {
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![4, 5, 7]),
("c1", &vec![7, 8, 9]),
);
let right = build_table(
("a2", &vec![10, 20, 30]),
("b1", &vec![4, 5, 6]), ("c2", &vec![70, 80, 90]),
);
let on = &[("b1", "b1")];
let join = join(left, right, on, &JoinType::Right)?;
let columns = columns(&join.schema());
assert_eq!(columns, vec!["a1", "c1", "a2", "b1", "c2"]);
let stream = join.execute(0).await?;
let batches = common::collect(stream).await?;
let result = format_batch(&batches[0]);
let expected = vec!["1,7,10,4,70", "2,8,20,5,80", "NULL,NULL,30,6,90"];
assert_same_rows(&result, &expected);
Ok(())
}
}