MongoDB 索引
- - 博客园_首页索引是用来加快查询的,数据库索引与数据的索引类似,有了索引就不需要翻遍整本书,数据库可以直接在索引中查找,. 使得查询速度很快,在索引中找到条目后,就可以直接跳转到目标文档的位置.. 要掌握如何为查询配置最佳索引会有些难度.. MongoDB索引几乎和关系型数据库的索引一样.绝大数优化关系型数据库索引的技巧同样适用于MongoDB..
'hid':88, 酒店id'date':20150530, 入住日期整形(不要纠结unix时间戳)'enable':1, 政策是否启用'price':100, 政策价格'name':'abc', 政策名称'position':'china', 酒店位置'writeTime':datetime.datetime.now(), 写入时间
db.getCollection('hotels').find({"hid":88, "date":{"$gte":20150501, "$lte":20150510}, "enable":1}).sort({"price":1}).limit(10)
# -*- coding: utf-8 -*-import pymongoimport jsonimport datetime,timeimport sysimport copyimport sys, osfrom multiprocessing import Process, Value, Arrayfrom hashlib import md5from random import choice, randintdef getTimestampFromDatetime(d=None):if d is None:d = datetime.datetime.now()return time.mktime(d.timetuple())def md5Hash(str):m = md5()m.update(str)return m.hexdigest().upper()def task():#10分之一的概率无法使用enableList = [1,1,1,1,1,1,1,1,1,0]dateList = []for i in range(31):dateInt = 20150501dateList.append(dateInt+i)mongoUri = 'mongodb://10.14.40.62:27017/hotel'all_data = {'hid':0,'date':0,'enable':0,'price':0,'name':'abc','position':'china','writeTime':datetime.datetime.now(),}tableName = 'hotels'client = pymongo.MongoClient(mongoUri, max_pool_size=100)db = client.hotellistData = []for i in range(100000):all_data['price'] = randint(100, 10000)all_data['enable'] = choice(enableList)all_data['date'] = choice(dateList)all_data['hid'] = randint(1, 100)listData.append(copy.copy(all_data))db[tableName].insert(listData)if __name__ == '__main__':start = getTimestampFromDatetime()task()end = getTimestampFromDatetime()print('time: {0}s'.format(end-start))
db.getCollection('hotels').find({"hid":88, "date":{"$gte":20150501, "$lte":20150510}, "enable":1}).sort({"price":1}).limit(10).explain()
"n" : 10,"nscannedObjects" : 100000,"nscanned" : 100000,..."scanAndOrder" : true,..."millis" : 200,
{"hid" : 1}
"n" : 10,"nscannedObjects" : 1024,"nscanned" : 1024,..."scanAndOrder" : true,..."millis" : 58ms,
{"hid" : 1,"date" : 1}
"n" : 10,"nscannedObjects" : 326,"nscanned" : 326,..."scanAndOrder" : true,..."millis" : 6ms,
{"hid" : 1,"date" : 1,"enable" : 1}
"n" : 10,"nscannedObjects" : 291,"nscanned" : 300,..."scanAndOrder" : true,..."millis" : 5ms,
{"hid" : 1,"date" : 1,"enable" : 1,"price" : 1}
"n" : 10,"nscannedObjects" : 291,"nscanned" : 300,..."scanAndOrder" : true,..."millis" : 5ms,
{ "hid" : 1, "price" : 1, "date" : 1, "enable" : 1 }
"n" : 10,"nscannedObjects" : 10,"nscanned" : 37,..."scanAndOrder" : false,..."millis" : 0ms,