【问题标题】:How do I check if key exists in Couchbase?如何检查 Couchbase 中是否存在密钥?
【发布时间】:2013-02-07 14:52:23
【问题描述】:

我已经想到了两种我不太喜欢的方法:

  1. 在 try..catch.. 中调用 touch(key, null) 并从 捕获部分。但是后来我改变了不好的ttl 为了我。
  2. 在 try..catch.. 中调用 add(key, value) 并返回 来自 catch 部分的错误 - 这会降低效率,因为我 必须删除我刚刚不必要地添加的密钥。

顺便说一句,我的环境是 PHP。

有什么建议吗?

谢谢!

【问题讨论】:

    标签: php couchbase


    【解决方案1】:

    Couchbase 目前还没有提供exists 方法,但是你可以使用adddelete 来做这件事,这对Memcache/Memcached 也很有用

    public function exists($key)
    {
        if ($this->object->add($key, true)) {
            $this->object->delete($key);
            return false;
        }
        return true;
    }
    

    https://github.com/twinh/widget/blob/master/lib/Widget/Couchbase.php#L118

    【讨论】:

    • 提供的链接已损坏
    【解决方案2】:

    一个简单的方法是做一个 get(key);如果键存在则返回值,否则操作返回null。

    你的申请还可以吗?

    请注意,由于所有键都在内存中,因此无论键是否存在,获取都一样快。

    【讨论】:

    • 但是如果key的值为null呢?键存在,但其值为 null。
    • 或者该值可以是兆字节大小;也许你不想不必要地拉它。
    【解决方案3】:

    查看此示例,取自 couchbase

      #retrieve the last access date/time of the script.
      #the key name is is the script name prefixed with DATE::
      $last_access_date=$cb_obj->get("DATE::" . $script_name);
    
      #handle the case where this is the first access to the script
      #and that key doesn't yet exist
      if($last_access_date == NULL){
      $last_access_date = "never";
       }
    

    Article Link

    【讨论】:

      【解决方案4】:

      我也缺少一个简单的Exists 成员。

      在 .Net 客户端中,您有 client.TryGet,但它仍然会拉取该项目,当它返回 false 时,这并不意味着它不存在,只是它无法拉取它(只是尝试在我的节点关闭的情况下执行它)。

      同样适用于 .Net 客户端,但 ExecuteGet 会给您一个 IGetOperationResult,它会公开例如 HasValue,但会再次获取实际值。

      使用视图?也许有点脏,但是您可以让视图仅返回 Id,这也将消除检索文档的需要。但不确定它是否真的会表现得更好。

      【讨论】:

        猜你喜欢
        • 2013-07-03
        • 2020-08-19
        • 1970-01-01
        • 2014-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多