def create_index(self,*fields):
"""Create an index on the specified field names
An index on a field is a mapping between the values taken by the field
and the sorted list of the ids of the records whose field is equal to
this value
For each indexed field, an attribute of self is created, an instance
of the class Index (see above). Its name it the field name, with the
prefix _ to avoid name conflicts
"""
reset = False
for f in fields:
if not f in self.fields:
raise NameError,"%s is not a field name" %f
# initialize the indices
if self.mode == "open" and f in self.indices:
continue
reset = True
self.indices[f] = {}
for _id,record in self.records.iteritems():
# use bisect to quickly insert the id in the list
bisect.insort(self.indices[f].setdefault(record[f],[]),
_id)
# create a new attribute of self, used to find the records
# by this index
setattr(self,'_'+f,Index(self,f))
if reset:
self.commit()
评论列表
文章目录