Reputation: 25
I have a CouchDB database with around a million rows. I want query for particular rows in the database using the keys present in an external json. Here is what I am doing right now to accomplish this task:
for i in test_json:
view = ViewDefinition('state', state_name.lower(),"""{function (doc){
if(doc._id == """+i+"""){
emit(doc._id,[doc.user_location,doc.user_project_links])
}}}""")
view.sync(db)
db.commit()
But this creates a separate view for every single input from the json to the query.
So here is my question: Is there a way in which I can parse the json within the javascript query in Couchdb so that a single view is created in the end?
Upvotes: 0
Views: 578
Reputation: 87
You should not create new view each time. This is the strenght of CouchDB - saved views are indexed and execute very fast. If you create new view on millions of documents (not rows, this is not RDBMS), it will take time to index them. You should create the view once in CouchDB, via Futon for example. Your view's map function should look something like this:
function(doc) {
emit(doc._id, [doc.user_location,doc.user_project_links])
}
Next, you can query the database by passing keys to the query. You pass single key: {key=value}, multiple keys: {keys: {...}} or by using the startkey
and endkey
parameters. These keys are filtered against the key in your emit statement, in this case doc._id.
Have a look here: http://guide.couchdb.org/draft/views.html.
Also, keep in mind, that if you need to access multiple fields of your documents, it is better to exclude the doc from the view and use the include_docs=true
in the query to the view. You will always have the key and the document id in the response, so y can use the latter to retrieve the doc as well. The values that you emit are actually part of the view and take additional disk space.
Hope this helps.
Upvotes: 2