couchdb-python和map函数ViewField执行

时间:2014-04-19 12:06:47

标签: python couchdb couchdb-python

如何在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 个答案:

答案 0 :(得分:1)

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

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

查找query方法签名

答案 1 :(得分:1)

不要忘记使用ViewField映射存储design_doc make。 要执行此操作,请调用sync():

Person.by_name.sync(db)

之后您将能够使用这样的视图:

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

我在包裹的文档中没有任何参考。 查看python shell中的ViewDefinition类的文档字符串或代码源https://github.com/oliora/couchdb-python/blob/master/couchdb/design.py