0

so I am new in CouchDB and I was trying to write some python program that will upload a JSON file, upload a VIEW, and return me the values in an array.

I wrote the view as if(doc['city.berlin']) emit(doc['city.berlin'], doc['city.berlin'])

So what are my best possibilities to extract the data into an array?

at the moment the return data in the terminal looks too complicated as it is giving back {ID, key, value}. Is there a simple method to save only the values?

Thanks

WestCoast
  • 39
  • 1
  • 8

1 Answers1

0

I'll assume your documents look like this

{
  city: 'berlin',
  x: 1,
  y: 2
}

You can create a view that only indexes documents that have a city value of berlin with a map function like this:

function(doc) {
  if (doc.city === 'berlin') {
    emit(null, null)
  }
}

In the above code, the if statement is choosing the subset of data that reaches the index. A more common pattern is to simply emit the city like so:

function(doc) {
  emit(doc.city, null)
}

Now all of your data is in the index and at query-time you can choose which city's data to retrieve:

/db/_design/mydesigndoc/_view/myview?key="berlin"

The above query will retrieve the ids the documents where the key of the index (the city) matches the value you provide (berlin).

Adding include_docs=true retrieves the original docs in the response too:

/db/_design/mydesigndoc/_view/myview?key="berlin"&include_docs=true

You can also add one of the built-in reducers (_count, _sum or _stats) when creating the view to aggregate the data e.g. using the _count reduce, you can get a list of all the values of city and their counts with:

/db/_design/mydesigndoc/_view/myview?group=true
Glynn Bird
  • 5,507
  • 2
  • 12
  • 21