如何编写CouchDB/Cloudant视图,根据指定文件获取对应文档ID?
How to find documents containing a specific file in CouchDB/Cloudant
Absolutely! You can create a map view that indexes each file in your documents, which will let you easily query for all docs associated with a specific file like fileC. Here's how to do it:
Step 1: Create the Map Function
This function will iterate over each file in the files array of your document and emit the file name as the key, paired with the document's _id as the value. This creates an index where each file points to all documents that include it.
function(doc) { // Check if the document has a files array to avoid runtime errors if (doc.files && Array.isArray(doc.files)) { // Emit each file as a key with the document ID as value doc.files.forEach(function(file) { emit(file, doc._id); }); } }
- We add a check for
doc.filesbeing an array to skip any documents that don't have this field (prevents unnecessary errors). - For every file in the array, we
emit()a key-value pair: the file name is the key, and the document's ID is the value.
Step 2: Use the View to Query for fileC
Once you've saved this view in a design document (e.g., _design/file_index with the view named docs_by_file), you can query it by specifying the key fileC.
Example Query (HTTP API)
GET /your-database/_design/file_index/_view/docs_by_file?key="fileC"
Sample Response
You'll get a result like this, showing all documents that include fileC:
{ "total_rows": 9, "offset": 2, "rows": [ { "id": "content1", "key": "fileC", "value": "content1" }, { "id": "content2", "key": "fileC", "value": "content2" } ] }
Quick Notes
- You don't need a reduce function here unless you want to aggregate results (like counting how many docs use a file). For just retrieving document IDs, the map function alone is sufficient.
- If you want the full document instead of just the ID, you can emit
docas the value instead ofdoc._id, or add theinclude_docs=trueparameter to your query.
内容的提问来源于stack exchange,提问作者keeterDev
相关产品推荐
相关产品推荐

