第一个解决方案
问题中详述的方法(2)似乎效果很好。在基准测试中,我获得了:
- 天真的方法,不带索引:18 MB数据库,86毫秒查询时间
- 天真的方法,带有索引:32 MB数据库,12 ms查询时间
- 方法(2): 18 MB数据库,12毫秒查询时间
这里的关键点是
dt用作
INTEGER PRIMARY KEY,因此 它将是行ID本身,使用B树,并且不会 再有其他隐藏
rowid列。因此,我们避免了会产生对应关系的额外索引
dt => rowid:这
dt是 行ID。
我们还使用
AUTOINCREMENT它在内部创建一个
sqlite_sequence表,该表跟踪最后添加的ID。插入时,这是非常有用的:因为它是可能的两个事件都在几秒钟内的同一时刻(有可能甚至毫秒或微秒时间戳,操作系统可能会截断精度),我们使用的最大
timestamp*10000和
last_added_ID+ 1,以确保它的独特:
MAX(?, (SELECt seq FROM sqlite_sequence) + 1)
代码:
import sqlite3, random, timedb = sqlite3.connect('test.db')db.execute("CREATE TABLE data(dt INTEGER PRIMARY KEY AUTOINCREMENT, label TEXT);")t = 1600000000for i in range(1000*1000): if random.randint(0, 100) == 0: # timestamp increases of 1 second with probability 1% t += 1 db.execute("INSERT INTO data(dt, label) VALUES (MAX(?, (SELECt seq FROM sqlite_sequence) + 1), 'hello');", (t*10000, ))db.commit()# t will range in a ~ 10 000 seconds windowt1, t2 = 1600005000*10000, 1600005100*10000 # time range of width 100 seconds (i.e. 1%)start = time.time()for _ in db.execute("SELECt 1 FROM data WHERe dt BETWEEN ? AND ?", (t1, t2)): passprint(time.time()-start)使用WITHOUT ROWID
桌子
这是
WITHOUT ROWID提供 8毫秒
查询时间的另一种方法。由于使用时AUTOINCREMENT不可用,因此我们必须自己实现一个自动递增的id
WITHOUT ROWID。
WITHOUT ROWID当我们要使用a
PRIMARY KEY(dt, another_column1, another_column2,id)并避免有多余的
rowid列时很有用。而不是拥有一棵B树
rowid和拥有一棵B树
(dt, another_column1,...),我们只有一棵。
db.executescript(""" CREATE TABLE autoinc(num INTEGER); INSERT INTO autoinc(num) VALUES(0); CREATE TABLE data(dt INTEGER, id INTEGER, label TEXT, PRIMARY KEY(dt, id)) WITHOUT ROWID; CREATE TRIGGER insert_trigger BEFORE INSERT ON data BEGIN UPDATe autoinc SET num=num+1; END; """)t = 1600000000for i in range(1000*1000): if random.randint(0, 100) == 0: # timestamp increases of 1 second with probabibly 1% t += 1 db.execute("INSERT INTO data(dt, id, label) VALUES (?, (SELECT num FROM autoinc), ?);", (t, 'hello'))db.commit()# t will range in a ~ 10 000 seconds windowt1, t2 = 1600005000, 1600005100 # time range of width 100 seconds (i.e. 1%)start = time.time()for _ in db.execute("SELECt 1 FROM data WHERe dt BETWEEN ? AND ?", (t1, t2)): passprint(time.time()-start)所有这些方法使用的ID为:
[---- timestamp ----][---- random and/or incremental ----]



