时间敏感的 Cloudant 视图并不总是返回正确的结果

Time-sensitive Cloudant view not always returning correct results

我有一个 Cloudant 数据库视图,旨在显示未来 24 小时内发生的事件:

function (doc) {

  // activefrom and activeto are in UTC 
  // set start to local time in UTC
  var m = new Date();
  var start = m.getTime();

  // end is start plus 24 hours of milliseconds
  var end = start + (24*60*60*1000);

  // only want approved disruptions for today that are not changed conditions
  if (doc.properties.status === 'Approved' && doc.properties.category != 'changed' && doc.properties.activefrom && doc.properties.activeto){
     if (doc.properties.activeto > start && doc.properties.activefrom < end)
       emit([doc.properties.category,doc.properties.location], doc.properties.timing);    
     }
  }
}

这在大多数情况下工作正常,但有时视图不会显示预期的结果。

如果我编辑视图,即使只是添加评论,输出也会更改为预期结果。如果我重新编辑视图并删除更改,结果 return 为不正确的结果。

这是因为视图的时效性吗?有没有更好的方法达到同样的效果?

你的MapReduce函数索引的日期是处理工作的服务器执行索引操作的时间。

Cloudant 视图不一定在数据添加到数据库时生成。有时,根据集群必须完成的工作量,Cloudant 索引器直到稍后才被触发。在视图被 查询 之前,文档甚至可以保持未索引状态。在那种情况下,索引中的日期将不是 "the time the document was inserted",而是 "the time the document was indexed/queried",这可能不是您的本意。

不仅如此,数据库的不同分片(副本)可能会在不同时间处理视图构建,根据您询问的服务器不同,结果也会不一致!

您可以通过索引源文档中的内容来解决问题,例如

如果您的文件看起来像:

{ "timestamp": 1519980078159, "properties": { "category": "books", "location": "Rome, IT" } }

您可以使用文档中的 timestamp 值生成索引,并且您创建的视图在所有分片中都是一致的并且是确定性的。