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

x6yk4ghg  于 2022-12-09  发布在  CouchDB
关注(0)|答案(2)|浏览(135)

我是CouchDb的新手。当我安装它的时候,我以为它会是类似MongoDb的东西,但是mongo现在看起来比couch更透明。至少,在mongo中,我可以使用find()几乎立即插入和获取数据,而在couch中,我看不到这样简单的查询方式。所以,想象一下,我保存了一个文档

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

现在我需要查询所有的帖子。我该如何在Python中做到这一点(使用couchdb模块)?

mspsb9vt

mspsb9vt1#

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

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

falq053o

falq053o2#

您可以使用的最简单的方法是Mango Query:
首先,创建数据库并保存文档(使用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)

就是这样!在这里阅读更多关于可能性的信息:数据库
注意,JSON查询是作为普通Python dict传递的。selector可以有多个条件,而不仅仅是等式:

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

不要忘记索引

如果你直接使用API,你会在结果中得到一个警告。查询没有使用索引!对于较大的数据库,这会很慢。
以编程方式创建索引是一个挑战,但我通过源代码挖掘学会了如何这样做(您不需要经常这样做-这是一个DB管理任务,您可以使用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']

相关问题