python 安装和使用 LMDB

创建日期: 2023-10-07 19:18 | 作者: 风波 | 浏览次数: 14 | 分类: Python

来源:https://lmdb.readthedocs.io/en/release/

1. 安装(Ubuntu 系统)

apt-get install libffi-dev python-dev build-essential
pip install lmdb -i https://mirrors.aliyun.com/pypi/simple/  --trusted-host mirrors.aliyun.com

注意⚠️:

The CFFI variant may be used on CPython by setting the LMDB_FORCE_CFFI environment variable before installation, or before module import with an existing installation:

import os
os.environ['LMDB_FORCE_CFFI'] = '1'

# CFFI variant is loaded.
import lmdb

2. 使用 LMDB

import lmdb

def main(filename):
    env = lmdb.Environment("abc-lmdb", map_size=2 ** 33) # 指定数据库占用磁盘空间的最大值
    env.set_mapsize(2 ** 30) # 设置 map_size 为 1GB。如果之前设置的太小了,那么可以重新设置。

    with env.begin(write=True) as txn:
        key = 'hello'
        value = 'world'
        txn.put(key.encode('utf-8'), value.encode('utf-8')) # put 的内容都需要时 bytes 类型

3. 获取 LMDB 数据库信息 .stat()/.info()

import lmdb

env = lmdb.Environment("abc-lmdb", map_size=2 ** 33)
print(env.stat()) # {'psize': 4096, 'depth': 3, 'branch_pages': 4, 'leaf_pages': 111, 'overflow_pages': 1399060, 'entries': 3207}
print(env.info()) # {'map_addr': 0, 'map_size': 8589934592, 'last_pgno': 1399185, 'last_txnid': 3207, 'max_readers': 126, 'num_readers': 1}

几个字段的含义 - entries key 的数量 - map_size map_size 的大小

4. 获取值 get()

    with env.begin() as txn:
        key = 'hello'
        v = txn.get(key.encode('utf-8'))
        print("value len: {}".format(len(v)))
        with open('a.png', 'wb') as f: # 把二进制内容写入文件
            f.write(v)

5. 遍历 LMDB txn.cursor().iternext()

import lmdb

def main():
    env = lmdb.Environment('abc-lmdb', readonly=True)
    #with env.begin() as txn:
    #    for key, _ in txn.cursor(): # 这个遍历方式会返回 value,所以会慢一些
    #        print(key)
    with env.begin() as txn:
        #keys = list(txn.cursor().iternext(values=False))
        for k in txn.cursor().iternext(values=False): # 不需要返回 value,只返回 key
            print(k.decode('utf-8')) # 返回的值是 bytes 二进制,需要 decode
14 浏览
7 爬虫
0 评论