Writing a simple group by with map-reduce (Couchba

2019-06-26 12:03发布

问题:

I'm new to the whole map-reduce concept, and i'm trying to perform a simple map-reduce function.

I'm currently working with Couchbase server as my NoSQL db.

I want to get a list of all my types:

key: 1, value: null
key: 2, value: null
key: 3, value: null

Here are my documents:

{
   "type": "1",
   "value": "1"
}

{
   "type": "2",
   "value": "2"
}

{
   "type": "3",
   "value": "3"
}

{
   "type": "1",
   "value": "4"
}

What I've been trying to do is: Write a map function:

function (doc, meta) {
  emit(doc.type, 0);
}

Using built-in reduce function:

_count

But i'm not getting the expected result.

How can I get all types ?

UPDATE

Please notice that the types are different documents, and I know that reduce works on a document and doesn't executes outside of it.

回答1:

By default it will reduce all key groups. The feature you want is called group_level:

This is equivalent of reduce=true

~ $ curl 'http://localhost:8092/so/_design/dev_test/_view/test?group_level=0'
{"rows":[
{"key":null,"value":4}
]
}

But here is how you can get reduction by the first level of the key

~ $ curl 'http://localhost:8092/so/_design/dev_test/_view/test?group_level=1'
{"rows":[
{"key":"1","value":2},
{"key":"2","value":1},
{"key":"3","value":1}
]
}

There is also blog post about this: http://blog.couchbase.com/understanding-grouplevel-view-queries-compound-keys

There is appropriate option in couchbase admin console: