几个月前我发现了
mongodb,在看完这个
post之后,我觉得mongodb真的比mysql快,所以我决定建立自己的替补,问题是我的结果与上面帖子的作者不一样,特别是查询数据库:mongodb似乎比MyISAM表慢.你能看看我的python代码,可能是它有问题:
from datetime import datetime
import random
import MySQLdb
import pymongo
mysql_db=MySQLdb.connect(user="me",passwd="mypasswd",db="test_kv")
c=mysql_db.cursor()
connection = pymongo.Connection()
mongo_db = connection.test
kvtab = mongo_db.kvtab
nb=1000000
thelist=[]
for i in xrange(nb):
thelist.append((str(random.random()),str(random.random())))
t1=datetime.now()
for k,v in thelist:
c.execute("INSERT INTO key_val_tab (k,v) VALUES ('" + k + "','" + v + "')")
dt=datetime.now() - t1
print 'MySQL insert elapse :',dt
t1=datetime.now()
for i in xrange(nb):
c.execute("select * FROM key_val_tab WHERE k='" + random.choice(thelist)[0] + "'")
result=c.fetchone()
dt=datetime.now() - t1
print 'MySQL select elapse :',dt
t1=datetime.now()
for k,v in thelist:
kvtab.insert({"key":k,"value":v})
dt=datetime.now() - t1
print 'Mongodb insert elapse :',dt
kvtab.ensure_index('key')
t1=datetime.now()
for i in xrange(nb):
result=kvtab.find_one({"key":random.choice(thelist)[0]})
dt=datetime.now() - t1
print 'Mongodb select elapse :',dt
笔记:
> MySQL和mongodb都在locahost上.
> MySQL和mongodb都有索引的’key’列
MySQL表:
CREATE TABLE IF NOT EXISTS `key_val_tab` (
`k` varchar(24) NOT NULL,
`v` varchar(24) NOT NULL,
KEY `kindex` (`k`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
版本是:
> MySQL:5.1.41
> mongodb:1.8.3
> python:2.6.5
> pymongo:2.0.1
> Linux:Ubuntu 2.6.32 32位PAE
>硬件:桌面核心i7 2.93 Ghz
结果(100万次插入/选择):
MySQL insert elapse : 0:02:52.143803
MySQL select elapse : 0:04:43.675914
Mongodb insert elapse : 0:00:49.038416 -> mongodb much faster for insert
Mongodb select elapse : 0:05:10.409025 -> ...but slower for quering (thought was the opposite)