我希望能够使用: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" => []}])如何才能做到这一点?
发布于 2022-05-22 12:28:12
陈郁的解决方案是好的,但在得到之前,我已经找到了另一个解决方案。基本上,您可以将地图添加到元组中。
:dets.insert(table, {:map, topics_map})然后,您可以使用
:dets.lookup(table, :map)发布于 2022-05-22 12:11:33
我被erlang测试过了。你应该先把地图转换成列表。
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).发布于 2022-05-22 15:48:50
正如我理解您的意图一样,您希望将users和tweets存储在单独的密钥下。为此,首先需要构造关键字列表,而不是地图。
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)https://stackoverflow.com/questions/72336508
复制相似问题