From 8f53f556b2bf9f170b55876f98b5eb2ef86d47cf Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 11 Mar 2022 14:11:37 -0800 Subject: [PATCH 1/7] Flesh out row conversion API Refactor to use record batch builder Fix most compiler errors Get a compiling version Allow overriding container type A bit more progress Draft list handling Get parsing working Get example running all the way through Draft narrative documentation Enhance docs Remove unused line Fix lint issues Fix ORC references Move at end Fix integer types Use sizetype from rj Use static cast Format Setup for benchmarks Start debugging Always retrieve the correct allocator Must copy value to new allocator Better handling of unique ptr Format Use better template and pure virtual functions --- cpp/examples/arrow/CMakeLists.txt | 2 + cpp/examples/arrow/rapidjson_row_converter.cc | 590 ++++++++++++++++++ cpp/src/arrow/api.h | 1 + cpp/src/arrow/row_conversion.h | 192 ++++++ cpp/src/arrow/table_builder.h | 4 +- docs/source/cpp/api/utilities.rst | 9 + .../cpp/examples/row_columnar_conversion.rst | 91 +++ 7 files changed, 887 insertions(+), 2 deletions(-) create mode 100644 cpp/examples/arrow/rapidjson_row_converter.cc create mode 100644 cpp/src/arrow/row_conversion.h diff --git a/cpp/examples/arrow/CMakeLists.txt b/cpp/examples/arrow/CMakeLists.txt index 229373665d5e..0514bf912751 100644 --- a/cpp/examples/arrow/CMakeLists.txt +++ b/cpp/examples/arrow/CMakeLists.txt @@ -17,6 +17,8 @@ add_arrow_example(row_wise_conversion_example) +add_arrow_example(rapidjson_row_converter) + if(ARROW_COMPUTE) add_arrow_example(compute_register_example) endif() diff --git a/cpp/examples/arrow/rapidjson_row_converter.cc b/cpp/examples/arrow/rapidjson_row_converter.cc new file mode 100644 index 000000000000..0b4aa23ebb78 --- /dev/null +++ b/cpp/examples/arrow/rapidjson_row_converter.cc @@ -0,0 +1,590 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +// Transforming dynamic row data into Arrow data +// When building connectors to other data systems, it's common to receive data in +// row-based structures. While the row_wise_conversion_example.cc shows how to +// handle this conversion for fixed schemas, this example demonstrates how to +// writer converters for arbitrary schemas. +// +// As an example, this conversion is between Arrow and rapidjson::Documents. +// +// We use the following helpers and patterns here: +// * arrow::ToRowConverter and arrow::FromRowConverter, which provide additional +// conversion methods given a basic converter +// * arrow::VisitArrayInline and arrow::VisitTypeInline for implementing a visitor +// pattern with Arrow to handle different array types +// * arrow::enable_if_primitive_ctype to create a template method that handles +// * conversion for Arrow types that have corresponding C types (bool, integer, +// float). + +rapidjson::Value kNullJsonSingleton = rapidjson::Value(); + +/// \brief Builder that holds state for a single conversion. +/// +/// Implements Visit() methods for each type of Arrow Array that set the values +/// of the corresponding fields in each row. +class RowBatchBuilder { + public: + explicit RowBatchBuilder(int64_t num_rows) : field_(nullptr) { + // Reserve all of the space required up-front to avoid unnecessary resizing + rows_.reserve(num_rows); + + for (int64_t i = 0; i < num_rows; ++i) { + rows_.push_back(rapidjson::Document()); + rows_[i].SetObject(); + } + } + + /// \brief Set which field to convert. + void SetField(std::shared_ptr field) { field_ = std::move(field); } + + /// \brief Retrieve converted rows from builder. + std::vector Rows() && { return std::move(rows_); } + + // Default implementation + arrow::Status Visit(const arrow::Array& array) { + return arrow::Status::NotImplemented( + "Can not convert to json document for array of type ", array.type()->ToString()); + } + + // Handles booleans, integers, floats + template + arrow::enable_if_primitive_ctype Visit( + const ArrayType& array) { + for (int64_t i = 0; i < array.length(); ++i) { + if (!array.IsNull(i)) { + rapidjson::Value str_key(field_->name().c_str(), rows_[i].GetAllocator()); + rows_[i].AddMember(str_key, array.Value(i), rows_[i].GetAllocator()); + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::StringArray& array) { + for (int64_t i = 0; i < array.length(); ++i) { + if (!array.IsNull(i)) { + rapidjson::Value str_key(field_->name().c_str(), rows_[i].GetAllocator()); + // StringArray.Value returns a string view + auto value_view = array.Value(i); + rapidjson::Value value; + value.SetString(value_view.data(), + static_cast(value_view.size()), + rows_[i].GetAllocator()); + rows_[i].AddMember(str_key, value, rows_[i].GetAllocator()); + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::StructArray& array) { + const arrow::StructType* type = array.struct_type(); + + RowBatchBuilder child_builder(rows_.size()); + for (int i = 0; i < type->num_fields(); ++i) { + std::shared_ptr child_field = type->field(i); + child_builder.SetField(std::move(child_field)); + ARROW_RETURN_NOT_OK(arrow::VisitArrayInline(*array.field(i).get(), &child_builder)); + } + std::vector rows = std::move(child_builder).Rows(); + + for (int64_t i = 0; i < array.length(); ++i) { + if (!array.IsNull(i)) { + rapidjson::Value str_key(field_->name().c_str(), rows_[i].GetAllocator()); + // Must copy value to new allocator + rapidjson::Value row_val; + row_val.CopyFrom(rows[i], rows_[i].GetAllocator()); + rows_[i].AddMember(str_key, row_val, rows_[i].GetAllocator()); + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::ListArray& array) { + // First create rows from values + std::shared_ptr values = array.values(); + RowBatchBuilder child_builder(values->length()); + std::shared_ptr value_field = array.list_type()->value_field(); + std::string value_field_name = value_field->name(); + child_builder.SetField(value_field); + ARROW_RETURN_NOT_OK(arrow::VisitArrayInline(*values.get(), &child_builder)); + + std::vector rows = std::move(child_builder).Rows(); + + int64_t values_i = 0; + for (int64_t i = 0; i < array.length(); ++i) { + rapidjson::Document::AllocatorType& allocator = rows_[i].GetAllocator(); + auto array_len = array.value_length(i); + + rapidjson::Value value; + value.SetArray(); + value.Reserve(array_len, allocator); + + for (int64_t j = 0; j < array_len; ++j) { + rapidjson::Value row_val; + // Must copy value to new allocator + row_val.CopyFrom(rows[values_i][value_field_name.c_str()], allocator); + value.PushBack(row_val, allocator); + ++values_i; + } + + rapidjson::Value str_key(field_->name().c_str(), allocator); + rows_[i].AddMember(str_key, value, allocator); + } + + return arrow::Status::OK(); + } + + private: + std::shared_ptr field_; + std::vector rows_; +}; // RowBatchBuilder + +class ArrowToDocumentConverter : public arrow::ToRowConverter { + public: + arrow::Result> ConvertToVector( + std::shared_ptr batch) override { + RowBatchBuilder builder{batch->num_rows()}; + + for (int i = 0; i < batch->num_columns(); ++i) { + builder.SetField(std::move(batch->schema()->field(i))); + ARROW_RETURN_NOT_OK(arrow::VisitArrayInline(*batch->column(i).get(), &builder)); + } + + return std::move(builder).Rows(); + } +}; // ArrowToDocumentConverter + +/// \brief Iterator over rows values of a document for a given field +/// +/// path and array_levels are used to address each field in a JSON document. As +/// an example, consider this JSON document: +/// { +/// "x": 3, // path: ["x"], array_levels: 0 +/// "files": [ // path: ["files"], array_levels: 0 +/// { // path: ["files"], array_levels: 1 +/// "path": "my_str", // path: ["files", "path"], array_levels: 1 +/// "sizes": [ // path: ["files", "size"], array_levels: 1 +/// 20, // path: ["files", "size"], array_levels: 2 +/// 22 +/// ] +/// } +/// ] +/// }, +class DocValuesIterator { + public: + /// \param rows vector of rows + /// \param path field names to enter + /// \param array_levels number of arrays to enter + DocValuesIterator(const std::vector& rows, + std::vector path, int64_t array_levels) + : rows(rows), path(std::move(path)), array_levels(array_levels) {} + + const rapidjson::Value* NextArrayOrRow(const rapidjson::Value* value, size_t* path_i, + int64_t* arr_i) { + while (array_stack.size() > 0) { + ArrayPosition& pos = array_stack.back(); + // Try to get next position in Array + if (pos.index + 1 < pos.array_node->Size()) { + ++pos.index; + value = &(*pos.array_node)[pos.index]; + *path_i = pos.path_index; + *arr_i = array_stack.size(); + return value; + } else { + array_stack.pop_back(); + } + } + ++row_i; + if (row_i < rows.size()) { + value = static_cast(&rows[row_i]); + } else { + value = nullptr; + } + *path_i = 0; + *arr_i = 0; + return value; + } + + arrow::Result Next() { + const rapidjson::Value* value = nullptr; + size_t path_i; + int64_t arr_i; + // Can either start at document or at last array level + if (array_stack.size() > 0) { + auto pos = array_stack.back(); + value = pos.array_node; + path_i = pos.path_index; + arr_i = array_stack.size() - 1; + } + + value = NextArrayOrRow(value, &path_i, &arr_i); + + // Traverse to desired level (with possible backtracking as needed) + while (path_i < path.size() || arr_i < array_levels) { + if (value == nullptr) { + return value; + } else if (value->IsArray() && value->Size() > 0) { + ArrayPosition pos; + pos.array_node = value; + pos.path_index = path_i; + pos.index = 0; + array_stack.push_back(pos); + + value = &(*value)[0]; + ++arr_i; + } else if (value->IsArray()) { + // Empty array means we need to backtrack and go to next array or row + value = NextArrayOrRow(value, &path_i, &arr_i); + } else if (value->HasMember(path[path_i].c_str())) { + value = &(*value)[path[path_i].c_str()]; + ++path_i; + } else { + return &kNullJsonSingleton; + } + } + + // Return value + return value; + } + + protected: + const std::vector& rows; + std::vector path; + int64_t array_levels; + size_t row_i = -1; // index of current row + + // Info about array position for one array level in array stack + struct ArrayPosition { + const rapidjson::Value* array_node; + int64_t path_index; + rapidjson::SizeType index; + }; + std::vector array_stack; +}; + +class JsonValueConverter { + public: + explicit JsonValueConverter(const std::vector& rows) + : rows_(rows), array_levels_(0) {} + + JsonValueConverter(const std::vector& rows, + const std::vector& root_path, int64_t array_levels) + : rows_(rows), root_path_(root_path), array_levels_(array_levels) {} + + /// \brief For field passed in, append corresponding values to builder + arrow::Status Convert(const arrow::Field& field, arrow::ArrayBuilder* builder) { + return Convert(field, field.name(), builder); + } + + /// \brief For field passed in, append corresponding values to builder + arrow::Status Convert(const arrow::Field& field, const std::string& field_name, + arrow::ArrayBuilder* builder) { + field_name_ = field_name; + builder_ = builder; + ARROW_RETURN_NOT_OK(arrow::VisitTypeInline(*field.type().get(), this)); + return arrow::Status::OK(); + } + + // Default implementation + arrow::Status Visit(const arrow::DataType& type) { + return arrow::Status::NotImplemented( + "Can not convert to json document for array of type ", type.ToString()); + } + + arrow::Status Visit(const arrow::Int64Type& type) { + arrow::Int64Builder* builder = static_cast(builder_); + for (const auto& maybe_value : FieldValues()) { + ARROW_ASSIGN_OR_RAISE(auto value, maybe_value); + if (value->IsNull()) { + ARROW_RETURN_NOT_OK(builder->AppendNull()); + } else { + if (value->IsUint()) { + ARROW_RETURN_NOT_OK(builder->Append(value->GetUint())); + } else if (value->IsInt()) { + ARROW_RETURN_NOT_OK(builder->Append(value->GetInt())); + } else if (value->IsUint64()) { + ARROW_RETURN_NOT_OK(builder->Append(value->GetUint64())); + } else if (value->IsInt64()) { + ARROW_RETURN_NOT_OK(builder->Append(value->GetInt64())); + } else { + return arrow::Status::Invalid("Value is not an integer"); + } + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::DoubleType& type) { + arrow::DoubleBuilder* builder = static_cast(builder_); + for (const auto& maybe_value : FieldValues()) { + ARROW_ASSIGN_OR_RAISE(auto value, maybe_value); + if (value->IsNull()) { + ARROW_RETURN_NOT_OK(builder->AppendNull()); + } else { + ARROW_RETURN_NOT_OK(builder->Append(value->GetDouble())); + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::StringType& type) { + arrow::StringBuilder* builder = static_cast(builder_); + for (const auto& maybe_value : FieldValues()) { + ARROW_ASSIGN_OR_RAISE(auto value, maybe_value); + if (value->IsNull()) { + ARROW_RETURN_NOT_OK(builder->AppendNull()); + } else { + ARROW_RETURN_NOT_OK(builder->Append(value->GetString())); + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::BooleanType& type) { + arrow::BooleanBuilder* builder = static_cast(builder_); + for (const auto& maybe_value : FieldValues()) { + ARROW_ASSIGN_OR_RAISE(auto value, maybe_value); + if (value->IsNull()) { + ARROW_RETURN_NOT_OK(builder->AppendNull()); + } else { + ARROW_RETURN_NOT_OK(builder->Append(value->GetBool())); + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::StructType& type) { + arrow::StructBuilder* builder = static_cast(builder_); + + std::vector child_path(root_path_); + if (field_name_.size() > 0) { + child_path.push_back(field_name_); + } + auto child_converter = JsonValueConverter(rows_, child_path, array_levels_); + + for (int i = 0; i < type.num_fields(); ++i) { + std::shared_ptr child_field = type.field(i); + std::shared_ptr child_builder = builder->child_builder(i); + + ARROW_RETURN_NOT_OK( + child_converter.Convert(*child_field.get(), child_builder.get())); + } + + // Make null bitmap + for (const auto& maybe_value : FieldValues()) { + ARROW_ASSIGN_OR_RAISE(auto value, maybe_value); + ARROW_RETURN_NOT_OK(builder->Append(!value->IsNull())); + } + + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::ListType& type) { + arrow::ListBuilder* builder = static_cast(builder_); + + // Values and offsets needs to be interleaved in ListBuilder, so first collect the + // values + std::unique_ptr tmp_value_builder; + ARROW_ASSIGN_OR_RAISE(tmp_value_builder, + arrow::MakeBuilder(builder->value_builder()->type())); + std::vector child_path(root_path_); + child_path.push_back(field_name_); + auto child_converter = JsonValueConverter(rows_, child_path, array_levels_ + 1); + ARROW_RETURN_NOT_OK( + child_converter.Convert(*type.value_field().get(), "", tmp_value_builder.get())); + + std::shared_ptr values_array; + ARROW_RETURN_NOT_OK(tmp_value_builder->Finish(&values_array)); + std::shared_ptr values_data = values_array->data(); + + arrow::ArrayBuilder* value_builder = builder->value_builder(); + int64_t offset = 0; + for (const auto& maybe_value : FieldValues()) { + ARROW_ASSIGN_OR_RAISE(auto value, maybe_value); + ARROW_RETURN_NOT_OK(builder->Append(!value->IsNull())); + if (!value->IsNull() && value->Size() > 0) { + ARROW_RETURN_NOT_OK( + value_builder->AppendArraySlice(*values_data.get(), offset, value->Size())); + offset += value->Size(); + } + } + + return arrow::Status::OK(); + } + + protected: + std::string field_name_; + arrow::ArrayBuilder* builder_; + const std::vector& rows_; + std::vector root_path_; + int64_t array_levels_; + + /// Return a flattened iterator over values at nested location + arrow::Iterator FieldValues() { + std::vector path(root_path_); + if (field_name_.size() > 0) { + path.push_back(field_name_); + } + auto iter = DocValuesIterator(rows_, std::move(path), array_levels_); + auto fn = [iter]() mutable -> arrow::Result { + return iter.Next(); + }; + + return arrow::MakeFunctionIterator(fn); + } +}; // JsonValueConverter + +class DocumentToArrowConverter : public arrow::FromRowConverter { + public: + explicit DocumentToArrowConverter(arrow::MemoryPool* pool) : pool_(pool) {} + + arrow::Result> ConvertToRecordBatch( + const std::vector& rows, + std::shared_ptr schema) override { + std::unique_ptr batch_builder; + ARROW_ASSIGN_OR_RAISE(batch_builder, + arrow::RecordBatchBuilder::Make(schema, pool_, rows.size())); + + JsonValueConverter converter(rows); + for (int i = 0; i < batch_builder->num_fields(); ++i) { + std::shared_ptr field = schema->field(i); + arrow::ArrayBuilder* builder = batch_builder->GetField(i); + ARROW_RETURN_NOT_OK(converter.Convert(*field.get(), builder)); + } + + std::shared_ptr batch; + ARROW_ASSIGN_OR_RAISE(batch, batch_builder->Flush()); + + DCHECK_OK(batch->ValidateFull()); + return batch; + } + + protected: + arrow::MemoryPool* pool_; +}; // DocumentToArrowConverter + +int main(int argc, char** argv) { + // Get sizes + int32_t num_rows = argc > 1 ? std::atoi(argv[1]) : 100; + int32_t batch_size = argc > 2 ? std::atoi(argv[2]) : 100; + + //(Doc section: Convert to Arrow) + // Write JSON records + std::vector json_records = { + R"({"pk": 1, "date_created": "2020-10-01", "data": {"deleted": true, "metrics": [{"key": "x", "value": 1}]}})", + R"({"pk": 2, "date_created": "2020-10-03", "data": {"deleted": false, "metrics": []}})", + R"({"pk": 3, "date_created": "2020-10-05", "data": {"deleted": false, "metrics": [{"key": "x", "value": 33}, {"key": "x", "value": 42}]}})"}; + + std::vector records; + records.reserve(num_rows); + for (int32_t i = 0; i < num_rows; ++i) { + rapidjson::Document document; + document.Parse(json_records[i % json_records.size()].c_str()); + records.push_back(std::move(document)); + } + // for (const std::string& json : json_records) { + // rapidjson::Document document; + // document.Parse(json.c_str()); + // records.push_back(std::move(document)); + // } + for (const rapidjson::Document& doc : records) { + rapidjson::StringBuffer sb; + rapidjson::Writer writer(sb); + // At batch_size >= 495, we segfault here: + doc.Accept(writer); + std::cout << sb.GetString() << std::endl; + } + auto tags_schema = arrow::list(arrow::struct_({ + arrow::field("key", arrow::utf8()), + arrow::field("value", arrow::int64()), + })); + auto schema = arrow::schema( + {arrow::field("pk", arrow::int64()), arrow::field("date_created", arrow::utf8()), + arrow::field("data", arrow::struct_({arrow::field("deleted", arrow::boolean()), + arrow::field("metrics", tags_schema)}))}); + + // Create converter + DocumentToArrowConverter to_arrow_converter(arrow::default_memory_pool()); + + // Convert records into a table + arrow::Result> table_result = + to_arrow_converter.ConvertToTable(records, schema); + std::shared_ptr table = std::move(table_result).ValueOrDie(); + + // Print table + std::cout << table->ToString() << std::endl; + auto res = table->ValidateFull(); + if (!res.ok()) { + std::cout << res.detail() << std::endl; + } + //(Doc section: Convert to Arrow) + + //(Doc section: Convert to Rows) + // Create converter + ArrowToDocumentConverter to_doc_converter; + + // Convert table into document (row) iterator + arrow::Iterator document_iter = + to_doc_converter.ConvertToIterator(table, batch_size); + + // Print each row + for (arrow::Result doc_result : document_iter) { + rapidjson::Document doc = std::move(doc_result).ValueOrDie(); + + assert(doc.HasMember("pk")); + assert(doc["pk"].IsInt64()); + assert(doc.HasMember("date_created")); + assert(doc["date_created"].IsString()); + assert(doc.HasMember("data")); + assert(doc["data"].IsObject()); + assert(doc["data"].HasMember("deleted")); + assert(doc["data"]["deleted"].IsBool()); + assert(doc["data"].HasMember("metrics")); + assert(doc["data"]["metrics"].IsArray()); + if (doc["data"]["metrics"].Size() > 0) { + auto metric = &doc["data"]["metrics"][0]; + assert(metric->IsObject()); + assert(metric->HasMember("key")); + assert((*metric)["key"].IsString()); + assert(metric->HasMember("value")); + assert((*metric)["value"].IsInt64()); + } + + rapidjson::StringBuffer sb; + rapidjson::Writer writer(sb); + doc.Accept(writer); + std::cout << sb.GetString() << std::endl; + } + //(Doc section: Convert to Rows) +} diff --git a/cpp/src/arrow/api.h b/cpp/src/arrow/api.h index 1aabee35b10f..d1e19340d196 100644 --- a/cpp/src/arrow/api.h +++ b/cpp/src/arrow/api.h @@ -32,6 +32,7 @@ #include "arrow/pretty_print.h" // IYWU pragma: export #include "arrow/record_batch.h" // IYWU pragma: export #include "arrow/result.h" // IYWU pragma: export +#include "arrow/row_conversion.h" // IYWU pragma: export #include "arrow/status.h" // IYWU pragma: export #include "arrow/table.h" // IYWU pragma: export #include "arrow/table_builder.h" // IYWU pragma: export diff --git a/cpp/src/arrow/row_conversion.h b/cpp/src/arrow/row_conversion.h new file mode 100644 index 000000000000..665a9f9530a7 --- /dev/null +++ b/cpp/src/arrow/row_conversion.h @@ -0,0 +1,192 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "arrow/record_batch.h" +#include "arrow/table.h" +#include "arrow/util/iterator.h" + +namespace arrow { + +/// \brief Base class for Arrow to row converter. +/// +/// To use, specialize the conversion for a particular row type. +/// +/// \tparam RowType type that contains a single row +/// \tparam ContainerType optional alternative vector implementation +/// +/// The derived conversion functions take a batch_size parameter that determines +/// how many rows convert at once. This allows you to do the conversion in smaller +/// batches. +template class ContainerType = std::vector> +class ToRowConverter { + public: + /// \brief Convert a record batch into a vector of rows. + /// + /// Implement this method in specialized classes to derive all other methods. + /// + /// \param batch Record batch to convert + /// \return A vector of rows containing all data in batch + virtual Result> ConvertToVector( + std::shared_ptr batch) = 0; + + /// \brief Convert a record batch into a vector of rows. + /// + /// \param batch Record batch to convert + /// \param batch_size Number of rows to convert at once + /// \return A vector of rows containing all data in batch + Result> ConvertToVector(std::shared_ptr batch, + size_t batch_size) { + ARROW_ASSIGN_OR_RAISE(std::shared_ptr table, + Table::FromRecordBatches({batch})); + return ConvertToVector(table, batch_size); + } + + /// \brief Convert an Arrow table to a vector of rows. + /// + /// \param table Table to convert + /// \param batch_size Number of rows to convert at once + /// \return A vector of rows containing all data in table + Result> ConvertToVector(std::shared_ptr
table, + size_t batch_size) { + ContainerType out; + + TableBatchReader batch_reader(*table); + batch_reader.set_chunksize(batch_size); + for (auto batch : batch_reader) { + ARROW_ASSIGN_OR_RAISE(auto converted, ConvertToVector(batch)); + out.extend(converted); + } + + return out; + } + + /// \brief Convert a record batch stream to a iterator of rows. + /// + /// \param reader a record batch reader + /// \return A iterator of rows yielding each row produced by reader + Iterator ConvertToIterator(std::shared_ptr reader) { + auto read_batch = + [this](const std::shared_ptr& batch) -> Result> { + ARROW_ASSIGN_OR_RAISE(auto rows, ConvertToVector(batch)); + return MakeVectorIterator(std::move(rows)); + }; + + auto nested_iter = + MakeMaybeMapIterator(read_batch, MakeIteratorFromReader(std::move(reader))); + + return MakeFlattenIterator(std::move(nested_iter)); + } + + /// \brief Convert an Arrow table to a iterator of rows. + /// + /// \param table Table to convert + /// \param batch_size Number of rows to convert at once + /// \return A iterator of rows yielding each row in table + Iterator ConvertToIterator(std::shared_ptr
table, size_t batch_size) { + auto batch_reader = std::make_shared(*table); + batch_reader->set_chunksize(batch_size); + + return ConvertToIterator(batch_reader); + } + + /// \brief Convert an Arrow record batch to an iterator of rows. + /// + /// \param batch Record batch to convert + /// \param batch_size Number of rows to convert at once + /// \return A iterator of rows yielding each row in batch + Iterator ConvertToIterator(std::shared_ptr batch, + size_t batch_size) { + ARROW_ASSIGN_OR_RAISE(std::shared_ptr
table, + Table::FromRecordBatches({batch})); + return ConvertToIterator(table, batch_size); + } +}; + +/// \brief Base class for Row to Arrow conversions. +/// +/// To use, specialize the conversion for a particular row type. +/// +/// \tparam RowType type that contains a single row +/// \tparam ContainerType optional alternative vector implementation +template class ContainerType = std::vector> +class FromRowConverter { + public: + /// \brief Convert a vector of rows to a record batch. + /// + /// Implement this method to enable all other methods. + /// + /// \param rows Vector of rows to convert + /// \param schema Schema of record batch to convert to + /// \return Arrow result with record batch containing all rows + virtual Result> ConvertToRecordBatch( + const ContainerType& rows, std::shared_ptr schema) = 0; + + /// \brief Convert a vector of rows to an Arrow table + /// + /// \param rows Vector of rows to convert + /// \param schema Schema of record batch to convert to + /// \return Arrow result with table containing all rows + Result> ConvertToTable(const ContainerType& rows, + std::shared_ptr schema) { + ARROW_ASSIGN_OR_RAISE(std::shared_ptr batch, + ConvertToRecordBatch(rows, schema)); + return Table::FromRecordBatches({batch}); + } + + /// \brief Convert a vector of rows to a record batch reader. + /// + /// \param row_iter Iterator of rows + /// \param schema Schema of record batches to convert to + /// \param batch_size Max size of record batches to produce in reader + /// \return Arrow result with record batch reader containing all rows + Result> ConvertToReader( + Iterator row_iter, std::shared_ptr schema, size_t batch_size) { + auto get_next_batch = [row_iter, batch_size, schema, + this]() -> Result> { + ContainerType rows; + RowType row; + rows.reserve(batch_size); + + while (true) { + auto row_res = row_iter->Next(); + if (row_res.ok()) { + row = std::move(row).MoveValueUnsafe(); + } + if (row == NULLPTR) { + break; + } + rows.emplace_back(row); + + if (rows.size() == batch_size) { + break; + } + } + + if (rows.size() > 0) { + return ConvertToRecordBatch(rows, schema); + } else { + return IterationTraits::End(); + } + }; + + auto batch_iter = MakeFunctionIterator(get_next_batch); + + return SimpleRecordBatchReader(batch_iter, schema); + } +}; + +} // namespace arrow diff --git a/cpp/src/arrow/table_builder.h b/cpp/src/arrow/table_builder.h index f2e030fff030..65ebd86ea416 100644 --- a/cpp/src/arrow/table_builder.h +++ b/cpp/src/arrow/table_builder.h @@ -38,7 +38,7 @@ class RecordBatch; /// schema class ARROW_EXPORT RecordBatchBuilder { public: - /// \brief Create an initialize a RecordBatchBuilder + /// \brief Create and initialize a RecordBatchBuilder /// \param[in] schema The schema for the record batch /// \param[in] pool A MemoryPool to use for allocations /// \param[in] builder the created builder instance @@ -46,7 +46,7 @@ class ARROW_EXPORT RecordBatchBuilder { static Status Make(const std::shared_ptr& schema, MemoryPool* pool, std::unique_ptr* builder); - /// \brief Create an initialize a RecordBatchBuilder + /// \brief Create and initialize a RecordBatchBuilder /// \param[in] schema The schema for the record batch /// \param[in] pool A MemoryPool to use for allocations /// \param[in] initial_capacity The initial capacity for the builders diff --git a/docs/source/cpp/api/utilities.rst b/docs/source/cpp/api/utilities.rst index 5ce3d7d1a4e4..fab346753b55 100644 --- a/docs/source/cpp/api/utilities.rst +++ b/docs/source/cpp/api/utilities.rst @@ -57,6 +57,15 @@ Compression .. doxygenclass:: arrow::util::Decompressor :members: +Row Conversion +============== + +.. doxygenclass:: arrow::ToRowConverter + :members: + +.. doxygenclass:: arrow::FromRowConverter + :members: + Visitors ======== diff --git a/docs/source/cpp/examples/row_columnar_conversion.rst b/docs/source/cpp/examples/row_columnar_conversion.rst index 3f45864c2283..64645814f392 100644 --- a/docs/source/cpp/examples/row_columnar_conversion.rst +++ b/docs/source/cpp/examples/row_columnar_conversion.rst @@ -21,7 +21,98 @@ Row to columnar conversion ========================== +Fixed Schemas +------------- + The following example converts an array of structs to a :class:`arrow::Table` instance, and then converts it back to the original array of structs. .. literalinclude:: ../../../../cpp/examples/arrow/row_wise_conversion_example.cc + + +Dynamic Schemas +--------------- + +For schemas not known at compile time, implement an :class:`arrow::ToRowConverter` +or an :class:`arrow::FromRowConverter`. +The following example shows how to implement conversion between `rapidjson::Document` +and Arrow objects. You can read the full example at +https://github.com/apache/arrow/blob/master/cpp/examples/arrow/rapidjson_row_converter.cc + +Writing conversions to Arrow +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To handle conversions into Arrow, define an :class:`arrow::FromRowConverter` specialized +for your row data structure. In this example, we use :class:`arrow::RecordBatchBuilder`, +which conveniently creates builders for each field in the schemas. Another class ``JsonValueConverter``, +which is introduced next, will handle getting the values from the rows and appending +to the appropriate builder, given a field. + +.. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc + :language: cpp + :start-at: class DocumentToArrowConverter + :end-at: }; // DocumentToArrowConverter + :linenos: + :lineno-match: + +The ``JsonValueConverter`` implements ``Visit()`` methods for each relevant array +type that append to the current builder. Then the ``Convert()`` method simply +sets the current field, builder, and then calls :func:`arrow::VisitTypeInline`. + +.. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc + :language: cpp + :start-at: class JsonValueConverter + :end-at: }; // JsonValueConverter + :linenos: + :lineno-match: + +With those defined, we can convert rows into a table using an instance of the +converter: + +.. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc + :language: cpp + :start-after: (Doc section: Convert to Arrow) + :end-before: (Doc section: Convert to Arrow) + :linenos: + :lineno-match: + + +Writing conversions from Arrow +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To convert into rows *from* Arrow, define an :class:`arrow::ToRowConverter` specialized +for your row data structure. In our example, we define a ``RowBatchBuilder`` class +to handle converting each column and assigning field values to each row. Because +the builder implements ``Visit()`` methods for each Arrow array type, it can be +passed to :func:`arrow::VisitArrayInline` to dispatch to the appropriate logic for +each array type. + +.. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc + :language: cpp + :start-at: class ArrowToDocumentConverter + :end-at: }; // ArrowToDocumentConverter + :linenos: + :lineno-match: + +The ``RowBatchBuilder`` implements ``Visit()`` methods, but to save on code is +able to write a template method for array types that have primitive C equivalents +(booleans, integers, and floats). It uses the ``arrow::enable_if_primitive_ctype`` +to narrow the template to only apply to relevant array types. See :ref:`type-traits` +for other type predicates. + +.. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc + :language: cpp + :start-at: class RowBatchBuilder + :end-at: }; // RowBatchBuilder + :linenos: + :lineno-match: + +Finally, we can use the converter iterate over rows in the batch as rapidjson +Documents: + +.. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc + :language: cpp + :start-after: (Doc section: Convert to Rows) + :end-before: (Doc section: Convert to Rows) + :linenos: + :lineno-match: \ No newline at end of file From 189100e9f7dfa52f9a4ad8d4d1d17314d424f9a2 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Tue, 14 Jun 2022 07:56:29 +0200 Subject: [PATCH 2/7] chore: respond to basic PR feedback --- cpp/examples/arrow/rapidjson_row_converter.cc | 66 +++++++++++-------- 1 file changed, 37 insertions(+), 29 deletions(-) diff --git a/cpp/examples/arrow/rapidjson_row_converter.cc b/cpp/examples/arrow/rapidjson_row_converter.cc index 0b4aa23ebb78..eec06d9892be 100644 --- a/cpp/examples/arrow/rapidjson_row_converter.cc +++ b/cpp/examples/arrow/rapidjson_row_converter.cc @@ -48,7 +48,7 @@ // * conversion for Arrow types that have corresponding C types (bool, integer, // float). -rapidjson::Value kNullJsonSingleton = rapidjson::Value(); +const rapidjson::Value kNullJsonSingleton = rapidjson::Value(); /// \brief Builder that holds state for a single conversion. /// @@ -67,7 +67,7 @@ class RowBatchBuilder { } /// \brief Set which field to convert. - void SetField(std::shared_ptr field) { field_ = std::move(field); } + void SetField(const arrow::Field* field) { field_ = field; } /// \brief Retrieve converted rows from builder. std::vector Rows() && { return std::move(rows_); } @@ -82,6 +82,7 @@ class RowBatchBuilder { template arrow::enable_if_primitive_ctype Visit( const ArrayType& array) { + assert((int64_t)rows_.size() == array.length()); for (int64_t i = 0; i < array.length(); ++i) { if (!array.IsNull(i)) { rapidjson::Value str_key(field_->name().c_str(), rows_[i].GetAllocator()); @@ -92,11 +93,11 @@ class RowBatchBuilder { } arrow::Status Visit(const arrow::StringArray& array) { + assert((int64_t)rows_.size() == array.length()); for (int64_t i = 0; i < array.length(); ++i) { if (!array.IsNull(i)) { rapidjson::Value str_key(field_->name().c_str(), rows_[i].GetAllocator()); - // StringArray.Value returns a string view - auto value_view = array.Value(i); + arrow::util::string_view value_view = array.Value(i); rapidjson::Value value; value.SetString(value_view.data(), static_cast(value_view.size()), @@ -110,10 +111,12 @@ class RowBatchBuilder { arrow::Status Visit(const arrow::StructArray& array) { const arrow::StructType* type = array.struct_type(); + assert((int64_t)rows_.size() == array.length()); + RowBatchBuilder child_builder(rows_.size()); for (int i = 0; i < type->num_fields(); ++i) { - std::shared_ptr child_field = type->field(i); - child_builder.SetField(std::move(child_field)); + const arrow::Field* child_field = type->field(i).get(); + child_builder.SetField(child_field); ARROW_RETURN_NOT_OK(arrow::VisitArrayInline(*array.field(i).get(), &child_builder)); } std::vector rows = std::move(child_builder).Rows(); @@ -131,10 +134,11 @@ class RowBatchBuilder { } arrow::Status Visit(const arrow::ListArray& array) { + assert((int64_t)rows_.size() == array.length()); // First create rows from values std::shared_ptr values = array.values(); RowBatchBuilder child_builder(values->length()); - std::shared_ptr value_field = array.list_type()->value_field(); + const arrow::Field* value_field = array.list_type()->value_field().get(); std::string value_field_name = value_field->name(); child_builder.SetField(value_field); ARROW_RETURN_NOT_OK(arrow::VisitArrayInline(*values.get(), &child_builder)); @@ -143,6 +147,8 @@ class RowBatchBuilder { int64_t values_i = 0; for (int64_t i = 0; i < array.length(); ++i) { + if (array.IsNull(i)) continue; + rapidjson::Document::AllocatorType& allocator = rows_[i].GetAllocator(); auto array_len = array.value_length(i); @@ -166,7 +172,7 @@ class RowBatchBuilder { } private: - std::shared_ptr field_; + const arrow::Field* field_; std::vector rows_; }; // RowBatchBuilder @@ -177,7 +183,7 @@ class ArrowToDocumentConverter : public arrow::ToRowConverternum_rows()}; for (int i = 0; i < batch->num_columns(); ++i) { - builder.SetField(std::move(batch->schema()->field(i))); + builder.SetField(batch->schema()->field(i).get()); ARROW_RETURN_NOT_OK(arrow::VisitArrayInline(*batch->column(i).get(), &builder)); } @@ -319,7 +325,7 @@ class JsonValueConverter { // Default implementation arrow::Status Visit(const arrow::DataType& type) { return arrow::Status::NotImplemented( - "Can not convert to json document for array of type ", type.ToString()); + "Can not convert json value to Arrow array of type ", type.ToString()); } arrow::Status Visit(const arrow::Int64Type& type) { @@ -494,11 +500,7 @@ class DocumentToArrowConverter : public arrow::FromRowConverter 1 ? std::atoi(argv[1]) : 100; - int32_t batch_size = argc > 2 ? std::atoi(argv[2]) : 100; - +arrow::Status DoRowConversion(int32_t num_rows, int32_t batch_size) { //(Doc section: Convert to Arrow) // Write JSON records std::vector json_records = { @@ -513,15 +515,10 @@ int main(int argc, char** argv) { document.Parse(json_records[i % json_records.size()].c_str()); records.push_back(std::move(document)); } - // for (const std::string& json : json_records) { - // rapidjson::Document document; - // document.Parse(json.c_str()); - // records.push_back(std::move(document)); - // } + for (const rapidjson::Document& doc : records) { rapidjson::StringBuffer sb; rapidjson::Writer writer(sb); - // At batch_size >= 495, we segfault here: doc.Accept(writer); std::cout << sb.GetString() << std::endl; } @@ -538,16 +535,12 @@ int main(int argc, char** argv) { DocumentToArrowConverter to_arrow_converter(arrow::default_memory_pool()); // Convert records into a table - arrow::Result> table_result = - to_arrow_converter.ConvertToTable(records, schema); - std::shared_ptr table = std::move(table_result).ValueOrDie(); + ARROW_ASSIGN_OR_RAISE(std::shared_ptr table, + to_arrow_converter.ConvertToTable(records, schema)); // Print table std::cout << table->ToString() << std::endl; - auto res = table->ValidateFull(); - if (!res.ok()) { - std::cout << res.detail() << std::endl; - } + ARROW_RETURN_NOT_OK(table->ValidateFull()); //(Doc section: Convert to Arrow) //(Doc section: Convert to Rows) @@ -560,7 +553,7 @@ int main(int argc, char** argv) { // Print each row for (arrow::Result doc_result : document_iter) { - rapidjson::Document doc = std::move(doc_result).ValueOrDie(); + ARROW_ASSIGN_OR_RAISE(rapidjson::Document doc, std::move(doc_result)); assert(doc.HasMember("pk")); assert(doc["pk"].IsInt64()); @@ -587,4 +580,19 @@ int main(int argc, char** argv) { std::cout << sb.GetString() << std::endl; } //(Doc section: Convert to Rows) + + return arrow::Status::OK(); } + +int main(int argc, char** argv) { + int32_t num_rows = argc > 1 ? std::atoi(argv[1]) : 100; + int32_t batch_size = argc > 2 ? std::atoi(argv[2]) : 100; + + arrow::Status status = DoRowConversion(num_rows, batch_size); + + if (!status.ok()) { + std::cerr << "Error occurred: " << status.message() << std::endl; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} \ No newline at end of file From c4b7a7d61260e2906a54748554a67cff590282f4 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Tue, 14 Jun 2022 09:47:43 +0200 Subject: [PATCH 3/7] refactor: use RAPIDJSON_HAS_STDSTRING --- cpp/examples/arrow/rapidjson_row_converter.cc | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/cpp/examples/arrow/rapidjson_row_converter.cc b/cpp/examples/arrow/rapidjson_row_converter.cc index eec06d9892be..5346b6fa0569 100644 --- a/cpp/examples/arrow/rapidjson_row_converter.cc +++ b/cpp/examples/arrow/rapidjson_row_converter.cc @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +#define RAPIDJSON_HAS_STDSTRING 1 + #include #include #include @@ -85,7 +87,7 @@ class RowBatchBuilder { assert((int64_t)rows_.size() == array.length()); for (int64_t i = 0; i < array.length(); ++i) { if (!array.IsNull(i)) { - rapidjson::Value str_key(field_->name().c_str(), rows_[i].GetAllocator()); + rapidjson::Value str_key(field_->name(), rows_[i].GetAllocator()); rows_[i].AddMember(str_key, array.Value(i), rows_[i].GetAllocator()); } } @@ -96,7 +98,7 @@ class RowBatchBuilder { assert((int64_t)rows_.size() == array.length()); for (int64_t i = 0; i < array.length(); ++i) { if (!array.IsNull(i)) { - rapidjson::Value str_key(field_->name().c_str(), rows_[i].GetAllocator()); + rapidjson::Value str_key(field_->name(), rows_[i].GetAllocator()); arrow::util::string_view value_view = array.Value(i); rapidjson::Value value; value.SetString(value_view.data(), @@ -123,7 +125,7 @@ class RowBatchBuilder { for (int64_t i = 0; i < array.length(); ++i) { if (!array.IsNull(i)) { - rapidjson::Value str_key(field_->name().c_str(), rows_[i].GetAllocator()); + rapidjson::Value str_key(field_->name(), rows_[i].GetAllocator()); // Must copy value to new allocator rapidjson::Value row_val; row_val.CopyFrom(rows[i], rows_[i].GetAllocator()); @@ -159,12 +161,12 @@ class RowBatchBuilder { for (int64_t j = 0; j < array_len; ++j) { rapidjson::Value row_val; // Must copy value to new allocator - row_val.CopyFrom(rows[values_i][value_field_name.c_str()], allocator); + row_val.CopyFrom(rows[values_i][value_field_name], allocator); value.PushBack(row_val, allocator); ++values_i; } - rapidjson::Value str_key(field_->name().c_str(), allocator); + rapidjson::Value str_key(field_->name(), allocator); rows_[i].AddMember(str_key, value, allocator); } @@ -272,8 +274,8 @@ class DocValuesIterator { } else if (value->IsArray()) { // Empty array means we need to backtrack and go to next array or row value = NextArrayOrRow(value, &path_i, &arr_i); - } else if (value->HasMember(path[path_i].c_str())) { - value = &(*value)[path[path_i].c_str()]; + } else if (value->HasMember(path[path_i])) { + value = &(*value)[path[path_i]]; ++path_i; } else { return &kNullJsonSingleton; @@ -512,7 +514,7 @@ arrow::Status DoRowConversion(int32_t num_rows, int32_t batch_size) { records.reserve(num_rows); for (int32_t i = 0; i < num_rows; ++i) { rapidjson::Document document; - document.Parse(json_records[i % json_records.size()].c_str()); + document.Parse(json_records[i % json_records.size()]); records.push_back(std::move(document)); } From f2090efe55a2c2f07c41438cbd6439da93c6ab2d Mon Sep 17 00:00:00 2001 From: Will Jones Date: Tue, 21 Jun 2022 08:10:23 -0700 Subject: [PATCH 4/7] fix: Add trailing newline --- cpp/examples/arrow/rapidjson_row_converter.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/examples/arrow/rapidjson_row_converter.cc b/cpp/examples/arrow/rapidjson_row_converter.cc index 5346b6fa0569..33eb211095cd 100644 --- a/cpp/examples/arrow/rapidjson_row_converter.cc +++ b/cpp/examples/arrow/rapidjson_row_converter.cc @@ -597,4 +597,4 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } return EXIT_SUCCESS; -} \ No newline at end of file +} From 516566d2c5a2088bafb8866992e6f851f0d30a58 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Tue, 21 Jun 2022 10:33:57 -0700 Subject: [PATCH 5/7] feat: Move API changes into example --- cpp/examples/arrow/rapidjson_row_converter.cc | 36 +++- cpp/src/arrow/api.h | 1 - cpp/src/arrow/row_conversion.h | 192 ------------------ 3 files changed, 28 insertions(+), 201 deletions(-) delete mode 100644 cpp/src/arrow/row_conversion.h diff --git a/cpp/examples/arrow/rapidjson_row_converter.cc b/cpp/examples/arrow/rapidjson_row_converter.cc index 33eb211095cd..bdcecffd6195 100644 --- a/cpp/examples/arrow/rapidjson_row_converter.cc +++ b/cpp/examples/arrow/rapidjson_row_converter.cc @@ -178,10 +178,10 @@ class RowBatchBuilder { std::vector rows_; }; // RowBatchBuilder -class ArrowToDocumentConverter : public arrow::ToRowConverter { +class ArrowToDocumentConverter { public: arrow::Result> ConvertToVector( - std::shared_ptr batch) override { + std::shared_ptr batch) { RowBatchBuilder builder{batch->num_rows()}; for (int i = 0; i < batch->num_columns(); ++i) { @@ -191,6 +191,23 @@ class ArrowToDocumentConverter : public arrow::ToRowConverter ConvertToIterator( + std::shared_ptr table, size_t batch_size) { + auto batch_reader = std::make_shared(*table); + batch_reader->set_chunksize(batch_size); + + auto read_batch = [this](const std::shared_ptr& batch) + -> arrow::Result> { + ARROW_ASSIGN_OR_RAISE(auto rows, ConvertToVector(batch)); + return arrow::MakeVectorIterator(std::move(rows)); + }; + + auto nested_iter = arrow::MakeMaybeMapIterator( + read_batch, arrow::MakeIteratorFromReader(std::move(batch_reader))); + + return arrow::MakeFlattenIterator(std::move(nested_iter)); + } }; // ArrowToDocumentConverter /// \brief Iterator over rows values of a document for a given field @@ -286,7 +303,7 @@ class DocValuesIterator { return value; } - protected: + private: const std::vector& rows; std::vector path; int64_t array_levels; @@ -451,7 +468,7 @@ class JsonValueConverter { return arrow::Status::OK(); } - protected: + private: std::string field_name_; arrow::ArrayBuilder* builder_; const std::vector& rows_; @@ -473,13 +490,13 @@ class JsonValueConverter { } }; // JsonValueConverter -class DocumentToArrowConverter : public arrow::FromRowConverter { +class DocumentToArrowConverter { public: explicit DocumentToArrowConverter(arrow::MemoryPool* pool) : pool_(pool) {} arrow::Result> ConvertToRecordBatch( const std::vector& rows, - std::shared_ptr schema) override { + std::shared_ptr schema) { std::unique_ptr batch_builder; ARROW_ASSIGN_OR_RAISE(batch_builder, arrow::RecordBatchBuilder::Make(schema, pool_, rows.size())); @@ -498,7 +515,7 @@ class DocumentToArrowConverter : public arrow::FromRowConverter batch, + to_arrow_converter.ConvertToRecordBatch(records, schema)); + ARROW_ASSIGN_OR_RAISE(std::shared_ptr table, - to_arrow_converter.ConvertToTable(records, schema)); + arrow::Table::FromRecordBatches({batch})); // Print table std::cout << table->ToString() << std::endl; diff --git a/cpp/src/arrow/api.h b/cpp/src/arrow/api.h index d1e19340d196..1aabee35b10f 100644 --- a/cpp/src/arrow/api.h +++ b/cpp/src/arrow/api.h @@ -32,7 +32,6 @@ #include "arrow/pretty_print.h" // IYWU pragma: export #include "arrow/record_batch.h" // IYWU pragma: export #include "arrow/result.h" // IYWU pragma: export -#include "arrow/row_conversion.h" // IYWU pragma: export #include "arrow/status.h" // IYWU pragma: export #include "arrow/table.h" // IYWU pragma: export #include "arrow/table_builder.h" // IYWU pragma: export diff --git a/cpp/src/arrow/row_conversion.h b/cpp/src/arrow/row_conversion.h deleted file mode 100644 index 665a9f9530a7..000000000000 --- a/cpp/src/arrow/row_conversion.h +++ /dev/null @@ -1,192 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -#include "arrow/record_batch.h" -#include "arrow/table.h" -#include "arrow/util/iterator.h" - -namespace arrow { - -/// \brief Base class for Arrow to row converter. -/// -/// To use, specialize the conversion for a particular row type. -/// -/// \tparam RowType type that contains a single row -/// \tparam ContainerType optional alternative vector implementation -/// -/// The derived conversion functions take a batch_size parameter that determines -/// how many rows convert at once. This allows you to do the conversion in smaller -/// batches. -template class ContainerType = std::vector> -class ToRowConverter { - public: - /// \brief Convert a record batch into a vector of rows. - /// - /// Implement this method in specialized classes to derive all other methods. - /// - /// \param batch Record batch to convert - /// \return A vector of rows containing all data in batch - virtual Result> ConvertToVector( - std::shared_ptr batch) = 0; - - /// \brief Convert a record batch into a vector of rows. - /// - /// \param batch Record batch to convert - /// \param batch_size Number of rows to convert at once - /// \return A vector of rows containing all data in batch - Result> ConvertToVector(std::shared_ptr batch, - size_t batch_size) { - ARROW_ASSIGN_OR_RAISE(std::shared_ptr
table, - Table::FromRecordBatches({batch})); - return ConvertToVector(table, batch_size); - } - - /// \brief Convert an Arrow table to a vector of rows. - /// - /// \param table Table to convert - /// \param batch_size Number of rows to convert at once - /// \return A vector of rows containing all data in table - Result> ConvertToVector(std::shared_ptr
table, - size_t batch_size) { - ContainerType out; - - TableBatchReader batch_reader(*table); - batch_reader.set_chunksize(batch_size); - for (auto batch : batch_reader) { - ARROW_ASSIGN_OR_RAISE(auto converted, ConvertToVector(batch)); - out.extend(converted); - } - - return out; - } - - /// \brief Convert a record batch stream to a iterator of rows. - /// - /// \param reader a record batch reader - /// \return A iterator of rows yielding each row produced by reader - Iterator ConvertToIterator(std::shared_ptr reader) { - auto read_batch = - [this](const std::shared_ptr& batch) -> Result> { - ARROW_ASSIGN_OR_RAISE(auto rows, ConvertToVector(batch)); - return MakeVectorIterator(std::move(rows)); - }; - - auto nested_iter = - MakeMaybeMapIterator(read_batch, MakeIteratorFromReader(std::move(reader))); - - return MakeFlattenIterator(std::move(nested_iter)); - } - - /// \brief Convert an Arrow table to a iterator of rows. - /// - /// \param table Table to convert - /// \param batch_size Number of rows to convert at once - /// \return A iterator of rows yielding each row in table - Iterator ConvertToIterator(std::shared_ptr
table, size_t batch_size) { - auto batch_reader = std::make_shared(*table); - batch_reader->set_chunksize(batch_size); - - return ConvertToIterator(batch_reader); - } - - /// \brief Convert an Arrow record batch to an iterator of rows. - /// - /// \param batch Record batch to convert - /// \param batch_size Number of rows to convert at once - /// \return A iterator of rows yielding each row in batch - Iterator ConvertToIterator(std::shared_ptr batch, - size_t batch_size) { - ARROW_ASSIGN_OR_RAISE(std::shared_ptr
table, - Table::FromRecordBatches({batch})); - return ConvertToIterator(table, batch_size); - } -}; - -/// \brief Base class for Row to Arrow conversions. -/// -/// To use, specialize the conversion for a particular row type. -/// -/// \tparam RowType type that contains a single row -/// \tparam ContainerType optional alternative vector implementation -template class ContainerType = std::vector> -class FromRowConverter { - public: - /// \brief Convert a vector of rows to a record batch. - /// - /// Implement this method to enable all other methods. - /// - /// \param rows Vector of rows to convert - /// \param schema Schema of record batch to convert to - /// \return Arrow result with record batch containing all rows - virtual Result> ConvertToRecordBatch( - const ContainerType& rows, std::shared_ptr schema) = 0; - - /// \brief Convert a vector of rows to an Arrow table - /// - /// \param rows Vector of rows to convert - /// \param schema Schema of record batch to convert to - /// \return Arrow result with table containing all rows - Result> ConvertToTable(const ContainerType& rows, - std::shared_ptr schema) { - ARROW_ASSIGN_OR_RAISE(std::shared_ptr batch, - ConvertToRecordBatch(rows, schema)); - return Table::FromRecordBatches({batch}); - } - - /// \brief Convert a vector of rows to a record batch reader. - /// - /// \param row_iter Iterator of rows - /// \param schema Schema of record batches to convert to - /// \param batch_size Max size of record batches to produce in reader - /// \return Arrow result with record batch reader containing all rows - Result> ConvertToReader( - Iterator row_iter, std::shared_ptr schema, size_t batch_size) { - auto get_next_batch = [row_iter, batch_size, schema, - this]() -> Result> { - ContainerType rows; - RowType row; - rows.reserve(batch_size); - - while (true) { - auto row_res = row_iter->Next(); - if (row_res.ok()) { - row = std::move(row).MoveValueUnsafe(); - } - if (row == NULLPTR) { - break; - } - rows.emplace_back(row); - - if (rows.size() == batch_size) { - break; - } - } - - if (rows.size() > 0) { - return ConvertToRecordBatch(rows, schema); - } else { - return IterationTraits::End(); - } - }; - - auto batch_iter = MakeFunctionIterator(get_next_batch); - - return SimpleRecordBatchReader(batch_iter, schema); - } -}; - -} // namespace arrow From c32ef476dad2f0d7fd440d82e08c2f697038aa27 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Tue, 21 Jun 2022 14:23:10 -0700 Subject: [PATCH 6/7] feat: refactor narrative docs --- cpp/examples/arrow/rapidjson_row_converter.cc | 64 +++++------ docs/source/cpp/api/utilities.rst | 9 -- docs/source/cpp/datatypes.rst | 2 + .../cpp/examples/row_columnar_conversion.rst | 108 ++++++++++-------- 4 files changed, 95 insertions(+), 88 deletions(-) diff --git a/cpp/examples/arrow/rapidjson_row_converter.cc b/cpp/examples/arrow/rapidjson_row_converter.cc index bdcecffd6195..348b2587fee3 100644 --- a/cpp/examples/arrow/rapidjson_row_converter.cc +++ b/cpp/examples/arrow/rapidjson_row_converter.cc @@ -42,12 +42,10 @@ // As an example, this conversion is between Arrow and rapidjson::Documents. // // We use the following helpers and patterns here: -// * arrow::ToRowConverter and arrow::FromRowConverter, which provide additional -// conversion methods given a basic converter // * arrow::VisitArrayInline and arrow::VisitTypeInline for implementing a visitor // pattern with Arrow to handle different array types // * arrow::enable_if_primitive_ctype to create a template method that handles -// * conversion for Arrow types that have corresponding C types (bool, integer, +// conversion for Arrow types that have corresponding C types (bool, integer, // float). const rapidjson::Value kNullJsonSingleton = rapidjson::Value(); @@ -180,6 +178,7 @@ class RowBatchBuilder { class ArrowToDocumentConverter { public: + /// Convert a single batch of Arrow data into Documents arrow::Result> ConvertToVector( std::shared_ptr batch) { RowBatchBuilder builder{batch->num_rows()}; @@ -192,8 +191,11 @@ class ArrowToDocumentConverter { return std::move(builder).Rows(); } + /// Convert an Arrow table into an iterator of Documents arrow::Iterator ConvertToIterator( std::shared_ptr table, size_t batch_size) { + // Use TableBatchReader to divide table into smaller batches. The batches + // created are zero-copy slices with *at most* `batch_size` rows. auto batch_reader = std::make_shared(*table); batch_reader->set_chunksize(batch_size); @@ -490,34 +492,33 @@ class JsonValueConverter { } }; // JsonValueConverter -class DocumentToArrowConverter { - public: - explicit DocumentToArrowConverter(arrow::MemoryPool* pool) : pool_(pool) {} - - arrow::Result> ConvertToRecordBatch( - const std::vector& rows, - std::shared_ptr schema) { - std::unique_ptr batch_builder; - ARROW_ASSIGN_OR_RAISE(batch_builder, - arrow::RecordBatchBuilder::Make(schema, pool_, rows.size())); - - JsonValueConverter converter(rows); - for (int i = 0; i < batch_builder->num_fields(); ++i) { - std::shared_ptr field = schema->field(i); - arrow::ArrayBuilder* builder = batch_builder->GetField(i); - ARROW_RETURN_NOT_OK(converter.Convert(*field.get(), builder)); - } - - std::shared_ptr batch; - ARROW_ASSIGN_OR_RAISE(batch, batch_builder->Flush()); - - DCHECK_OK(batch->ValidateFull()); - return batch; +arrow::Result> ConvertToRecordBatch( + const std::vector& rows, std::shared_ptr schema) { + // RecordBatchBuilder will create array builders for us for each field in our + // schema. By passing the number of output rows (`rows.size()`) we can + // pre-allocate the correct size of arrays, except of course in the case of + // string, byte, and list arrays, which have dynamic lengths. + std::unique_ptr batch_builder; + ARROW_ASSIGN_OR_RAISE( + batch_builder, + arrow::RecordBatchBuilder::Make(schema, arrow::default_memory_pool(), rows.size())); + + // Inner converter will take rows and be responsible for appending values + // to provided array builders. + JsonValueConverter converter(rows); + for (int i = 0; i < batch_builder->num_fields(); ++i) { + std::shared_ptr field = schema->field(i); + arrow::ArrayBuilder* builder = batch_builder->GetField(i); + ARROW_RETURN_NOT_OK(converter.Convert(*field.get(), builder)); } - private: - arrow::MemoryPool* pool_; -}; // DocumentToArrowConverter + std::shared_ptr batch; + ARROW_ASSIGN_OR_RAISE(batch, batch_builder->Flush()); + + // Use RecordBatch::ValidateFull() to make sure arrays were correctly constructed. + DCHECK_OK(batch->ValidateFull()); + return batch; +} // ConvertToRecordBatch arrow::Status DoRowConversion(int32_t num_rows, int32_t batch_size) { //(Doc section: Convert to Arrow) @@ -550,12 +551,9 @@ arrow::Status DoRowConversion(int32_t num_rows, int32_t batch_size) { arrow::field("data", arrow::struct_({arrow::field("deleted", arrow::boolean()), arrow::field("metrics", tags_schema)}))}); - // Create converter - DocumentToArrowConverter to_arrow_converter(arrow::default_memory_pool()); - // Convert records into a table ARROW_ASSIGN_OR_RAISE(std::shared_ptr batch, - to_arrow_converter.ConvertToRecordBatch(records, schema)); + ConvertToRecordBatch(records, schema)); ARROW_ASSIGN_OR_RAISE(std::shared_ptr table, arrow::Table::FromRecordBatches({batch})); diff --git a/docs/source/cpp/api/utilities.rst b/docs/source/cpp/api/utilities.rst index fab346753b55..5ce3d7d1a4e4 100644 --- a/docs/source/cpp/api/utilities.rst +++ b/docs/source/cpp/api/utilities.rst @@ -57,15 +57,6 @@ Compression .. doxygenclass:: arrow::util::Decompressor :members: -Row Conversion -============== - -.. doxygenclass:: arrow::ToRowConverter - :members: - -.. doxygenclass:: arrow::FromRowConverter - :members: - Visitors ======== diff --git a/docs/source/cpp/datatypes.rst b/docs/source/cpp/datatypes.rst index 5428fbd008cf..2a31ac65a939 100644 --- a/docs/source/cpp/datatypes.rst +++ b/docs/source/cpp/datatypes.rst @@ -151,6 +151,8 @@ function for any numeric (integer or float) array: See :ref:`type-predicates-api` for a list of these. +.. _cpp-visitor-pattern: + Visitor Pattern --------------- diff --git a/docs/source/cpp/examples/row_columnar_conversion.rst b/docs/source/cpp/examples/row_columnar_conversion.rst index 64645814f392..d3c0a98559a7 100644 --- a/docs/source/cpp/examples/row_columnar_conversion.rst +++ b/docs/source/cpp/examples/row_columnar_conversion.rst @@ -33,31 +33,62 @@ instance, and then converts it back to the original array of structs. Dynamic Schemas --------------- -For schemas not known at compile time, implement an :class:`arrow::ToRowConverter` -or an :class:`arrow::FromRowConverter`. -The following example shows how to implement conversion between `rapidjson::Document` -and Arrow objects. You can read the full example at +In many cases, we need to convert to and from row data that does not have a +schema known at compile time. To help implement these conversions, this library +provides several utilities: + +* :class:`arrow::RecordBatchBuilder`: creates and manages array builders for + a full record batch. +* :func:`arrow::VisitTypeInline`: dispatch to functions specialized for the given + array type. +* :ref:`type-traits` (such as ``arrow::enable_if_primitive_ctype``): narrow template + functions to specific Arrow types, useful in conjunction with + the :ref:`cpp-visitor-pattern`. +* :class:`arrow::TableBatchReader`: read a table in a batch at a time, with each + batch being a zero-copy slice. + +The following example shows how to implement conversion between ``rapidjson::Document`` +and Arrow objects. You can read the full code example at https://github.com/apache/arrow/blob/master/cpp/examples/arrow/rapidjson_row_converter.cc Writing conversions to Arrow ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To handle conversions into Arrow, define an :class:`arrow::FromRowConverter` specialized -for your row data structure. In this example, we use :class:`arrow::RecordBatchBuilder`, -which conveniently creates builders for each field in the schemas. Another class ``JsonValueConverter``, -which is introduced next, will handle getting the values from the rows and appending -to the appropriate builder, given a field. +To convert rows to Arrow record batches, we'll setup Array builders for all the columns +and then for each field iterate through row values and append to the builders. +We assume that we already know the target schema, which may have +been provided by another system or was inferred in another function. Inferring +the schema *during* conversion is a challenging proposition; many systems will +check the first N rows to infer a schema if there is none already available. + +At the top level, we define a function ``ConvertToRecordBatch``: .. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc :language: cpp - :start-at: class DocumentToArrowConverter - :end-at: }; // DocumentToArrowConverter + :start-at: arrow::Result> ConvertToRecordBatch( + :end-at: } // ConvertToRecordBatch :linenos: :lineno-match: -The ``JsonValueConverter`` implements ``Visit()`` methods for each relevant array -type that append to the current builder. Then the ``Convert()`` method simply -sets the current field, builder, and then calls :func:`arrow::VisitTypeInline`. +First we use :class:`arrow::RecordBatchBuilder`, which conveniently creates builders +for each field in the schema. Then we iterate over the fields of the schema, get +the builder, and call ``Convert()`` on our ``JsonValueConverter`` (to be discussed +next). At the end, we call ``batch->ValidateFull()``, which checks the integrity +of our arrays to make sure the conversion was performed correctly, which is useful +for debugging new conversion implementations. + +One level down, the ``JsonValueConverter`` is responsible for appending row values +for the provided field to a provided array builder. In order to specialize logic +for each data type, it implements ``Visit`` methods and calls :func:`arrow::VisitTypeInline`. +(See more about type visitors in :ref:`cpp-visitor-pattern`.) + +At the end of that class is the private method ``FieldValues()``, which returns +an iterator of the column values for the current field across the rows. In +row-based structures that are flat (such as a vector of values) this may be +trivial to implement. But if the schema is nested, as in the case of JSON documents, +a special iterator is needed to navigate the levels of nesting. See the +`full example `_ +for the implementation details of ``DocValuesIterator``. .. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc :language: cpp @@ -66,26 +97,21 @@ sets the current field, builder, and then calls :func:`arrow::VisitTypeInline`. :linenos: :lineno-match: -With those defined, we can convert rows into a table using an instance of the -converter: - -.. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc - :language: cpp - :start-after: (Doc section: Convert to Arrow) - :end-before: (Doc section: Convert to Arrow) - :linenos: - :lineno-match: - - Writing conversions from Arrow ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To convert into rows *from* Arrow, define an :class:`arrow::ToRowConverter` specialized -for your row data structure. In our example, we define a ``RowBatchBuilder`` class -to handle converting each column and assigning field values to each row. Because -the builder implements ``Visit()`` methods for each Arrow array type, it can be -passed to :func:`arrow::VisitArrayInline` to dispatch to the appropriate logic for -each array type. +To convert into rows *from* Arrow record batches, we'll process the table in +smaller batches, visiting each field of the batch and filling the output rows +column-by-column. + +At the top-level, we define ``ArrowToDocumentConverter`` that provides the API +for converting Arrow batches and tables to rows. In many cases, it's more optimal +to perform conversions to rows in smaller batches, rather than doing the entire +table at once. So we define one ``ConvertToVector`` method to convert a single +batch, then in the other conversion method we use :class:`arrow::TableBatchReader` +to iterate over slices of a table. This returns Arrow's iterator type +(:class:`arrow::Iterator`) so rows could then be processed either one-at-a-time +or be collected into a container. .. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc :language: cpp @@ -94,11 +120,11 @@ each array type. :linenos: :lineno-match: -The ``RowBatchBuilder`` implements ``Visit()`` methods, but to save on code is -able to write a template method for array types that have primitive C equivalents -(booleans, integers, and floats). It uses the ``arrow::enable_if_primitive_ctype`` -to narrow the template to only apply to relevant array types. See :ref:`type-traits` -for other type predicates. +One level down, the output rows are filled in by ``RowBatchBuilder``. +The ``RowBatchBuilder`` implements ``Visit()`` methods, but to save on code we +write a template method for array types that have primitive C equivalents +(booleans, integers, and floats) using ``arrow::enable_if_primitive_ctype``. +See :ref:`type-traits` for other type predicates. .. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc :language: cpp @@ -106,13 +132,3 @@ for other type predicates. :end-at: }; // RowBatchBuilder :linenos: :lineno-match: - -Finally, we can use the converter iterate over rows in the batch as rapidjson -Documents: - -.. literalinclude:: ../../../../cpp/examples/arrow/rapidjson_row_converter.cc - :language: cpp - :start-after: (Doc section: Convert to Rows) - :end-before: (Doc section: Convert to Rows) - :linenos: - :lineno-match: \ No newline at end of file From d84ef7f28237713c6ad6d80061ecc89771b4d2d3 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Wed, 22 Jun 2022 17:55:26 -0700 Subject: [PATCH 7/7] fix: use static_cast instead of C-style cast --- cpp/examples/arrow/rapidjson_row_converter.cc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cpp/examples/arrow/rapidjson_row_converter.cc b/cpp/examples/arrow/rapidjson_row_converter.cc index 348b2587fee3..defa6de4610b 100644 --- a/cpp/examples/arrow/rapidjson_row_converter.cc +++ b/cpp/examples/arrow/rapidjson_row_converter.cc @@ -82,7 +82,7 @@ class RowBatchBuilder { template arrow::enable_if_primitive_ctype Visit( const ArrayType& array) { - assert((int64_t)rows_.size() == array.length()); + assert(static_cast(rows_.size()) == array.length()); for (int64_t i = 0; i < array.length(); ++i) { if (!array.IsNull(i)) { rapidjson::Value str_key(field_->name(), rows_[i].GetAllocator()); @@ -93,7 +93,7 @@ class RowBatchBuilder { } arrow::Status Visit(const arrow::StringArray& array) { - assert((int64_t)rows_.size() == array.length()); + assert(static_cast(rows_.size()) == array.length()); for (int64_t i = 0; i < array.length(); ++i) { if (!array.IsNull(i)) { rapidjson::Value str_key(field_->name(), rows_[i].GetAllocator()); @@ -111,7 +111,7 @@ class RowBatchBuilder { arrow::Status Visit(const arrow::StructArray& array) { const arrow::StructType* type = array.struct_type(); - assert((int64_t)rows_.size() == array.length()); + assert(static_cast(rows_.size()) == array.length()); RowBatchBuilder child_builder(rows_.size()); for (int i = 0; i < type->num_fields(); ++i) { @@ -134,7 +134,7 @@ class RowBatchBuilder { } arrow::Status Visit(const arrow::ListArray& array) { - assert((int64_t)rows_.size() == array.length()); + assert(static_cast(rows_.size()) == array.length()); // First create rows from values std::shared_ptr values = array.values(); RowBatchBuilder child_builder(values->length());