Sqlite升序似乎不适用于bisect

时间:2014-01-18 11:15:40

标签: python sqlite sorting bisect

我正在使用bisect模块搜索并将sha256哈希插入列表中。

我有大约8,000,000个要搜索和添加的项目,它们存储在sqlite数据库中,我想将它们读入列表中,以便我可以更快地搜索它们。

我遇到的问题是使用bisect将项目插入列表以找到正确的插入点非常慢。完成所有8,000,000件物品大约需要700秒。

在sqlite数据库中按升序创建索引只需要大约90秒,然后大约60秒将这些索引按顺序插入到列表中。

麻烦的是,当我这样做时,对某些项目的bisect搜索失败,但是如果我按顺序搜索该项目的哈希,它实际上就在那里。

因此,似乎数据库提供的顺序与使用bisect获取索引位置时提供的顺序完全相同。

任何想法为什么会这样?能够在依赖bisect之前对列表进行预排序是非常有用的。

UPDATE .... 基于注释,我应该解释一下,我有一个行为类似于列表的自定义类,它将哈希值打包在bytearray中以节省内存。这是我的班级

class Hashlist():

def __init__(self, hashLen):
    self.__hashLen = hashLen
    self.__hashlist = bytearray()
    self.__num_items = 0

def __getitem__(self, index):
    if index >= len(self) or index < 0: 
        print index
        raise IndexError("hash index out of range")
        return 
    return str(self.__hashlist[index*self.__hashLen:(index+1)*self.__hashLen])

def __setitem__(self, index, data):
    if index > len(self) or index < 0: 
        raise IndexError("hash index out of range")
        return 
    if index == len(self):
        self.__hashlist.extend(data)
    else:
        self.__hashlist[index*self.__hashLen:(index+1)*self.__hashLen] = data

def insert(self, index, data):
    oldlen = len(self.__hashlist)/self.__hashLen
    if index > oldlen  or index < 0:
        raise IndexError("trying to insert past next element")
        return
    if index == oldlen:
        self.__hashlist.extend(data)
    else:
        # move the data
        if self.__hashLen == 1:
            self.__hashlist.append(chr(0))
            orig_data = str(self.__hashlist[(index):(len(self.__hashlist)-1)])
            self.__hashlist[(index + 1)*self.__hashLen:(len(self.__hashlist))*self.__hashLen] = orig_data
            #replace existing data
            self.__hashlist[index*self.__hashLen:(index+1)*self.__hashLen] = data
        else:
            orig_data = str(self.__hashlist[(index*self.__hashLen):(len(self.__hashlist) -1)*self.__hashLen])
            self.__hashlist[(index + 1)*self.__hashLen:(len(self.__hashlist))*self.__hashLen] = orig_data
            #replace existing data
            self.__hashlist[index*self.__hashLen:(index+1)*self.__hashLen] = data

由于

迪安

1 个答案:

答案 0 :(得分:0)

如果它们存储在SQL数据库中,则索引不能保证在&#34; sort&#34;中返回结果。订单 - 您必须明确使用&#34;订购&#34;。

另外,如果您正在进行那么多插入,那么我就不会使用bisect,而是排序/合并。

# Add new to old and sort the whole lot...
old_hash_list.extend(new_hash_list)
old_hash_list.sort()

# Assuming new is already sorted than create new list of merged
import heapq
old_and_new = list(heapq.merge(old_hash_list, sorted(new_hash_list)))