You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by GitBox <gi...@apache.org> on 2020/11/05 19:01:31 UTC
[GitHub] [iceberg] TGooch44 opened a new pull request #1727: [python] Adding parquet package and the classes for reading parquet
TGooch44 opened a new pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727
This adds a parquet reader class that leverages pyarrow.datasets to read parquet files and apply row-level filters. Additionally, there are some helper classes to convert between arrow schemas and iceberg schemas, so that we can apply any necessary schema evolution.
cc @danielcweeks @rymurr
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r524496049
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
currently, the way that I do it is to downloaded the needed files in parallel using an internal lib, then do a single threaded read of the local files into an arrow table then combine the per file tables using [concat_tables](https://arrow.apache.org/docs/python/generated/pyarrow.concat_tables.html). I can set-up some benchmarks to comapre the two approaches, but it seems like from the answer on the user list that it's not currently possible if there is schema evolution across the files.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rdblue commented on pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rdblue commented on pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#issuecomment-739087770
Thanks @TGooch44 for working on this! And thanks to @rymurr for reviewing!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r535782412
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,264 @@
+# 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.
+
+
+from collections import namedtuple
+from datetime import datetime
+import decimal
+import logging
+import typing
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.filesystem import FileSystem, LocalFileSystem, S3FileSystem
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import FileSystemNotFound, InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: typing.Dict[TypeID,
+ typing.Callable[[NestedField], typing.Tuple[pa.Field, typing.Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+FS_MAP: typing.Dict[typing.Type[FileSystem], typing.Type[fs.FileSystem]] = {LocalFileSystem: fs.LocalFileSystem}
+
+try:
+ FS_MAP[S3FileSystem] = fs.S3FileSystem
+except ImportError:
+ _logger.warning("S3 Filesystem not available to arrow")
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: typing.Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+ self._batches = None
+ self._row_tuple = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> typing.Union[pd.Series, pd.DataFrame]:
Review comment:
It's removed in the latest commit, and the to_arrow_table method has been renamed to `read()`. Yes, there should be a something between `TableScan` and `ParquetReader` that combines the results of all the `ScanTask`s.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r535781402
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,264 @@
+# 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.
+
+
+from collections import namedtuple
+from datetime import datetime
+import decimal
+import logging
+import typing
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.filesystem import FileSystem, LocalFileSystem, S3FileSystem
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import FileSystemNotFound, InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: typing.Dict[TypeID,
+ typing.Callable[[NestedField], typing.Tuple[pa.Field, typing.Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+FS_MAP: typing.Dict[typing.Type[FileSystem], typing.Type[fs.FileSystem]] = {LocalFileSystem: fs.LocalFileSystem}
+
+try:
+ FS_MAP[S3FileSystem] = fs.S3FileSystem
Review comment:
what happens is the import succeeds for `fs`, but when you actually do fs.S3FileSystem it throws the import error. It might be clearer to do it all in the `try...except` though...let me just change that
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r520708351
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
I agree this is the biggest problem with this implementation. I can start a discussion on the arrow dev list and see if there are any ideas here.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rdblue merged pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rdblue merged pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rymurr commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rymurr commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r526112834
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
I would be curious to see perf impact if we just made 10 copies of a single parquet file and read it in one go vs sequentially w/ a concat at the end.
Its too bad that the support for this use case in Arrow seems to be a future enhancement. Should be relatively easy to take it up once Arrow supports it.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rymurr commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rymurr commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r528780623
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,264 @@
+# 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.
+
+
+from collections import namedtuple
+from datetime import datetime
+import decimal
+import logging
+import typing
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.filesystem import FileSystem, LocalFileSystem, S3FileSystem
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import FileSystemNotFound, InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: typing.Dict[TypeID,
+ typing.Callable[[NestedField], typing.Tuple[pa.Field, typing.Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+FS_MAP: typing.Dict[typing.Type[FileSystem], typing.Type[fs.FileSystem]] = {LocalFileSystem: fs.LocalFileSystem}
+
+try:
+ FS_MAP[S3FileSystem] = fs.S3FileSystem
Review comment:
I think the import for the S3 filesystem should be down here right?
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,264 @@
+# 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.
+
+
+from collections import namedtuple
+from datetime import datetime
+import decimal
+import logging
+import typing
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.filesystem import FileSystem, LocalFileSystem, S3FileSystem
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import FileSystemNotFound, InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: typing.Dict[TypeID,
+ typing.Callable[[NestedField], typing.Tuple[pa.Field, typing.Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+FS_MAP: typing.Dict[typing.Type[FileSystem], typing.Type[fs.FileSystem]] = {LocalFileSystem: fs.LocalFileSystem}
+
+try:
+ FS_MAP[S3FileSystem] = fs.S3FileSystem
+except ImportError:
+ _logger.warning("S3 Filesystem not available to arrow")
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: typing.Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+ self._batches = None
+ self._row_tuple = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> typing.Union[pd.Series, pd.DataFrame]:
Review comment:
were you still going to remove the pandas and iterator stuff? I was kinda thinking that we would have a class 1 level higher that would read across all tables and pandas would be accessed there
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r520742733
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
Here is the thread on the user list:
https://lists.apache.org/thread.html/r7d82d38d1e9a1b9bc99d64a0779de8886cf0bf7216d64d576a6c18e9%40%3Cuser.arrow.apache.org%3E
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rymurr commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rymurr commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r526114080
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
+ schema=self._arrow_file.schema_arrow,
+ format=ds.ParquetFileFormat(),
+ filesystem=fs.LocalFileSystem())
+
+ arrow_table = arrow_dataset.to_table(columns=cols_to_read, filter=self._filter)
+
+ # process schema evolution if needed
+ with profile("schema_evol_proc", self._stats):
+ processed_tbl = self.migrate_schema(arrow_table)
+ for i, field in self.get_missing_fields():
+ dtype_func = DTYPE_MAP.get(field.type.type_id)
+ if dtype_func is None:
+ raise RuntimeError("Unable to create null column for type %s" % field.type.type_id)
+
+ dtype = dtype_func(field)
+ processed_tbl = (processed_tbl.add_column(i,
+ pa.field(field.name, dtype[0], True, None),
+ ParquetReader.create_null_column(processed_tbl[0],
+ dtype)))
+ self._table = processed_tbl
+ self.materialized_table = True
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ if self.curr_iterator is None:
+ if not self.materialized_table:
Review comment:
I agree. I think keeping this at the arrow level is best and having a layer above which concats the arrow tables together before handing back to the client.
This of course could lead to memory difficulties so a future enhancement might be to do some sort of chunked reads (moving to arrow's datasets is preferable to writing our own tho :-)
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rymurr commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rymurr commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r519833436
##########
File path: python/iceberg/parquet/dataset_utils.py
##########
@@ -0,0 +1,177 @@
+# 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.
+
+
+from iceberg.api.expressions import Expression, Operation, Predicate
+import pyarrow.dataset as ds
+
+
+def get_dataset_filter(expr: Expression, expected_to_file_map: dict) -> ds.Expression:
Review comment:
just curious why we have `get_dataset_filter` and `get_expr`. Maybe it will become clear as I review the rest but from here it seems redundnat
##########
File path: python/iceberg/core/util/profile.py
##########
@@ -0,0 +1,36 @@
+# 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.
+
+
+from contextlib import contextmanager
+import logging
+import time
+
+_logger = logging.getLogger(__name__)
+
+
+@contextmanager
+def profile(label, stats_dict=None):
+ if stats_dict is None:
+ print('PROFILE: %s starting' % label)
Review comment:
probably want this to be _logger.debug
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
Its a shame that we can't do this for a batch of files. Seems like a common pattern that pyarrow should be able to handle. Have you asked on user@arrow.apache.org if there is a plan to support this?
Do you have a sense of the performance hit of reading files individually as opposed to in one batch? I am worried it could be significant.
Finally, what is the path for reading/iterating multi-file iceberg tables? Do we read 1 parrquet file at a time or all at once or all at once as a pandas df? One of the key features of Datasets (for me) was being able to control memory when doing large reads.
##########
File path: python/setup.py
##########
@@ -38,7 +37,7 @@
'requests',
'retrying',
'pandas',
- 'pyarrow'
+ 'pyarrow>=0.17.0'
Review comment:
why not pyarrow 2.0.0?
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
+ schema=self._arrow_file.schema_arrow,
+ format=ds.ParquetFileFormat(),
+ filesystem=fs.LocalFileSystem())
Review comment:
Is `LocalFileSystem` correct here? It caught my eye and wasn't sure how we would read eg from S3 or hadoop
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
+ schema=self._arrow_file.schema_arrow,
+ format=ds.ParquetFileFormat(),
+ filesystem=fs.LocalFileSystem())
+
+ arrow_table = arrow_dataset.to_table(columns=cols_to_read, filter=self._filter)
+
+ # process schema evolution if needed
+ with profile("schema_evol_proc", self._stats):
+ processed_tbl = self.migrate_schema(arrow_table)
+ for i, field in self.get_missing_fields():
+ dtype_func = DTYPE_MAP.get(field.type.type_id)
+ if dtype_func is None:
+ raise RuntimeError("Unable to create null column for type %s" % field.type.type_id)
+
+ dtype = dtype_func(field)
+ processed_tbl = (processed_tbl.add_column(i,
+ pa.field(field.name, dtype[0], True, None),
+ ParquetReader.create_null_column(processed_tbl[0],
+ dtype)))
+ self._table = processed_tbl
+ self.materialized_table = True
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ if self.curr_iterator is None:
+ if not self.materialized_table:
Review comment:
Is there any way to do this w/o first going to pandas? Pandas is the most expensive part of this operation and if we could avoid it (say get tuples direct from pyarrow) performance would significantly improve
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#issuecomment-724218264
@rymurr Let me know what you think on this. I wasn't able to get a version working with multiple files being passed in because (at least I believe) we aren't able to know the schema for a each file in a set ahead of time, and the arrow Datasets read didn't like it when there were multiple schemas in the set. Not sure if there is some way to pass in a list of files, and get back a list of tables instead of trying to conform all the files to a single schema.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r520708241
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
+ schema=self._arrow_file.schema_arrow,
+ format=ds.ParquetFileFormat(),
+ filesystem=fs.LocalFileSystem())
Review comment:
Let me change this to map from the filesystem type of the input files. We always bring files local before reading because we have some very fast libs for sucking down s3 data. Much better than throughput than reading via boto, alhough I haven't benchmarked against what pyarrow is doing. We typically do not see a lot of row-group elimination. so the mileage on doing partial s3 reads is not that significant. This may not be the general-case though, so it should probably pick a filesystem based on the input file.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rymurr commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rymurr commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r528779292
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
Yeah, I will do another quick pass now but I think its ready to go
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rymurr commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rymurr commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r526952557
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
Ok, thats good. I just wanted to get a broad idea to ensure we understand where the python reader will work/fail. So the bottleneck is really comign down to memory then as there is currently no way to page or dynamically load these per-file arrow tables
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r526246133
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
I just did some initial testing and I'm not seeing a significant difference between passing a list of files to Datasets vs. using a python threadpool per file and then concating the resulting tables. Let me come up with some more test cases and see if there are some where the arrow threading does better. Using some internal data I read about ~90M rows in about 9 secs both ways. Test was run on a r4.16xlarge instance with EBS storage. I'll try and setup something reproducible for you to try out
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rymurr commented on pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rymurr commented on pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#issuecomment-724232913
Hey @TGooch44 apologies, I'm about 3/4 done reviewing. Should have something tomorrow morning.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r524493239
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
+ schema=self._arrow_file.schema_arrow,
+ format=ds.ParquetFileFormat(),
+ filesystem=fs.LocalFileSystem())
+
+ arrow_table = arrow_dataset.to_table(columns=cols_to_read, filter=self._filter)
+
+ # process schema evolution if needed
+ with profile("schema_evol_proc", self._stats):
+ processed_tbl = self.migrate_schema(arrow_table)
+ for i, field in self.get_missing_fields():
+ dtype_func = DTYPE_MAP.get(field.type.type_id)
+ if dtype_func is None:
+ raise RuntimeError("Unable to create null column for type %s" % field.type.type_id)
+
+ dtype = dtype_func(field)
+ processed_tbl = (processed_tbl.add_column(i,
+ pa.field(field.name, dtype[0], True, None),
+ ParquetReader.create_null_column(processed_tbl[0],
+ dtype)))
+ self._table = processed_tbl
+ self.materialized_table = True
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ if self.curr_iterator is None:
+ if not self.materialized_table:
Review comment:
@rymurr I updated this, although I'm wondering if it makes more sense to remove this iterator logic and to_pandas from the parquet reader and move it to a higher level class because above the parquet reader, we will need something that combines all the various file scans into a single arrow table/pandas df.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r528777505
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
yeah just wondering if this is primarily IO bound, so the diff between C threads and python threads is negligible. Maybe in cases where there is more cpu intense work going on this won't track so closely. In any case, I think this is an ok design until we can get better native support for schema normalization in arrow itself. What do you think? Any other outstanding items before this is ready for merge?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r520697445
##########
File path: python/iceberg/parquet/dataset_utils.py
##########
@@ -0,0 +1,177 @@
+# 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.
+
+
+from iceberg.api.expressions import Expression, Operation, Predicate
+import pyarrow.dataset as ds
+
+
+def get_dataset_filter(expr: Expression, expected_to_file_map: dict) -> ds.Expression:
Review comment:
you're right this is redundant. It's an artifact of a previous implementation that I should have cleaned up. I'll update.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r528431433
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
Check this out and let me know what you think:
https://www.kaggle.com/tedgooch/notebook2b16380982
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#issuecomment-738510292
> 1 or 2 minor things left. Also wondering how we can help the user to not load a 1TB iceberg table into a pandas data frame. Pandas merrily does this currently so probably nothing...
I think this may need to be handled at a level higher, we should be able to know based on the plan the cumulative `file_size_in_bytes` for the scan before residuals are applied.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r520697582
##########
File path: python/iceberg/core/util/profile.py
##########
@@ -0,0 +1,36 @@
+# 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.
+
+
+from contextlib import contextmanager
+import logging
+import time
+
+_logger = logging.getLogger(__name__)
+
+
+@contextmanager
+def profile(label, stats_dict=None):
+ if stats_dict is None:
+ print('PROFILE: %s starting' % label)
Review comment:
agree.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#issuecomment-724220000
@rblue i rebased this to the current master and it looks like it fixed the previous issues.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r526246133
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
I just did some initial testing and I'm not seeing a significant difference between passing a list of files to Datasets vs. using a python threadper file and then concating the resulting tables. Let me come up with some more test cases and see if there are some where the arrow threading does better. Using some internal data I read about ~90M rows in about 9 secs both ways. Test was run on a r4.16xlarge instance with EBS storage. I'll try and setup something reproducible for you to try out
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#issuecomment-723224357
@rdblue I'm not sure why this Run license check is failing. I initially didn't have those files in my PR, but I've rebased onto the current master and still seems to not have them. When I look at my branch in my repo they are there. Also, when running locally the license check passes for all the python files.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rymurr commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rymurr commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r528756505
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
Review comment:
thanks for the through investigation! Really interesting how close they are in a lot of cases.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r520708751
##########
File path: python/setup.py
##########
@@ -38,7 +37,7 @@
'requests',
'retrying',
'pandas',
- 'pyarrow'
+ 'pyarrow>=0.17.0'
Review comment:
Good catch.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on a change in pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#discussion_r520699413
##########
File path: python/iceberg/parquet/parquet_reader.py
##########
@@ -0,0 +1,240 @@
+# 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.
+
+
+from datetime import datetime
+import decimal
+import logging
+from typing import Any, Callable, Dict, List, Tuple, Union
+
+from iceberg.api import Schema
+from iceberg.api.expressions import Expression
+from iceberg.api.io import InputFile
+from iceberg.api.types import NestedField, Type, TypeID
+from iceberg.core.util.profile import profile
+from iceberg.exceptions import InvalidCastException
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+from pyarrow import fs
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+
+from .dataset_utils import get_dataset_filter
+from .parquet_schema_utils import prune_columns
+from .parquet_to_iceberg import convert_parquet_to_iceberg
+
+_logger = logging.getLogger(__name__)
+
+DTYPE_MAP: Dict[TypeID,
+ Callable[[NestedField], Tuple[pa.Field, Any]]] = \
+ {TypeID.BINARY: lambda field: pa.binary(),
+ TypeID.BOOLEAN: lambda field: (pa.bool_(), False),
+ TypeID.DATE: lambda field: (pa.date32(), datetime.now()),
+ TypeID.DECIMAL: lambda field: (pa.decimal128(field.type.precision, field.type.scale),
+ decimal.Decimal()),
+ TypeID.DOUBLE: lambda field: (pa.float64(), np.nan),
+ TypeID.FIXED: lambda field: pa.binary(field.length),
+ TypeID.FLOAT: lambda field: (pa.float32(), np.nan),
+ TypeID.INTEGER: lambda field: (pa.int32(), np.nan),
+ TypeID.LIST: lambda field: (pa.list_(pa.field("element",
+ DTYPE_MAP[field.type.element_type.type_id](field.type)[0])),
+ None),
+ TypeID.LONG: lambda field: (pa.int64(), np.nan),
+ # To-Do: update to support reading map fields
+ # TypeID.MAP: lambda field: (,),
+ TypeID.STRING: lambda field: (pa.string(), ""),
+ TypeID.STRUCT: lambda field: (pa.struct([(nested_field.name,
+ DTYPE_MAP[nested_field.type.type_id](nested_field.type)[0])
+ for nested_field in field.type.fields]), {}),
+ TypeID.TIMESTAMP: lambda field: (pa.timestamp("us"), datetime.now()),
+ # not used in SPARK, so not implementing for now
+ # TypeID.TIME: pa.time64(None)
+ }
+
+
+class ParquetReader(object):
+
+ def __init__(self, input: InputFile, expected_schema: Schema, options, filter_expr: Expression,
+ case_sensitive: bool, start: int = None, end: int = None):
+ self._stats: Dict[str, int] = dict()
+
+ self._input = input
+ self._input_fo = input.new_fo()
+
+ self._arrow_file = pq.ParquetFile(self._input_fo)
+ self._file_schema = convert_parquet_to_iceberg(self._arrow_file)
+ self._expected_schema = expected_schema
+ self._file_to_expected_name_map = ParquetReader.get_field_map(self._file_schema,
+ self._expected_schema)
+ self._options = options
+ self._filter = get_dataset_filter(filter_expr, ParquetReader.get_reverse_field_map(self._file_schema,
+ self._expected_schema))
+
+ self._case_sensitive = case_sensitive
+ if start is not None or end is not None:
+ raise NotImplementedError("Partial file reads are not yet supported")
+ # self.start = start
+ # self.end = end
+
+ self.materialized_table = False
+ self.curr_iterator = None
+ self._table = None
+ self._df = None
+
+ _logger.debug("Reader initialized for %s" % self._input.path)
+
+ @property
+ def stats(self) -> dict:
+ return dict(self._stats)
+
+ def to_pandas(self) -> Union[pd.Series, pd.DataFrame]:
+ if not self.materialized_table:
+ self._read_data()
+ with profile("to_pandas", self._stats):
+ if self._table is not None:
+ self._df = self._table.to_pandas(use_threads=True)
+ else:
+ self._df = None
+
+ return self._df
+
+ def to_arrow_table(self) -> pa.Table:
+ if not self.materialized_table:
+ self._read_data()
+
+ return self._table
+
+ def _read_data(self) -> None:
+ _logger.debug("Starting data read")
+
+ # only scan the columns projected and in our file
+ cols_to_read = prune_columns(self._file_schema, self._expected_schema)
+
+ with profile("read data", self._stats):
+ arrow_dataset = ds.FileSystemDataset.from_paths([self._input.location()],
+ schema=self._arrow_file.schema_arrow,
+ format=ds.ParquetFileFormat(),
+ filesystem=fs.LocalFileSystem())
+
+ arrow_table = arrow_dataset.to_table(columns=cols_to_read, filter=self._filter)
+
+ # process schema evolution if needed
+ with profile("schema_evol_proc", self._stats):
+ processed_tbl = self.migrate_schema(arrow_table)
+ for i, field in self.get_missing_fields():
+ dtype_func = DTYPE_MAP.get(field.type.type_id)
+ if dtype_func is None:
+ raise RuntimeError("Unable to create null column for type %s" % field.type.type_id)
+
+ dtype = dtype_func(field)
+ processed_tbl = (processed_tbl.add_column(i,
+ pa.field(field.name, dtype[0], True, None),
+ ParquetReader.create_null_column(processed_tbl[0],
+ dtype)))
+ self._table = processed_tbl
+ self.materialized_table = True
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ if self.curr_iterator is None:
+ if not self.materialized_table:
Review comment:
Let me revisit this. Internally(at NFLX), we generally end up in a pandas DF, so that was the motivation here, but as arrow has matured, it does seem like it's more viable to leave things in an arrow buffer, and let clients deal with how they want to post-process.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] TGooch44 commented on pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
TGooch44 commented on pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#issuecomment-724320412
No problem, take your time. I'm very appreciative that you're reviewing it.
On Mon, Nov 9, 2020, 11:37 AM Ryan Murray <no...@github.com> wrote:
> Hey @TGooch44 <https://github.com/TGooch44> apologies, I'm about 3/4 done
> reviewing. Should have something tomorrow morning.
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/apache/iceberg/pull/1727#issuecomment-724232913>, or
> unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AAMETH6VAC7IHQS7HNMDU2DSPBAIFANCNFSM4TLX5O3A>
> .
>
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
[GitHub] [iceberg] rdblue commented on pull request #1727: [python] Adding parquet package and the classes for reading parquet
Posted by GitBox <gi...@apache.org>.
rdblue commented on pull request #1727:
URL: https://github.com/apache/iceberg/pull/1727#issuecomment-723232790
@TGooch44, the license check is new and master had failures that we fixed yesterday. Pushing to this branch should fix it, but I'm okay just ignoring the errors that we already fixed.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org