以缩放为中心的MongoDB对象文档映射器
scalymongo的Python项目详细描述
Author: | Allan Caffee <allan.caffee@gmail.com> |
---|
关于
scalymongo包是一组简化大型 利用mongodb扩展分布式软件。
项目状态
scalymongo仍处于alpha之前的开发阶段,尚未准备好部署 在野外。
关键原则
scalymongo旨在通过以下方式帮助开发人员:
- scalability: ScalyMongo makes it easy to write software intended to work efficiently on sharded MongoDB deployments. Internal checks warn developers when their queries or inserts are liable to perform poorly on sharded collections.
- simplicity: ScalyMongo makes interacting with your documents easier by providing a simple Python-friendly document interface.
- flexibility: ScalyMongo doesn’t try to be everything for everyone. Where necessary users can interact directly with the underlying PyMongo driver.
开始
下面是一个简单的博客文章碎片集合示例
>>> from scalymongo import Document, Connection
>>> class BlogPost(Document): ... structure = { ... 'author': basestring, ... 'title': basestring, ... 'body': basestring, ... 'unique_views': int, ... 'comments': [{ ... 'author': basestring, ... 'comment': basestring, ... 'rank': int, ... }], ... } ... indexes = [{ ... 'fields': ['author', 'title'], ... 'shard_key': True, ... 'unique': True, ... }] ... __database__ = 'blog' ... __collection__ = 'blog_posts' ...
上面的示例描述了博客文章的结构。注意我们 在author和title字段上声明了唯一索引。索引 还没有真正创建,但知道存在哪些索引允许 scalymongo警告您查询中可能存在的错误选择。同时注意 我们声明此索引用作shard键。
现在我们有了一个简单的文档类,让我们创建一个示例post。
>>> conn = Connection("localhost", 27017) >>> post = conn.models.BlogPost() >>> post['author'] = 'Allan' >>> post['title'] = 'My first post' >>> post['body'] = "Well, I don't actually have anything to write about..." >>> post.save()
太好了!现在我们有了第一篇博文。现在让我们看看艾伦的帖子 确保它真的被保存了下来。
>>> conn.models.BlogPost.find_one({'author': 'Allan'}) Traceback (most recent call last): ... scalymongo.errors.GlobalQueryException: Some or all of the shard key was not specified. Missing fields were title.
发生了什么事!?记住,我们在author上声明了一个shard键,并且 title字段?scalymongo注意到我们试图在没有 全切分键。这意味着查询可能必须每命中every 在我们的集群中找到我们要找的一个文档。那是 可能不是我们想做的,当然也不是我们想做的 希望在生产集群中定期发生。让我们改进一下 我们的查询有一点,这样就不会碰到每个碎片。
>>> conn.models.BlogPost.find_one({'author': 'Allan', 'title': 'My first post'}) {u'_id': ObjectId('4deb90e41717953527000000'), u'author': u'Allan', u'body': u"Well, I don't actually have anything to write about...", u'title': u'My first post'}
当然这是我们的第一个帖子。当然有时候我们真的想要 即使我们没有完整的碎片钥匙也能找到东西。有时这是 在开发过程中从交互式控制台查找文档非常有用。我们 只需重写scalymongo的建议并强制查询即可:
>>> conn.models.BlogPost.find_one({'author': 'Allan'}, allow_global=True) {u'_id': ObjectId('4deb90e41717953527000000'), u'author': u'Allan', u'body': u"Well, I don't actually have anything to write about...", u'title': u'My first post'}
采取最佳实践!
这是我们对scalymongo的基本概述。很快就来 深入介绍。
特别感谢
scalymongo深受流行的 数据库框架MongoKit。特别感谢Namlook和所有 为Mongokit做出贡献的开发者。