Created
February 21, 2019 14:40
-
-
Save mraaroncruz/a49ccbe177659132218910db82f59e75 to your computer and use it in GitHub Desktop.
Batch ecto requests as a stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule PrimedMind.Domain.Utils.EctoBatchStream do | |
import Ecto.Query, only: [from: 2] | |
@batch_size 1000 | |
# Example: | |
# | |
# query = from u in MyApp.User, select: u.email | |
# stream = EctoBatchStream.stream(MyApp.Repo, query) | |
# stream |> Stream.take(3) |> Enum.to_list # => […] | |
def stream(repo, query, batch_size \\ @batch_size) do | |
batches_stream = Stream.unfold(0, fn | |
:done -> | |
nil | |
offset -> | |
results = repo.all(from _ in query, offset: ^offset, limit: ^batch_size) | |
if length(results) < batch_size, | |
do: { results, :done }, | |
else: { results, offset + batch_size } | |
end) | |
batches_stream |> Stream.concat | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment