Pyspark count() slow

So I have a spark dataframe where I need to get the count/length of the dataframe but the count method is very very slow. I can’t afford to use the .count() because I’ll be getting the count for about 16 million options.

Is there any alternative to this? Thank you

Posted Nov 8, 2021, 7:59 PM UTC

56
vvs02•

in most cases, your count is taking a lot of time because it is recalculating the data frame from the first step onwards which will take a lot of time. Try this - just before counting, push the DF to a temp file and read back from it, (maybe filter for just one column) and cache it. Then use the count function. What this does is that the DF lineage is shortened from the entire calculation to just reading from the file and your count happen faster. Try and let me know if that worked for you, it did in my scenario.

3
manimalman•

Do you mean write it out to a parquet first? How would you write it to a temp file/cache it?

2
westfelia•

Yeah parquet or any preferred format really. I think as long as you're writing it out you'll be fine.

For caching, you can call df.cache(). I think theoretically you could do this without writing it out and back in, but in my experience the optimizer doesn't always remember this so writing it out is a sure fire way to make sure you're not recalculating

3
According-Cow-1984•

I believe filter won't help much. Since count function causes shuffling of data over partitions. Maybe reducing the partition size might help.

1
Wtanso•

Are you just counting how many rows are in the data frame? Maybe try collecting one column of the data frame to a list and then call len()? (Df.select(‘row_name’).collect())

1
According-Cow-1984•

Collect will also cause shuffling. It's not good idea to use collect.

1