Skip to content

dask DataFrame.read_parquet doesn't preserve the paths order #8829

Description

@rajeee

What happened:
Dask doesn't honor the order of files listed in the path

What you expected to happen:
I would have expected the partition ordering to be consistent with list of paths in read_parquet. Seems like the input path is automatically sorted internally without choice.

Minimal Complete Verifiable Example:

import dask.dataframe as dd
import pandas as pd
df1=pd.DataFrame({'i': [1, 1], 'A': [1.0, 2.0], 'B': [11.0, 12.0]})
df1.to_parquet("df1.parquet")
df2=pd.DataFrame({'i': [0, 0], 'A':  [3.0, 4.0], 'B': [13.0, 14.0]})
df2.to_parquet("df2.parquet")
forward_df = dd.read_parquet(["df1.parquet", "df2.parquet"], engine='pyarrow')
reverse_df = dd.read_parquet(["df2.parquet", "df1.parquet"], engine='pyarrow')
forward_df.npartitions  # 2
reverse_df.npartitions  # 2

forward_df.get_partition(0).compute() # returns df1
reverse_df.get_partition(0).compute() # Also returns df1. Expected to return df2

Anything else we need to know?:

Environment:

  • Dask version:
  • Python version:
  • Operating System:
  • Install method (conda, pip, source):
Cluster Dump State:

Activity

  1. added
    needs triage
    on Mar 21, 2022
  2. bryanwweber commented on Mar 21, 2022

    @bryanwweber
    Contributor

    I think the existing behavior is expected. The parts of the file are lexicographically sorted before they're read. This is implied by the docstring for to_parquet(..., name_function=...) which says that the name function must preserve the lexicographic ordering of the partitions. Checking the code for read_parquet(), I can see that the paths are sorted before reading, here:

    paths = sorted(paths, key=natural_sort_key) # numeric rather than glob ordering

    Certainly, this could be better documented. I'll leave it to someone else to decide if and option should be added to specify that files should be loaded in the order they're passed 😄

  3. rajeee commented on Mar 21, 2022

    @rajeee
    Author

    I think this behavior is a limitation. If you want to load the files in a custom order, there is currently no way to do so unless you rename the files. It makes sense to sort the paths if the list of paths is created by automatically listing the files. However, I think, it makes the most sense to not sort the user supplied list so that the user can load the files in the order they want. And it seems like it wouldn't be too hard to lift this limitation.

  4. bryanwweber commented on Mar 21, 2022

    @bryanwweber
    Contributor

    If you want to load the files in a custom order

    Can you add something about why you want to do this? Perhaps there's another way. Not saying it doesn't make sense, just that if there's another way to do this, we can unblock you now to keep doing your work 😄

  5. rajeee commented on Mar 21, 2022

    @rajeee
    Author

    Sure, I understand :). Also, good to have a use case in mind rather than a generic "makes sense" feature request.
    The use case is like this: I have about 10k parquet files that holds timeseries values for 10k homes. Since these are too many files, I want to group a bunch of them together. However, I want to group them intelligently so that each group only contains houses belonging to, let's say, same city. One way to do this is repartitioning with custom divisions. But for this to work, I need to have the files be partitioned in a certain order to begin with.

    This SO question I asked might provide more context. I attempted to do that using dask.delayed (which would allow me to decide which file goes into which partition). But using dask.delayed has its own limitation and I would rather use read_parquet directly. But then, read_parquet doesn't honor the order in the input list. Which brings me to this issue. :)

  6. bryanwweber commented on Mar 21, 2022

    @bryanwweber
    Contributor

    Can you use the filters keyword argument to filter the data, or the columns argument? It's not quite clear to me how your files are organized. Is it 1 house's timeseries per parquet file, or 1 house per column? How do you know which files are associated with each, say, city?

  7. rajeee commented on Mar 21, 2022

    @rajeee
    Author

    It's one house per parquet file. Each columns could be power consumption of different circuits. The mapping of buildings to cities is stored in a separate file. I don't see how "filters" argument could help here.

  8. jsignell commented on Mar 22, 2022

    @jsignell
    Member

    This seems like a valid request, but I'm not sure how feasible it is. The sorting seems really baked in. I tried naively removing the sorted line that Bryan pointed out above, but the output is still sorted. There is a lot of path sorting that goes on in the backend, which makes me worried about the implications of trying to make this more flexible.

    Would it be possible to load different cities into separate dataframes and the concatenate them into one large dataframe?

  9. added
    needs info
    and removed
    needs triage
    on Mar 22, 2022
  10. rajeee commented on Mar 22, 2022

    @rajeee
    Author

    Thanks @jsignell.

    I also had another hurdle which required me to pre-process the files anyway. So I ended up renaming the files during the pre-process.
    But, yeah, for a general case, it would be nice if dask would honor the order of files in the input path list.

  11. rjzamora commented on Mar 22, 2022

    @rjzamora
    Member

    We can certainly avoid sorting the file names, but it couldn't be the default behavior (since current users/tests expect dask to correct input glob ordering to be numerical ordering). Therefore, we would probably need to add another argument to read_parquet, and I get the sense that it is not an option many people would be using. With that said, I will be happy to work on this if enough people can confirm that the current behavior is a problem.

    If I understand correctly, the larger problem you are facing is that you need to aggregate many small files into a parquet dataset with fewer files. The most common approach to doing this for an arbitrary file pattern is definitely to use from_delayed. However, in your SO question, I see that you are defining a distinct delayed function for every file. This should "work", but will result in a very large graph. If you already know the mapping between file names and “city”, for example, I’d want my delayed partitions to originate from a function designed to read in and concatenate data for multiple files (rather than just one).

    If you want to try to use the read_parquet API for this, you can also try read_parquet(..., aggregate_files=True) (along with a chunksize= or split_row_groups= setting to specify the size of the output partitions). However, this will not result in each partition cleanly mapping to the same city as you want (it will just give you fewer partitions). I think the most common way to "partition" the parquet dataset on disk is to do something like:

    dd.read_parquet(paths, aggregate_files=True, chunksize=‘1GB’).to_parquet(partitioned_path, partition_on=["city"])

    This will not result in a smaller number of files, but you could always read the dataset back as

    dd.read_parquet(partitioned_path, aggregate_files="city") to get a distinct city in each dask partition.

  12. rajeee commented on Mar 22, 2022

    @rajeee
    Author

    Thanks for detailed reply @rjzamora. Yes, I also tried dataframe.from_delayed where each delayed object is returning a concatenation of a bunch of files. It did work okay but started breaking (taking forever to schedule) once the number of such delayed objects reached around 6K (happens when aggregating largish ~500K files). I finally transitioned to using a simple map of delayed objects that would directly write concatenated files to disk independently without forming a dataframe.

    I am personally not blocked by this anymore; so it's up to you guys to decide if adding an option to not sort the input path is a worthwhile feature to add or not. I am kinda wondering why the decision was made to sort the input path list in dask; if people want sorted path, it's not hard to sort in the application code before passing to dask.

  13. rjzamora commented on Mar 23, 2022

    @rjzamora
    Member

    I finally transitioned to using a simple map of delayed objects that would directly write concatenated files to disk independently without forming a dataframe



    Yeah - If your only goal is to write a new dataset, then skipping the from_delayed part makes a lot of sense. I know most people use delayed over a custom graph, but I personally do something like the following for simple cases like these:



    import pandas as pd
    from dask.dataframe.core import Scalar
    
    files_per_task = 10
    input_paths = ["tmpdir/part.0.parquet", "tmpdir/part.1.parquet", …]
    output_dir = "new_tmpdir"
    
    def read_concat_write(input_paths, output_path):
        pd.concat(
            [pd.read_parquet(path) for path in input_paths]
        ).to_parquet(output_path)
    
    graph = {
        ("read-files", i): (
            read_concat_write,
            input_paths[j:j+files_per_task],
            f"{output_dir}/part.{i}.parquet",
        )
        for i, j in enumerate(range(0, len(input_paths), files_per_task))
    }
    graph[("finish", 0)] = (lambda x: None, list(graph.keys()))
    Scalar(graph, "finish", "").compute()

    I am personally not blocked by this anymore; so it's up to you guys to decide if adding an option to not sort the input path is a worthwhile feature to add or not.

    Regardless of it is currently blocking you, I am interested to know if the path-sorting has been a problem for anyone else. This is the first issue I have seen about this, but it is certainly possible that others have run into the same problem but didn’t bother to share their experience on GitHub. (So, thank you for sharing - I encourage you to keep doing so when behavior seems “off”)

    I am kinda wondering why the decision was made to sort the input path list in dask; if people want sorted path, it's not hard to sort in the application code before passing to dask.



    Fair question - The different engines have historically discovered paths in a slightly different order for directory-partitioned datasets. I think I remember this complicating aggregation behavior and parallel metadata parsing. The backends have also tended to use “glob” ordering instead of numerical ordering. For these reasons, among others, the implicit sorting behavior was probably just introduced without much of an explicit decision. This is probably because no one ever asked for read_parquet to preserve the input path order, but people did ask for numerical ordering (and the directory-partitioning features that motivated the sorting).

    All this is to say that: “Yes. It does seem to me like the user should have the option to preserve the order of the paths specified to read_parquet. The reason that is isn’t supported is just that (1) no one has raised an issue about this yet, and (2) always sorting the paths has simplified other features in read_parquet.

  14. added
    feature
    and removed
    needs info
    on Mar 23, 2022
  15. rajeee commented on Mar 23, 2022

    @rajeee
    Author

    Thanks for the explanation and a bit of a history and context, Rick.

    Your example code looks too raw for my experience (I don't have experience with raw task graph or Scalar construct), so I am using something like this:

    files_groups = np.array_split(input_paths, files_per_task)
    output_paths = [f"{output_idr"/part.{i}.parquet" for i in range(len(files_groups))]
    dask.compute(map(dask.delayed(read_concat_write), files_groups, output_paths))

    I assume this might be similar to your code though, under the hood.

    I have created only a couple of issues so far in this repo, and the engagements and feedbacks have been awesome. This definitely increases my confidence in using dask on my data processing projects. So, kudos to you guys and keep up the good work!

  16. rjzamora commented on Mar 25, 2022

    @rjzamora
    Member

    Just a note here that #8852 will likely improve from_delayed performance for applications like this.

  17. added
    needs attention
    on Jul 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dataframefeatureneeds attentionparquet

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions