You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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.files being 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 doc as the value instead of doc._id, or add the include_docs=true parameter to your query.

内容的提问来源于stack exchange,提问作者keeterDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:25:00