Elixir: Redis のデータを作成 (Create)

Python のプログラムを、ChatGPT と Gemini に渡して得られた結果を、ちょっと修正しました。

参考ページ
[Elixir: Redix の使い方](https://qiita.com/ekzemplaro/items/9dce1e03e154e4719a8d)
[Elixir: mix の使い方](https://qiita.com/ekzemplaro/items/e5f2c8b2c3ac5cb856f0)

## Python のプログラム

```py:redis_create.py
#!/usr/bin/python
#
#	redis_create.py
#
#					Mar/09/2024
#
import sys
import json
import redis
#
#
# ----------------------------------------------------------------
def dict_append_proc(dict_aa,key,name,population,date_mod):
	dict_aa[key] = {'name':name,'population':population,'date_mod':date_mod}
#
	return dict_aa
#
# ----------------------------------------------------------------
def	data_prepare_proc():
	dict_aa = {} 
#
	dict_aa = dict_append_proc(dict_aa,'t1851','福井',52761,'2003-4-30')
	dict_aa = dict_append_proc(dict_aa,'t1852','敦賀',41295,'2003-5-10')
	dict_aa = dict_append_proc(dict_aa,'t1853','小浜',28674,'2003-6-14')
	dict_aa = dict_append_proc(dict_aa,'t1854','大野',89612,'2003-9-9')
	dict_aa = dict_append_proc(dict_aa,'t1855','勝山',47391,'2003-8-4')
	dict_aa = dict_append_proc(dict_aa,'t1856','鯖江',35187,'2003-1-21')
	dict_aa = dict_append_proc(dict_aa,'t1857','あわら',81246,'2003-7-23')
	dict_aa = dict_append_proc(dict_aa,'t1858','越前',25791,'2003-10-26')
	dict_aa = dict_append_proc(dict_aa,'t1859','坂井',84139,'2003-12-15')
#
	return	dict_aa
#
# ----------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
rr = redis.Redis(host='localhost', port=6379, db=0)
#
dict_aa = data_prepare_proc()
#
for key in dict_aa.keys():
	print(key)
	value = dict_aa[key]
	json_str = json.dumps(value)
	rr.set(key, json_str)
#
sys.stderr.write("*** 終了 ***\n")
# ----------------------------------------------------------------
```

## プロジェクトの作成方法

<ol>

<li>プロジェクトの作成</li>

```bash
mix new redis_create
```

<li>mix.exs を修正</li>
<br />
<li>ライブラリーのロード</li>

```bash
mix deps.get
```

<li>lib/redis_create.ex を置き換える</li>

</ol>

## ChatGPT が作成したプログラムを修正したもの

```exs:lib/redis_create.ex
defmodule RedisCreate do
  def dict_append_proc(dict_aa, key, name, population, date_mod) do
    Map.put(dict_aa, key, %{"name" => name, "population" => population, "date_mod" => date_mod})
  end

  def data_prepare_proc do
    dict_aa =
      dict_append_proc(%{}, "t1851", "福井", 52761, "2003-4-30")
      |> dict_append_proc("t1852", "敦賀", 41295, "2003-5-10")
      |> dict_append_proc("t1853", "小浜", 28674, "2003-6-14")
      |> dict_append_proc("t1854", "大野", 89612, "2003-9-9")
      |> dict_append_proc("t1855", "勝山", 47391, "2003-8-4")
      |> dict_append_proc("t1856", "鯖江", 35187, "2003-1-21")
      |> dict_append_proc("t1857", "あわら", 81246, "2003-7-23")
      |> dict_append_proc("t1858", "越前", 25791, "2003-10-26")
      |> dict_append_proc("t1859", "坂井", 84139, "2003-12-15")
  end

  def main do
    IO.puts("*** 開始 ***")
    
    {:ok, redis} = Exredis.start_link(url: "redis://localhost:6379/0")

    dict_aa = data_prepare_proc()

    Enum.each(dict_aa, fn {key, value} ->
      IO.puts(key)
      json_str = Jason.encode!(value)
#      Exredis.set(redis, key, json_str)
      redis |> Exredis.query ["SET", key, json_str]
    end)

    IO.puts("*** 終了 ***")
  end
end

RedisCreate.main()
```

```exs:mix.exs
（省略）
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
        {:exredis, "~> 0.3.0"},
        {:jason, "~> 1.4"},
    ]
  end
end
```

実行コマンド

```bash
mix run -e "RedisCreate.main"
```

実行結果

```text
$ mix run -e "RedisCreate.main"
*** 開始 ***
t1851
t1852
t1853
t1854
t1855
t1856
t1857
t1858
t1859
*** 終了 ***
```

## Gemini が作成したプログラムを修正したもの

```exs:lib/redis_create.ex
# redis_create.exs

defmodule RedisCreate do
#  @redis_options [host: "localhost", port: 6379, db: 0]
  @redis_options [host: "localhost", port: 6379]

  def start do
    IO.puts("*** 開始 ***")
    with {:ok, redis} <- Redix.start_link(@redis_options) do
      data_prepare_proc()
      |> Enum.each(fn {key, value} ->
        IO.inspect(key)
        json_str = Poison.encode!(value)
        Redix.command!(redis, ["SET", key, json_str])
      end)
    end
    IO.puts("*** 終了 ***")
  end

  defp dict_append_proc(dict_aa, key, name, population, date_mod) do
    dict_aa |> Map.put(key, %{name: name, population: population, date_mod: date_mod})
  end

  defp data_prepare_proc do
    %{}
    |> dict_append_proc("t1851", "福井", 52761, "2003-4-30")
    |> dict_append_proc("t1852", "敦賀", 41295, "2003-5-10")
    |> dict_append_proc("t1853", "小浜", 28674, "2003-6-14")
    |> dict_append_proc("t1854", "大野", 89612, "2003-9-9")
    |> dict_append_proc("t1855", "勝山", 47391, "2003-8-4")
    |> dict_append_proc("t1856", "鯖江", 35187, "2003-1-21")
    |> dict_append_proc("t1857", "あわら", 81246, "2003-7-23")
    |> dict_append_proc("t1858", "越前", 25791, "2003-10-26")
    |> dict_append_proc("t1859", "坂井", 84139, "2003-12-15")
  end
end


RedisCreate.start
```

```exs:mix.exs
（省略）
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
	{:redix, "~> 1.4"},
	{:poison, "~> 5.0"},
    ]
  end
end
```

実行コマンド

```bash
mix run
```

実行結果

```text
$ mix run
Compiling 1 file (.ex)
*** 開始 ***
"t1851"

12:57:40.282 [warning] Failed to lookup telemetry handlers. Ensure the telemetry application has been started. 

12:57:40.283 [warning] Failed to lookup telemetry handlers. Ensure the telemetry application has been started. 
"t1852"

12:57:40.289 [warning] Failed to lookup telemetry handlers. Ensure the telemetry application has been started.
（省略）
```

## Redis の使い方

全てのキーを削除

```text
flushall
```

```text
127.0.0.1:6379> flushall
OK
```

キーの一覧

```text
keys *
```