def zadd(self, key, score, value, nx=False, xx=False): zset_length = int(self._db.get(KEY_CODEC.encode_zset(key), '0')) batch = self._db.write_batch() db_score = self._db.get(KEY_CODEC.encode_zset_value(key, value)) if db_score is not None: if nx: return 0 result = 0 previous_score = db_score if float(previous_score) == float(score): return result else: batch.delete( KEY_CODEC.encode_zset_score(key, value, previous_score)) else: if xx: return 0 result = 1 zset_length += 1 batch.put(KEY_CODEC.encode_zset(key), bytes(zset_length)) batch.put(KEY_CODEC.encode_zset_value(key, value), to_float_string(score)) batch.put(KEY_CODEC.encode_zset_score(key, value, score), bytes('')) batch.write() return result
def zrem(self, key, *members): """ see zadd() for information about score and value structures """ result = 0 zset_length = int(self._db.get(KEY_CODEC.encode_zset(key), '0')) # safe guard if zset_length == 0: return result batch = self._db.write_batch() for member in members: score = self._db.get(KEY_CODEC.encode_zset_value(key, member)) if score is None: continue result += 1 zset_length -= 1 batch.delete(KEY_CODEC.encode_zset_value(key, member)) batch.delete(KEY_CODEC.encode_zset_score(key, member, score)) # empty zset should be removed from keyspace if zset_length == 0: self.delete(key) else: batch.put(KEY_CODEC.encode_zset(key), bytes(zset_length)) batch.write() return result