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

为Couchbase中的Map函数添加新过滤条件

Updating Your Couchbase Map Function with Additional Filters

First, let's recap your existing setup to make sure we're aligned:

Your document structure looks like this:

{ 
  "id" : 1, 
  "type" : "queueStat", 
  "timestampIN" : 1524131000000, 
  "timestampOut" : 1524131925000 
}

And your current Map function is:

function (doc, meta) {
  if (doc.id && doc.type && doc.type === "queueStat" ){
    emit([doc.id, doc.timestampIN]);
  }
}

You're querying using StartKey and EndKey based on doc.id and timestampIN, and now need to add extra filtering conditions. Below are common scenarios and how to adjust your Map function for each:


Scenario 1: Filter for documents that have completed the queue (non-null timestampOut)

If you only want to emit documents where the item has left the queue (i.e., timestampOut exists and isn't empty), add a check for this field:

function (doc, meta) {
  // Keep original validation + add timestampOut check
  if (doc.id && doc.type && doc.type === "queueStat" && doc.timestampOut) {
    emit([doc.id, doc.timestampIN]);
  }
}

This ensures you only include documents where the queue exit timestamp is set, excluding items still in the queue.


Scenario 2: Pre-filter documents by a timestampIN range

If you want to narrow down emitted docs to those where timestampIN falls within a fixed range (to optimize view performance), add numeric bounds checks:

function (doc, meta) {
  // Example: Only include docs with timestampIN between 1524130000000 and 1524140000000
  const minEntryTime = 1524130000000;
  const maxEntryTime = 1524140000000;

  if (doc.id && doc.type && doc.type === "queueStat" && 
      doc.timestampIN >= minEntryTime && doc.timestampIN <= maxEntryTime) {
    emit([doc.id, doc.timestampIN]);
  }
}

Note: Use this only for static ranges. For dynamic time-based queries, stick to your existing StartKey/EndKey approach instead of hardcoding values here.


Scenario 3: Combine multiple filters (e.g., completed queue + ID range)

You can stack conditions to narrow results further. For example, only emit completed queue items where doc.id is between 1 and 100:

function (doc, meta) {
  if (doc.id && doc.type && doc.type === "queueStat" && 
      doc.timestampOut && doc.id >= 1 && doc.id <= 100) {
    emit([doc.id, doc.timestampIN]);
  }
}

Compatibility Tips

  • Your existing query workflow (using StartKey/EndKey on [doc.id, timestampIN]) will still work exactly as before—you're just reducing the number of documents in the view, which can speed up queries.
  • If some documents might have fields like timestampOut set to null (not just missing), adjust checks to doc.timestampOut !== null to avoid unintended exclusions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:01:26