erlang 如何存储Map使用:dets在 Elixir ?

pinkon5k  于 2022-12-16  发布在  Erlang
关注(0)|答案(3)|浏览(172)

我希望能够使用以下命令存储Map:dets
目前,这是我正在尝试实施的解决方案:

# 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)

不过,我得到

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

如何才能做到这一点?

ylamdve6

ylamdve61#

我已经用erlang测试过了。你应该先把Map转换成列表。
从dets:insert_new()文档开始

insert_new(Name, Objects) -> boolean() | {error, Reason}
Types
Name = tab_name()
Objects = object() | [object()] 
Reason = term()
Inserts one or more objects into table Name. If there already exists some object with a key matching the key of any of the specified objects, the table is not updated and false is returned. Otherwise the objects are inserted and true returned.

测试码

dets:open_file(dets_a,[{file,"/tmp/aab"}]).
Map = #{a => 2, b => 3, c=> 4, "a" => 1, "b" => 2, "c" => 4}.
List_a = maps:to_list(Map). %% <----- this line
dets:insert(dets_a,List_a).
l3zydbqr

l3zydbqr2#

陈宇的解决方案很好,但是在得到它之前我已经找到了另一个解决方案,基本上,你可以把Map添加到元组中

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

然后,您可以使用以下命令获取此Map

:dets.lookup(table, :map)
vs3odd8k

vs3odd8k3#

根据我的理解,您希望将userstweets存储在不同的键下,为此,首先需要构造一个关键字列表,而不是Map。

topics = for topic <- topics, do: {topic, []}
# or topics = Enum.map(topics, &{&1, []})
# or topics = Enum.map(topics, fn topic -> {topic, []} end)

那么您可以使用此关键字列表来创建dets

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

相关问题