日期:2014-05-16  浏览次数:20501 次

Mongodb内嵌文档插入性能评测
Mongodb作为典型的文档数据库,支持内嵌文档和复杂的查询,这给数据库建模带来了更多的灵活性。在一个博客应用中,有博客(Blog)和评论(Comment),每篇博客可以有多条评论。在关系数据库建模中,通常博客和评论分别对应一张表,评论表有到博客表的外键。在MongoDB中,也可以像关系型数据库那样,将博客和评论分别放到不同的集合中,另外也可以选择将评论嵌入到博客文档中。对于后者,一个博客的数据结构可能像这样:

> db.blog.findOne()
{
	_id: 1,
	title: "No Free Lunch",
	author: "Alex",
	comments: [
		{ who: "John", comment: "I agree" },
		{ who: "Felix", comment: "You must be joking..." },
	]
}


这种方式的好处显而易见,它更加符合对象模型,也可以利用MongoDB的事务,因为MongoDB并不支持跨文档的事务。当然这样做也有坏处,最明显的缺陷在于MongoDB限制单个文档大小最大只能为16M。若每条评论大小以1K计,那么一个文档最多可容纳16K的评论,这个数字实在不小,中国最著名的博主韩寒,去掉被和谐的博客和评论,评论数最多的博客也只有不到6万条评论。而另一个可能的问题是性能,在文档中插入内嵌文档的性能如何,这是我主要关注的问题。

为了考虑文档大小对内嵌文档插入速度的影响,分别考虑每篇博客有1条、10条、100条、1000条、10000条评论的情况。每种情况均插入1万条评论,博客只有1条评论时同时插入1万个博客文档,有10条评论时同时插入1000个博客文档,有100条评论时同时插入100个博客文档,依此类推。另外为了对比内嵌文档插入和独立文档插入的速度,我也需要记录在独立集合中插入1万条评论的时间。MongoDB同时支持异步插入和同步插入,为了排除它的影响,两种情况我都作了测试。

测试代码如下,使用python,每条评论大小为1K。insert_embbded_comments是内嵌文档插入,参数n是每篇博客的评论数目,comment_len是每条评论的长度,这里总为1000,count为插入的博客数目,count*n总为10000,safe表示是否为同步插入,函数返回结果为执行时间。insert_comments和insert_embbded_comments基本一样,只是在独立集合中插入评论。

from pymongo import Connection
import sys, time

# 目的:测试Mongo中内嵌文档的插入速度
conn = Connection()
db = conn.bench

conn.drop_database('bench')
def insert_embbded_comments(n, comment_len, count=1, safe=False):
    comment_text = 'a'*comment_len
    start = time.time()
    for c in xrange(count):
        blog = {'_id': c, 'title': 'Mongodb Benchmark'}
        db.blog.insert(blog)
        for i in xrange(n):
            db.blog.update({'_id': c}, {'$push': { 'comments': {'comment': comment_text}}}, safe=safe)
    end = time.time()
    return end - start

def insert_comments(n, comment_len, count=1, safe=False):
    comment_text = 'a'*comment_len
    start = time.time()
    for c in xrange(count):
        for i in xrange(n):
            db.blog.comments.insert({'comment': comment_text}, safe=safe)
    end = time.time()
    return end - start

def bench(safe=False):
    total = 10000
    print '===== %sINSERT %s comments =====' % ('SAFE ' if safe else '', total)
    print '%12s %15s %15s %15s %15s %15s' % ('', '1(x10000)', '10(x1000)', '100(x100)', '1000(x10)', '10000(x1)')

    sys.stdout.write('%12s ' % 'Embeded')
    sys.stdout.flush()
    row_types = (1, 10, 100, 1000, 10000)
    for nrows in row_types:
        conn.drop_database('bench')
        count = total / nrows
        time = insert_embbded_comments(nrows, 1000, count=count, safe=safe)
        sys.stdout.write('%15s%s' % (time, '\n' if nrows==row_types[-1] else ' '))
        sys.stdout.flush()
    sys.stdout.write('%12s ' % 'Non-embeded')
    for nrows in row_types:
        count = total / nrows
        conn.drop_database('bench')
        time = insert_comments(nrows, 1000, count=count, safe=safe)
        sys.stdout.write('%15s%s' % (time, '\n' if nrows==row_types[-1] else ' '))
        sys.stdout.flush()

bench()
bench(safe=True)


在我的笔记本(Ubuntu10.04, MongoDB1.8)上运行結果:
===== INSERT 10000 comments =====
                   1(x10000)       10(x1000)       100(x100)       1000(x10)       10000(x1)
     Embeded   2.31141519547   1.42457890511   1.34223604202    4.3767850399   35.7308151722
 Non-embeded   1.29936504364   1.30167293549   1.30044412613   1.29023313522   1.29240202904
===== SAFE INSERT 10000 comments =====
                   1(x10000)       10(x1000)       100(x100)       1000(x10)       10000(x1)
     Embeded   5.45804405212   4.29802298546   4.95570802689   13.7657668591   107.089906216
 Non-embeded   3.68912506104   3.65784692764   3.77990913391   3.66531991959   3.70736408234


前部分是异步插入,后部分是同步插入。标有Embeded的那一行是插入内嵌评论文档的执行时间,第一列,即标有1(x10000)的列,每篇博客有1条评论,共插入1万篇博客。第二列,即标有10(x1000)的列,每篇博客有10条评论,共插入1000篇博客。第三列,每篇博客有100条评论,共插入100篇博客。最后一列,每篇博客有1万条评论,只插入1篇博客。标有Non-embeded的行是是插入独立评论文档的执行结果,都是插入10000条评论,这一行执行时间基