Sub topic 16
Working with Remote File Systems such as S3
This chapter covers how to point the dataset API at object storage such as Amazon S3. It assumes you can write and read a local partitioned dataset with ds.write_dataset and ds.dataset, and that you know what Hive partitioning and filters do. The dataset code stays the same. What changes is the file system object you pass in, and the cost of each file operation.
Why remote storage changes the picture
Object stores are not disks. Each request has latency, and listing a "directory" is an API call that returns keys sharing a prefix. Three consequences follow:
- Discovery is slower. Opening a dataset lists every object under the prefix, so a dataset with many files pays for many list calls.
- Small files hurt more. Each file costs at least one request to read its footer and one or more to read data.
- Partition pruning pays off more. Skipping a directory skips its list and read requests.
The earlier chapters on pruning and file sizing therefore matter most here.
File system objects
PyArrow exposes remote storage through pyarrow.fs. The main classes are:
| Class | Storage |
|---|---|
| `fs.LocalFileSystem` | Local disk |
| `fs.S3FileSystem` | Amazon S3 and S3-compatible stores |
| `fs.GcsFileSystem` | Google Cloud Storage |
| `fs.HadoopFileSystem` | HDFS |
Every dataset function accepts a filesystem argument. When you give it a file system, paths are relative to that file system and must not include a scheme such as s3://. With a URI string and no filesystem, PyArrow infers the file system from the scheme.
Opening an S3 dataset
Pass an S3FileSystem and a path in the form bucket/prefix.
import pyarrow.dataset as ds
from pyarrow import fs
s3 = fs.S3FileSystem(region="eu-west-1")
dataset = ds.dataset(
"my-bucket/warehouse/sales",
filesystem=s3,
format="parquet",
partitioning="hive",
)
print(dataset.schema)Credentials come from the usual AWS sources: environment variables, the shared credentials file, or an instance role. You can also pass access_key, secret_key and session_token, but avoid hard-coding them in source files.
The URI form does the same job and infers the file system:
import pyarrow.dataset as ds
dataset = ds.dataset(
"s3://my-bucket/warehouse/sales",
format="parquet",
partitioning="hive",
)
print(sorted(dataset.files)[:3])If you need to set options such as the region or an endpoint, build the S3FileSystem yourself. You can also call fs.FileSystem.from_uri to get the file system and the path stripped of its scheme.
from pyarrow import fs
filesystem, path = fs.FileSystem.from_uri("s3://my-bucket/warehouse/sales")
print(type(filesystem).__name__, path)Writing to S3
write_dataset takes the same filesystem argument. The layout it creates is identical to the local one.
import pyarrow as pa
import pyarrow.dataset as ds
from pyarrow import fs
s3 = fs.S3FileSystem(region="eu-west-1")
table = pa.table({
"year": [2023, 2023, 2024],
"country": ["DE", "FR", "DE"],
"amount": [10.5, 20.0, 7.25],
})
part = ds.partitioning(
pa.schema([("year", pa.int64()), ("country", pa.string())]),
flavor="hive",
)
ds.write_dataset(
table,
"my-bucket/warehouse/sales",
filesystem=s3,
format="parquet",
partitioning=part,
existing_data_behavior="overwrite_or_ignore",
)Two points are specific to object stores:
- There are no real directories. The
year=2023/part exists only as a key prefix. Creating "directories" is cheap, but some tools show empty marker objects. - Writes are not atomic across files. If a job fails halfway, readers may see a partial dataset. Write to a new prefix and switch readers over when the job is done, or use a table format that has transactions.
With existing_data_behavior="delete_matching", deletion runs against the object store as list and delete calls. This is slower than on local disk, so check that your credentials allow deletes before you rely on it.
Passing a filter to reduce requests
Filters on partition columns are applied before any data is read. On S3 this avoids reading the files at all.
import pyarrow.dataset as ds
from pyarrow import fs
s3 = fs.S3FileSystem(region="eu-west-1")
dataset = ds.dataset(
"my-bucket/warehouse/sales",
filesystem=s3,
format="parquet",
partitioning="hive",
)
flt = (ds.field("year") == 2024) & (ds.field("country") == "DE")
table = dataset.to_table(filter=flt, columns=["amount"])
print(table.num_rows)Discovery has already listed every key by this point. Pruning saves the reads, not the listing. To avoid the full listing on a very large dataset, open only the sub-prefix you need, for example my-bucket/warehouse/sales/year=2024. Hive discovery on a sub-prefix does not see year as a partition field, because that part of the path is outside the discovery root. Declare the field yourself if you need it, or add it as a column afterwards.
Tuning reads
S3FileSystem and the Parquet scan have options that matter at scale.
import pyarrow.dataset as ds
from pyarrow import fs
s3 = fs.S3FileSystem(
region="eu-west-1",
retry_strategy=fs.AwsStandardS3RetryStrategy(max_attempts=5),
)
fmt = ds.ParquetFileFormat(
default_fragment_scan_options=ds.ParquetFragmentScanOptions(
pre_buffer=True,
),
)
dataset = ds.dataset(
"my-bucket/warehouse/sales",
filesystem=s3,
format=fmt,
partitioning="hive",
)
scanner = dataset.scanner(columns=["amount"], filter=ds.field("year") >= 2023)
print(scanner.count_rows())pre_buffer=Truecoalesces the small reads for column chunks into fewer, larger requests. This helps on high-latency storage and is a good default for S3.- The retry strategy controls how many times a failed request is repeated. Transient errors and throttling are normal on object stores.
- Larger row groups mean fewer, bigger reads. The sizing guidance from the previous chapters applies. Files of roughly 100 MB to 1 GB usually work better on S3 than thousands of tiny ones.
S3-compatible services
Other services that speak the S3 protocol, such as MinIO, need an endpoint and often a different scheme.
from pyarrow import fs
minio = fs.S3FileSystem(
access_key="minio-user",
secret_key="minio-password",
endpoint_override="localhost:9000",
scheme="http",
)
print(minio.get_file_info("test-bucket"))The credentials above are examples for a local test server. In real use, read them from the environment.
Request flow
The diagram shows what happens when you open a dataset on S3 and read it with a filter.
Common problems
- Scheme in the path with an explicit file system.
ds.dataset("s3://bucket/x", filesystem=s3)fails. Drop thes3://when you pass a file system. - Wrong region. Requests to a bucket in another region fail or redirect. Set
regionexplicitly. - Slow open on large prefixes. Listing scales with the number of objects. Compact small files, or open a narrower prefix.
- Missing partition column after opening a sub-prefix. The discovery root decides which path segments become fields. See the filter section above.
- Permission errors on write. Writing needs put permission.
delete_matchingalso needs list and delete permission. - Partial results after a failed write. Use a staging prefix and a final switch.
Exercise
You open ds.dataset("s3://my-bucket/sales/year=2024", partitioning="hive", format="parquet") and find that the schema has no year column. Why, and how can you fix it?
Show answer
Hive discovery only parses path segments below the root you give it. year=2024 is part of the root, so it is not treated as a partition field. Either open s3://my-bucket/sales and filter on year, or open the sub-prefix with an explicit partition schema (for example a ds.partitioning with a year field and partition_base_dir="my-bucket/sales"), or add the column after reading.
Exercise
A dataset on S3 has 40,000 files of 200 KB each. Name two reasons it is slow to read and one fix.
Show answer
Opening it needs listing of all 40,000 keys, and each file costs separate requests for its footer and data, so latency dominates. Fix it by rewriting the data into fewer, larger files (for example with max_rows_per_file and coarser partition keys), ideally 100 MB or more per file.