Home

Awesome

BSONEach

Deps Status Hex.pm Downloads Latest Version License Build Status Coverage Status Ebert

This module aims on reading large BSON files with low memory consumption. It provides single BSONEach.each(func) function that will read BSON file and apply callback function func to each parsed document.

File is read by 4096 byte chunks, BSONEach iterates over all documents till the end of file is reached.

Also you can use BSONEach.stream(path) if you want to read file as IO stream, which is useful when you use GenStage behavior.

Performance

Installation

It's available on hex.pm and can be installed as project dependency:

  1. Add bsoneach to your list of dependencies in mix.exs:
```elixir
def deps do
  [{:bsoneach, "~> 0.4.1"}]
end
```

2. Ensure bsoneach is started before your application:

```elixir
def application do
  [applications: [:bsoneach]]
end
```

How to use

  1. Open file and pass iostream to a BSONEach.each(func) function:
```elixir
"test/fixtures/300.bson" # File path
|> BSONEach.File.open # Open file in :binary, :raw, :read_ahead modes
|> BSONEach.each(&process_bson_document/1) # Send IO.device to BSONEach.each function and pass a callback
|> File.close # Don't forget to close referenced file
```

2. Callback function should receive a struct:

```elixir
def process_bson_document(%{} = document) do
  # Do stuff with a document
  IO.inspect document
end
```

When you process large files its a good thing to process documents asynchronously, you can find more info here.

Thanks

I want to thank to @ericmj for his MongoDB driver. All code that encodes and decodes to with BSON was taken from his repo.