I'm working on a project that extracts massive amounts of data from Elasticsearch in batches, one at a time from a group of indexes. It takes "batch_size" documents, does some work on them, then grabs the next "batch_size" documents until it's worked on all of them. Any advice on what's the most optimal batch size? These documents are extensive and a few fields often contain nested JSON, so I don't want to take too many and bloat the RAM, or make requests take too long. Each document appears to be 0.01 MB in size on average, and as such size scales linearly (200 documents = 2 MB on average, 1000 docs = 10 MB, etc). Any help would be greatly appreciated, thanks!
There isn't one magic number, but with ~0.01 MB per document a few things usually matter more than the exact batch size:
-
Size batches by bytes, not by document count. A response in the 5-15 MB range is a comfortable starting point for most clusters and clients; at your average that is roughly 500-1,500 documents. Because a few documents carry large nested JSON, a byte target protects you from the occasional fat batch better than a fixed count does.
-
Use point-in-time (PIT) plus search_after for deep pagination instead of from/size (which gets slower and is capped by index.max_result_window) or long-lived scroll contexts. Sort on a stable tiebreaker (the PIT gives you _shard_doc) and pass the last sort values of each page into the next request.
-
Only fetch what you process. _source includes/excludes (or "fields") can cut the payload a lot when the nested JSON isn't needed for every step.
-
If one sequential stream is too slow, use sliced PIT searches so several workers each walk a slice, rather than making a single batch huge.
-
Measure: start around 1,000 docs, then try 500 and 2,000 while watching client RSS, request latency and cluster heap/search thread pool rejections. Keep the smallest size after which throughput stops improving.
Also process each batch and release it before fetching the next one, so client memory stays at roughly one or two batches regardless of the total.