SELECT ... WHERE ...在CouchDB + Python中查询

时间:2015-03-02 11:13:14

标签: python couchdb

我是CouchDb的新手。当我安装它时,我认为它会像MongoDb,但mongo现在似乎比沙发更透明。至少,在mongo我几乎可以立即插入并获取数据,使用find(),在沙发中我看不到这么简单的查询方式。所以,想象一下,我保存了一份文件

{'type':'post','theme':'blabla'}

现在我需要查询所有帖子。我如何在Python中使用couchdb模块?

2 个答案:

答案 0 :(得分:2)

首先,尝试创建一个视图。

function(doc) {
  if(doc.type) {
    emit(doc.type);
  }
}

有关观看的详情,请参阅此处:http://guide.couchdb.org/draft/views.html

接下来,写一些python。我只有cloudant-python库的经验,看起来像这样:

import cloudant

account = cloudant.Account('http://localhost:5984')
db = account.database('yourdb')

view = db.view('theview')
options = {
    'key': 'post',
    'include_docs': True
}
for row in view.iter(params=options):
    # emits only rows with the key 'post'
    # with each row's emitting document

注意:这也适用于CouchDB

答案 1 :(得分:1)

您可以使用的最简单的方法是 Mango 查询:

首先,让我们创建数据库并保存您的文档(使用 savecreate 已弃用):

import couchdb
s = couchdb.Server()  # this is http://localhost:5984/ by default
db = s.create('posts')
db.save({'type': 'post', 'theme': 'blabla'})

我们应该描述设置 OP。

使用 find 查询

for doc in db.find({'selector': {'type': 'post'}}):
    # process your doc
    print(doc)

就是这样! 在此处阅读有关可能性的更多信息:http://localhost:5984/_utils/docs/api/database/find.html

请注意,JSON 查询是作为普通 Python dict 传递的。 selector 可以有多个条件,不仅仅是相等:

db.find({'selector': {'type': 'post', 'theme': {'$regex': '^bla'}})

不要忘记索引

如果您直接使用 API,您会在结果中收到警告。 查询没有使用索引!对于较大的数据库,这会很慢。

以编程方式创建索引是一项挑战,但我通过源代码挖掘学会了如何做到这一点(您不需要经常这样做 - 这是一项数据库管理任务,您可以使用 Fauxton UI 来完成)。

>

以下是访问和查看索引的方法:

idx = db.index()

显示:

>>> list(idx)
[{'ddoc': None,
  'name': '_all_docs',
  'type': 'special',
  'def': {'fields': [{'_id': 'asc'}]}}]

现在在 type 上创建一个新的:

idx[None, None] = ['type']

(传递 None 将生成一个随机的设计文档,以及一个随机的索引名称(UUID)):

>>> list(idx)
[{'ddoc': None,
  'name': '_all_docs',
  'type': 'special',
  'def': {'fields': [{'_id': 'asc'}]}},
 {'ddoc': '_design/3298cb694b9b0e42b2a70030ece92eca87d3552d',
  'name': '3298cb694b9b0e42b2a70030ece92eca87d3552d',
  'type': 'json',
  'def': {'fields': [{'type': 'asc'}]}}]

如果您要过滤 theme,您也可以添加:

idx['ddoc_theme_idx', 'theme_idx'] = [{'theme': 'asc'}]

给出:

>>> list(idx)
[{'ddoc': None,
  'name': '_all_docs',
  'type': 'special',
  'def': {'fields': [{'_id': 'asc'}]}},
 {'ddoc': '_design/3298cb694b9b0e42b2a70030ece92eca87d3552d',
  'name': '3298cb694b9b0e42b2a70030ece92eca87d3552d',
  'type': 'json',
  'def': {'fields': [{'type': 'asc'}]}},
 {'ddoc': '_design/ddoc_theme_idx',
  'name': 'theme_idx',
  'type': 'json',
  'def': {'fields': [{'theme': 'asc'}]}}]

索引可以在多个字段上 - 只需在列表中添加更多字段,例如:

idx[None, None] = ['type', 'theme']