How do I check if key exists in Couchbase?

泄露秘密 提交于 2020-01-03 18:36:13

问题


I've already thought of two methods which I don't really like:

  1. Call to touch(key, null) inside try..catch.. and return false from the catch section. But then I'm changing the ttl which is not good for me.
  2. Call to add(key, value) inside try..catch.. and return false from the catch section - This defects efficiency because I have to delete they key I've just unnecessarily added.

BTW, my environment is PHP.

Any suggestions?

Thanks!


回答1:


Couchbase has not provided an exists method at this time, but u can use add and delete to do this stuff, this also work useful for 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:


An easy way will be to do a get(key); if the key exists the value is returned, if not the operation returns null.

Is it ok with your application?

Note that since all the keys are in memory it is as fast to do a get when the key exists or not.




回答3:


check into this example, taken from 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:


I'm missing a simple Exists member as well.

In the .Net client you have client.TryGet which, however still will pull the item and when it returns false, it doesn't really mean it does not exists, just that it couldn't pull it (just tried to execute it with my nodes shutdown).

Again for the .Net client, but ExecuteGet would give you an IGetOperationResult which will expose e.g HasValue, but again pulls in the actual value.

Using a view? Perhaps a bit dirty, but you could have a view returning only the Ids, this would remove the need for retrieving the document as well. Not sure if it's really going to be performing better though.



来源:https://stackoverflow.com/questions/14754007/how-do-i-check-if-key-exists-in-couchbase

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!