清理 Postgres table 的坏行
cleaning a Postgres table of bad rows
我继承了一个 Postgres 数据库,目前正在清理它。我创建了一个算法来 查找 数据错误的行。该算法被编码到名为 checkProblems()
的函数中。使用它,我能够 select 包含坏行的行,如下所示 ...
schema = findTables(dbName)
conn = psycopg2.connect("dbname='%s' user='postgres' host='localhost'"%dbName)
cur = conn.cursor()
results = []
for t in tqdm(sorted(schema.keys())):
n = 0
cur.execute('select * from %s'%t)
for i, cs in enumerate(tqdm(cur)):
if checkProblem(cs):
n += 1
results.append({
'tableName': t,
'totalRows': i+1,
'badRows' : n,
})
cur.close()
conn.close()
print pd.DataFrame(results)[['tableName', 'badRows', 'totalRows']]
现在,我需要删除 坏行。我有两种不同的方法。首先,我可以在临时 table 中写入干净的行,然后重命名 table。我认为这个选项太占用内存了。如果我能够只删除光标处的特定记录,那就更好了。这甚至是一个选择吗?
否则,在这种情况下删除记录的最佳方法是什么?我猜这应该是数据库管理员做的比较普遍的事情...
当然删除光标处的具体记录更好。你可以这样做:
for i, cs in enumerate(tqdm(cur)):
if checkProblem(cs):
# if cs is a tuple with cs[0] being the record id.
cur.execute('delete from %s where id=%d'%(t, cs[0]))
或者您可以存储坏记录的 ID,然后执行类似
从 table 中删除 ID IN (id1,id2,id3,id4)
我继承了一个 Postgres 数据库,目前正在清理它。我创建了一个算法来 查找 数据错误的行。该算法被编码到名为 checkProblems()
的函数中。使用它,我能够 select 包含坏行的行,如下所示 ...
schema = findTables(dbName)
conn = psycopg2.connect("dbname='%s' user='postgres' host='localhost'"%dbName)
cur = conn.cursor()
results = []
for t in tqdm(sorted(schema.keys())):
n = 0
cur.execute('select * from %s'%t)
for i, cs in enumerate(tqdm(cur)):
if checkProblem(cs):
n += 1
results.append({
'tableName': t,
'totalRows': i+1,
'badRows' : n,
})
cur.close()
conn.close()
print pd.DataFrame(results)[['tableName', 'badRows', 'totalRows']]
现在,我需要删除 坏行。我有两种不同的方法。首先,我可以在临时 table 中写入干净的行,然后重命名 table。我认为这个选项太占用内存了。如果我能够只删除光标处的特定记录,那就更好了。这甚至是一个选择吗?
否则,在这种情况下删除记录的最佳方法是什么?我猜这应该是数据库管理员做的比较普遍的事情...
当然删除光标处的具体记录更好。你可以这样做:
for i, cs in enumerate(tqdm(cur)):
if checkProblem(cs):
# if cs is a tuple with cs[0] being the record id.
cur.execute('delete from %s where id=%d'%(t, cs[0]))
或者您可以存储坏记录的 ID,然后执行类似 从 table 中删除 ID IN (id1,id2,id3,id4)