将多个tinyDB数据库加在一起

Add multiple tinyDB databases together

如何将多个 tinyDB(基于文档的数据库)数据库添加在一起而不会出现 AssertionError 错误? 我正在尝试在此示例中将 12 个 tinyDB 数据库添加到一起。

文件结构:

每个编号的文件如下所示:

{
    "_default": {
        "1": {
            "Strategy": "MAShift",
            "Symbol": "AAVE/USD",
            "Timeframes": [
                "30T"
            ],
            "Parameters": {
                "atr": 14,
                "sma": 5,
                "longLine": 3,
                "shortLine": 5,
                "slMultipier": 12,
                "leverage": 1
            },
            "Start": "2020-10-13 12:00:00",
            "End": "2021-04-26 11:30:00",
            "Duration (days)": 194,
            "Equity Start [$]": 10000,
            "Equity Final [$]": 90470.5732,
            "Return [%]": 804.71,
            "Max. Drawdown [%]": -28.1,
            "Win rate [%]": 69.12,
            "Total trades": 570,
            "Avg. trade [%]": 0.43,
            "Avg. winning trade [%]": 1.88,
            "Avg. losing trade [%]": -2.81
        }, ...
    }
}

我的代码:

from tinydb import TinyDB

resultsTotalDb = TinyDB(f'db/backtestingResultsTotal.json')

for i in range(12):
    resultsDb = TinyDB(f'db/backtestingResults{i}.json')
    for result in resultsDb.all():
        resultsTotalDb.insert(result)

错误:

AssertionError: doc_id 1 already exists

您可以根据数据库计数器重新计算新的文档 ID:

from tinydb import TinyDB
from tinydb.table import Document

# ...

for i in range(12):
    resultsDb = TinyDB(f"db/backtestingResults{i}.json")

    for result in resultsDb.all():
        new_id = i * 100000000 + result.doc_id
        resultsTotalDb.insert(Document(result, doc_id=new_id))