Search code examples
functional-programmingerlangelixirdets

How to store a map using :dets in Elixir?


I want to be able to store a map using :dets

Currently, that is the solution I am trying to implement:

# a list of strings
topics = GenServer.call(MessageBroker.TopicsProvider, {:get_topics})

# a map with each element of the list as key and an empty list as value
topics_map =
  topics
  |> Enum.chunk_every(1)
  |> Map.new(fn [k] -> {k, []} end)

{:ok, table} = :dets.open_file(:messages, type: :set)

# trying to store the map
:dets.insert(table, [topics_map])

:dets.close(table)

However, I get

** (EXIT) an exception was raised:
    ** (ArgumentError) argument error
        (stdlib 3.12) dets.erl:1259: :dets.insert(:messages, [%{"tweet" => [], "user" => []}])

How is it possible to accomplish this?


Solution

  • Chen Yu's solution is good, but before getting it I already found another solution. Basically, you can just add the map to a tuple

    :dets.insert(table, {:map, topics_map})
    

    Then, you can get this map by using

    :dets.lookup(table, :map)