# 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 / writting 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` attributes on each array.

After decoding the `_ARRAY_DIMENSIONS` 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")
    ---------------------------------------------------------------------------
    ModuleNotFoundError                       Traceback (most recent call last)
    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/tutorial.py in open_dataset(name, cache, cache_dir, engine, **kws)
        113     try:
    --> 114         import pooch
        115     except ImportError as e:

    ModuleNotFoundError: No module named 'pooch'

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

    ImportError                               Traceback (most recent call last)
    <ipython-input-4-1d37fb2cd247> in <module>
    ----> 1 ds = xr.tutorial.load_dataset("rasm")

    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/tutorial.py in load_dataset(*args, **kwargs)
        223     open_dataset
        224     """
    --> 225     with open_dataset(*args, **kwargs) as ds:
        226         return ds.load()
        227

    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/tutorial.py in open_dataset(name, cache, cache_dir, engine, **kws)
        114         import pooch
        115     except ImportError as e:
    --> 116         raise ImportError(
        117             "tutorial.open_dataset depends on pooch to download and manage datasets."
        118             " To proceed please install pooch."

    ImportError: tutorial.open_dataset depends on pooch to download and manage datasets. To proceed please install pooch.

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

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

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

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

    In [9]: dict(zgroup["Tair"].attrs)
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-9-2ab81eb1d230> in <module>
    ----> 1 dict(zgroup["Tair"].attrs)

    /usr/lib/python3/dist-packages/zarr/hierarchy.py in __getitem__(self, item)
        347                          synchronizer=self._synchronizer)
        348         else:
    --> 349             raise KeyError(item)
        350
        351     def __setitem__(self, item, value):

    KeyError: 'Tair'