为Couchbase中的Map函数添加新过滤条件
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/EndKeyon[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
timestampOutset tonull(not just missing), adjust checks todoc.timestampOut !== nullto avoid unintended exclusions.
内容的提问来源于stack exchange,提问作者Mohammed47

