在sqlite中插入大量数据。

问题描述 投票:0回答:1

我正在用sqlite3为我的数据库做一个倒置索引查找表。我的数据库是由某些博客和他们的文章组成的,我有一个表post,它的列是id,text,blogger_id。

我有一个表post,其中有id,text,blogger_id这几列。这个表由大约680 000个帖子组成,我想做一个表Blogger_id。我想建立一个表Blogger_Post_Word,其列为blogger_id, post_id, word_position, word_id。

我是用Python做的,我之前试过2种方法,但都有问题。

  • 我在网上看到,插入大量数据的最好方法是批量插入。这意味着我必须获取所有的帖子,并且对于帖子中的每一个单词,我必须将其存储在本地,这样我就可以在以后进行批量插入。这需要太多的内存,而我没有。

  • 我也试过一个一个地插入每个单词,但这需要的时间太长了。

有没有一种有效的方法来解决这个问题,或者有一个sql语句可以一次完成?

编辑:这是我现在使用的代码。

@lru_cache()
def get_word_id(_word: str) -> int:
    word_w_id = db.get_one('Word', ['word'], (word,))
    if word_w_id is None:
        db.insert_one('Word', ['word'], (word,))
        word_w_id = db.get_one('Word', ['word'], (word,))
    return word_w_id[0]

for post_id, text, creation_date, blogger_id in db.get_all('Post'):
    split_text = text.split(' ')

    for word_position, word in enumerate(split_text):
        word_id = get_word_id(word)

        db.insert_one('Blogger_Post_Word',
                      ['blogger_id', 'post_id', 'word_position', 'word_id'],
                      (blogger_id, post_id, word_position, word_id))

db是我写的一个处理数据库的类 这些是我用的那个类中的函数。

def get(self, table: str, where_cols: list = None, where_vals: tuple = None):
    query = 'SELECT * FROM ' + table

    if where_cols is not None and where_vals is not None:
        where_cols = [w + '=?' for w in where_cols]
        query += ' WHERE ' + ' and '.join(where_cols)

        return self.c.execute(query, where_vals)

    return self.c.execute(query)

def get_one(self, table: str, where_cols: list = None, where_vals: tuple = None):
    self.get(table, where_cols, where_vals)
    return self.c.fetchone()



def insert_one(self, table: str, columns: list, values: tuple):
    query = self.to_insert_query(table, columns)
    self.c.execute(query, values)
    self.conn.commit()


def to_insert_query(self, table: str, columns: list):
    return 'INSERT INTO ' + table + '(' + ','.join(columns) + ')' + ' VALUES (' + ','.join(['?' for i in columns]) + ')'

python database sqlite bulkinsert
1个回答
0
投票

好吧,我希望这能帮助任何人。

问题是,确实那个insert那个太慢了,而且我没有足够的内存在本地存储整个列表。

相反,我使用了两种方法的混合,并将它们增量地插入到数据库中。

我显示了我的列表的大小来确定瓶颈。似乎68万个帖子中的15万个帖子就是我的瓶颈。列表的总大小约为4.5GB。

from pympler.asizeof import asizeof
print(asizeof(indexed_data))

>>> 4590991936

我决定以50000个帖子为增量,以保证一切顺利进行。

这就是我现在的代码。

# get all posts
c.execute('SELECT * FROM Post')
all_posts = c.fetchall()

increment = 50000

start = 0
end = increment

while start < len(all_posts):
    indexed_data = []

    print(start, ' -> ', end)

    for post_id, text, creation_date, blogger_id in all_posts[start:end]:
        split_text = text.split(' ')

        # for each word in the post add a tuple with blogger id, post id, word position in the post and the word to indexed_data
        indexed_data.extend([(blogger_id, post_id, word_position, word) for word_position, word in enumerate(split_text)])

    print('saving...')
    c.executemany('''
    INSERT INTO Inverted_index (blogger_id, post_id, word_position, word)
    VALUES (?, ?, ?, ?)
    ''', indexed_data)

    start += increment
    if end + increment > len(all_posts):
        end = len(all_posts)
    else:
        end += increment
© www.soinside.com 2019 - 2024. All rights reserved.