couchdb-python 和 map 函数 ViewField 执行

1 投票
2 回答
585 浏览
提问于 2025-04-18 03:23

在couchdb-python中,如何执行一个在ViewField中定义的map函数?

>>> from couchdb import Server
>>> from couchdb.mapping import Document, TextField, IntegerField, DateTimeField, ViewField
>>> db = server.create('python-tests')

>>> class Person(Document):
...     _id = TextField()                    
...     name = TextField()                  
...     age = IntegerField()                
...     by_name = ViewField('people', '''\  
...             function(doc) {             
...                     emit(doc.name, doc);
...             }''')
... 
>>> person = Person(_id='Person1', name='John Doe', age=42)                                
>>> person.store(db)                                                                       
<Person u'Person1'@u'1-95aa43bc1639f0602812ef78deca0a96' {'age': 42, 'name': u'John Doe'}>
>>> Person.by_name(db)
<ViewResults <PermanentView '_design/people/_view/by_name'> {}>


>>> for row in db.query(Person.by_name(db)):
...     print row.key
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mit/apps/pymodules/lib/python2.7/site-packages/CouchDB-0.9-py2.7.egg/couchdb/client.py", line 713, in query
wrapper=wrapper)(**options)
  File "/home/mit/apps/pymodules/lib/python2.7/site-packages/CouchDB-0.9-py2.7.egg/couchdb/client.py", line 1041, in __init__
self.map_fun = dedent(map_fun.lstrip('\n\r'))
AttributeError: 'ViewResults' object has no attribute 'lstrip'

2 个回答

1

别忘了保存用 ViewField 映射制作的设计文档。要做到这一点,调用 sync() 方法:

Person.by_name.sync(db)

然后你就可以像这样使用视图:

for person in Person.by_name(db):
     print person._id

我在这个包的文档里没有找到任何参考资料。你可以查看 Python 交互式环境中 ViewDefinition 类的文档字符串,或者查看源代码 https://github.com/oliora/couchdb-python/blob/master/couchdb/design.py

1

你可以用 map 函数作为第一个参数来调用 query 方法:

for row in db.query(Person.by_name.map_fun):
    print row.key

可以查看 query 方法的具体用法

撰写回答