0

How is it possible to use map and reduce functions in CouchDB-Python, because the below code does not return anything?

Is it also possible to disable reduce function if it is not needed?

import couchdb

# $ sudo systemctl start couchdb
# http://localhost:5984/_utils/


def fill_data(users_no):
    for i in range(users_no):
        doc = {
            '_id': str(i),
            'uname': "name_" + str(i),
        }
        db.save(doc)


if __name__ == "__main__":
    server = couchdb.Server()
    db = server.create("test-pagination")
    fill_data(300)



    map_fun = """
                function(doc) {
                    emit(doc.uname, 1);
                }
              """
    reduce_fun ="_count"


    design = { 'views': {
              'get_unames': {
                  'map': map_fun,
                  'reduce': reduce_fun
                }
            } }
    db["_design/users"] = design

    uname_list = db.view('users/get_unames')

    print uname_list
    for r in uname_list :
        print r.key
Aurélien Bénel
  • 3,775
  • 24
  • 45
user977828
  • 7,259
  • 16
  • 66
  • 117
  • 1
    It is just a test, right? You are aware that you are not supposed to create the view every time you query it, aren't you? Or you will lose the efficiency benefits of Map/Reduce. – Aurélien Bénel Oct 20 '14 at 05:35
  • 1
    Your example is weird... If you really want *all the data*, without *custom sorting*, nor *grouping*. You should use query `_all_docs` instead of your custom view. You can even query `_all_docs?include_docs=true` to get documents details. If I may give you an advice: you should explore the HTTP API (and common Map/Reduce algorithms) *before* learning CouchDB-Python. – Aurélien Bénel Oct 20 '14 at 06:17

2 Answers2

1

You give very few details about what you want to get. But I infer from the code that you want unique names. If it is so, you definitely need data to be reduced.

Your problem is that you group data too much. You should call the view with group_level=exact (or group=true which is a synonym).

Aurélien Bénel
  • 3,775
  • 24
  • 45
0

Yes it is possible to disable the reduce, and this is exactly what you need:

db.view('users/get_unames', reduce=False)

With the reduce active, you get exactly one row back, with just a value (300, the count of your rows) and and empty key.

Matt Jennings
  • 1,148
  • 6
  • 11