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..defa6de4610b --- /dev/null +++ b/cpp/examples/arrow/rapidjson_row_converter.cc @@ -0,0 +1,618 @@ +// 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. + +#define RAPIDJSON_HAS_STDSTRING 1 + +#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::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). + +const 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(const arrow::Field* field) { field_ = 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) { + 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()); + rows_[i].AddMember(str_key, array.Value(i), rows_[i].GetAllocator()); + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::StringArray& array) { + 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()); + arrow::util::string_view 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(); + + assert(static_cast(rows_.size()) == array.length()); + + RowBatchBuilder child_builder(rows_.size()); + for (int i = 0; i < type->num_fields(); ++i) { + 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(); + + for (int64_t i = 0; i < array.length(); ++i) { + if (!array.IsNull(i)) { + 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()); + rows_[i].AddMember(str_key, row_val, rows_[i].GetAllocator()); + } + } + return arrow::Status::OK(); + } + + arrow::Status Visit(const arrow::ListArray& array) { + assert(static_cast(rows_.size()) == array.length()); + // First create rows from values + std::shared_ptr values = array.values(); + RowBatchBuilder child_builder(values->length()); + 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)); + + std::vector rows = std::move(child_builder).Rows(); + + 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); + + 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], allocator); + value.PushBack(row_val, allocator); + ++values_i; + } + + rapidjson::Value str_key(field_->name(), allocator); + rows_[i].AddMember(str_key, value, allocator); + } + + return arrow::Status::OK(); + } + + private: + const arrow::Field* field_; + std::vector rows_; +}; // 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()}; + + for (int i = 0; i < batch->num_columns(); ++i) { + builder.SetField(batch->schema()->field(i).get()); + ARROW_RETURN_NOT_OK(arrow::VisitArrayInline(*batch->column(i).get(), &builder)); + } + + 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); + + 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 +/// +/// 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])) { + value = &(*value)[path[path_i]]; + ++path_i; + } else { + return &kNullJsonSingleton; + } + } + + // Return value + return value; + } + + private: + 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 json value to Arrow 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(); + } + + private: + 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 + +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)); + } + + 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) + // 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()]); + records.push_back(std::move(document)); + } + + for (const rapidjson::Document& doc : records) { + rapidjson::StringBuffer sb; + rapidjson::Writer writer(sb); + 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)}))}); + + // Convert records into a table + ARROW_ASSIGN_OR_RAISE(std::shared_ptr batch, + ConvertToRecordBatch(records, schema)); + + ARROW_ASSIGN_OR_RAISE(std::shared_ptr table, + arrow::Table::FromRecordBatches({batch})); + + // Print table + std::cout << table->ToString() << std::endl; + ARROW_RETURN_NOT_OK(table->ValidateFull()); + //(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) { + ARROW_ASSIGN_OR_RAISE(rapidjson::Document doc, std::move(doc_result)); + + 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) + + 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; +} 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/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 3f45864c2283..d3c0a98559a7 100644 --- a/docs/source/cpp/examples/row_columnar_conversion.rst +++ b/docs/source/cpp/examples/row_columnar_conversion.rst @@ -21,7 +21,114 @@ 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 +--------------- + +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 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: arrow::Result> ConvertToRecordBatch( + :end-at: } // ConvertToRecordBatch + :linenos: + :lineno-match: + +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 + :start-at: class JsonValueConverter + :end-at: }; // JsonValueConverter + :linenos: + :lineno-match: + +Writing conversions from Arrow +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +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 + :start-at: class ArrowToDocumentConverter + :end-at: }; // ArrowToDocumentConverter + :linenos: + :lineno-match: + +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 + :start-at: class RowBatchBuilder + :end-at: }; // RowBatchBuilder + :linenos: + :lineno-match: