0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Python】.NET 向けの軽量DB 「LiteDB」の Python 版を調べてみた

Last updated at Posted at 2024-04-23

はじめに

C#で書かれた.NET 向けの軽量DB「LiteDB」ですが、Python版が無いかググったところ見つかったので試してみました。

どちらも同じ「LiteDB」を名乗っているため、てっきり互換性があるのかと思いきや、まったく別物でした。

とはいうものの、コンセプトは同じなので、「Python版LiteDB公式サイト」 を参考に、簡単なサンプルプログラムを作ってみました。

インストール方法

pip で簡単にインストール可能です。

pip install litedb

サンプルプログラムのソースコード

.NET版 LietDB に比べて、実装されているメソッドが少ないですが、こちらの方がより簡単に使えそうです。

from litedb import DiskDatabase
from datetime import date, timedelta

# 保存対象のクラス
class Employees:
    def __init__(self, day: date, name: str, age: int):
        self.day = day
        self.name = name
        self.age = age

# EmployeesのメンバーをPrintする関数
def print_employees(empls):
    for empl in empls:
        print(f"{empl.day} {empl.name} {empl.age}")

# データベースのオープン(無ければ自動作成)
db = DiskDatabase("d:/data.db")

# データの挿入
db.insert(Employees("2024-04-23","海江田四郎",33))
db.insert(Employees("2024-04-23","芹沢大助",28))
db.insert(Employees("2024-04-23","古畑任一郎",38))
db.insert(Employees("2024-04-24","古畑任次郎",33))
db.insert(Employees("2024-04-25","古畑任三郎",28))
db.commit()

print("---DBから全件取得-----------------------")
elements = db.select(Employees)
print_employees(list(elements))

print("---条件を指定して取り出す-----------------")
empls = list(elements.retrieve(age=33,name="古畑任次郎"))
print_employees(list(empls))

print("---条件を指定して削除--------------------")
elements.delete(age=33)
db.commit() #DBに保存
print_employees(list(elements))

print("---全件削除-----------------------------")
for empl in list(elements):
    elements.delete(age = empl.age)
db.commit() #DBに保存
print_employees(list(elements))

補足説明

ファイルに保存する DiskDatabase と、インメモリで利用する MemoryDatabase の2種類が用意されています。

DiskDatabase(ファイル名) で単一ファイルが生成されるのかと思ったら、次の階層を持つフォルダが生成されました。

D:\DATA.DB
└─0x1c74f7e7af
    │  shard0
    │
    ├─index
    │      blacklist
    │      map
    │
    └─info
            config
            size
            table_type
            unused_indexes

まとめ

ネットでググると、.NET 版「LiteDB」のDBをPython版「LiteDB」で読もうとして失敗するというQAが見つかりましたが、両者は全く異なるものなのでご注意ください。

互換性はありません。

.NET 版の LiteDB の詳しい解説は「【詳しく解説】LiteDBで手軽にデータ保存。NoSQLはアプリと相性抜群!」に詳しい記事があるので、こちらが参考になります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?