# Zarr Encoding Specification

In implementing support for the Zarr storage format, Xarray developers made some ad hoc choices about how to store NetCDF data in Zarr. Future versions of the Zarr spec will likely include a more formal convention for the storage of the NetCDF data model in Zarr; see Zarr spec repo for ongoing discussion.

First, Xarray can only read and write Zarr groups. There is currently no support for reading / writing individual Zarr arrays. Zarr groups are mapped to Xarray `Dataset` objects.

Second, from Xarray’s point of view, the key difference between NetCDF and Zarr is that all NetCDF arrays have dimension names while Zarr arrays do not. Therefore, in order to store NetCDF data in Zarr, Xarray must somehow encode and decode the name of each array’s dimensions.

To accomplish this, Xarray developers decided to define a special Zarr array attribute: `_ARRAY_DIMENSIONS`. The value of this attribute is a list of dimension names (strings), for example `["time", "lon", "lat"]`. When writing data to Zarr, Xarray sets this attribute on all variables based on the variable dimensions. When reading a Zarr group, Xarray looks for this attribute on all arrays, raising an error if it can’t be found. The attribute is used to define the variable dimension names and then removed from the attributes dictionary returned to the user.

Because of these choices, Xarray cannot read arbitrary array data, but only Zarr data with valid `_ARRAY_DIMENSIONS` or NCZarr attributes on each array (NCZarr dimension names are defined in the `.zarray` file).

After decoding the `_ARRAY_DIMENSIONS` or NCZarr attribute and assigning the variable dimensions, Xarray proceeds to [optionally] decode each variable using its standard CF decoding machinery used for NetCDF data (see `decode_cf()`).

Finally, it’s worth noting that Xarray writes (and attempts to read) “consolidated metadata” by default (the `.zmetadata` file), which is another non-standard Zarr extension, albeit one implemented upstream in Zarr-Python. You do not need to write consolidated metadata to make Zarr stores readable in Xarray, but because Xarray can open these stores much faster, users will see a warning about poor performance when reading non-consolidated stores unless they explicitly set `consolidated=False`. See Consolidated Metadata for more details.

As a concrete example, here we write a tutorial dataset to Zarr and then re-open it directly with Zarr:

    In [1]: import os

    In [2]: import xarray as xr

    In [3]: import zarr

    In [4]: ds = xr.tutorial.load_dataset("rasm")
    ---------------------------------------------------------------------------
    PermissionError                           Traceback (most recent call last)
    File /usr/lib/python3/dist-packages/pooch/utils.py:262, in make_local_storage(path, env)
        258 if action == "create":
        259     # When running in parallel, it's possible that multiple jobs will
        260     # try to create the path at the same time. Use exist_ok to avoid
        261     # raising an error.
    --> 262     os.makedirs(path, exist_ok=True)
        263 else:

    File <frozen os>:217, in makedirs(name, mode, exist_ok)

    File <frozen os>:217, in makedirs(name, mode, exist_ok)

    File <frozen os>:227, in makedirs(name, mode, exist_ok)

    PermissionError: [Errno 13] Permission denied: '/sbuild-nonexistent'

    The above exception was the direct cause of the following exception:

    PermissionError                           Traceback (most recent call last)
    Cell In[4], line 1
    ----> 1 ds = xr.tutorial.load_dataset("rasm")

    File /build/python-xarray-69jxB9/python-xarray-2025.01.2/xarray/tutorial.py:213, in load_dataset(*args, **kwargs)
        176 def load_dataset(*args, **kwargs) -> Dataset:
        177     """
        178     Open, load into memory, and close a dataset from the online repository
        179     (requires internet).
       (...)
        211     load_dataset
        212     """
    --> 213     with open_dataset(*args, **kwargs) as ds:
        214         return ds.load()

    File /build/python-xarray-69jxB9/python-xarray-2025.01.2/xarray/tutorial.py:165, in open_dataset(name, cache, cache_dir, engine, **kws)
        162 downloader = pooch.HTTPDownloader(headers=headers)
        164 # retrieve the file
    --> 165 filepath = pooch.retrieve(
        166     url=url, known_hash=None, path=cache_dir, downloader=downloader
        167 )
        168 ds = _open_dataset(filepath, engine=engine, **kws)
        169 if not cache:

    File /usr/lib/python3/dist-packages/pooch/core.py:227, in retrieve(url, known_hash, fname, path, processor, downloader, progressbar)
        222 action, verb = download_action(full_path, known_hash)
        224 if action in ("download", "update"):
        225     # We need to write data, so create the local data directory if it
        226     # doesn't already exist.
    --> 227     make_local_storage(path)
        229     get_logger().info(
        230         "%s data from '%s' to file '%s'.",
        231         verb,
        232         url,
        233         str(full_path),
        234     )
        236     if downloader is None:

    File /usr/lib/python3/dist-packages/pooch/utils.py:276, in make_local_storage(path, env)
        272 if env is not None:
        273     message.append(
        274         f"Use environment variable '{env}' to specify a different location."
        275     )
    --> 276 raise PermissionError(" ".join(message)) from error

    PermissionError: [Errno 13] Permission denied: '/sbuild-nonexistent' | Pooch could not create data cache folder '/sbuild-nonexistent/.cache/xarray_tutorial_data'. Will not be able to download data files.

    In [5]: ds.to_zarr("rasm.zarr", mode="w")
    Out[5]: <xarray.backends.zarr.ZarrStore at 0x7c5f82b381f0>

    In [6]: zgroup = zarr.open("rasm.zarr")

    In [7]: print(os.listdir("rasm.zarr"))
    ['latitude', 'longitude', '.zattrs', '.zgroup', '.zmetadata']

    In [8]: print(zgroup.tree())
    /
     ├── latitude (50,) float64
     └── longitude (50,) float64

    In [9]: dict(zgroup["Tair"].attrs)
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    Cell In[9], line 1
    ----> 1 dict(zgroup["Tair"].attrs)

    File /usr/lib/python3/dist-packages/zarr/hierarchy.py:511, in Group.__getitem__(self, item)
        509         raise KeyError(item)
        510 else:
    --> 511     raise KeyError(item)

    KeyError: 'Tair'