Database / CouchDB Interview Questions
How do you create and use a Mango index in CouchDB (json and text indexes)?
Mango supports two index types: json indexes (B-tree, for equality and range queries on specific fields) and text indexes (full-text Lucene-backed, for free-text search on string fields). Both are created via POST to /_index.
# Create a JSON index on status + created_at for the orders collection
curl -X POST http://admin:pass@localhost:5984/mydb/_index \
-H "Content-Type: application/json" \
-d '{
"index": {
"fields": ["type", "status", "created_at"]
},
"name": "idx-orders-status-date",
"type": "json",
"ddoc": "_design/mango_indexes"
}'
# {"result":"created","id":"_design/mango_indexes","name":"idx-orders-status-date"}
# Create a text (full-text) index
curl -X POST http://admin:pass@localhost:5984/mydb/_index \
-H "Content-Type: application/json" \
-d '{
"index": {
"default_field": { "enabled": true, "analyzer": "standard" }
},
"name": "idx-fulltext",
"type": "text"
}'
# Query using the json index (CouchDB picks the index automatically)
curl -X POST http://admin:pass@localhost:5984/mydb/_find \
-H "Content-Type: application/json" \
-d '{
"selector": { "type": "order", "status": "pending" },
"sort": [{ "created_at": "desc" }],
"limit": 10
}'
# List all indexes
curl http://admin:pass@localhost:5984/mydb/_index
CouchDB automatically selects the best available index for a _find query. Check the response header X-Couch-Request-ID and use _explain (POST to _explain with the same selector) to confirm which index was chosen. Without an appropriate index, CouchDB falls back to a full database scan, which is safe for development but unacceptable in production.
More Related questions...