1. 程式人生 > 實用技巧 >Redis系列(九):資料結構Hash之HDEL、HEXISTS、HGETALL、HKEYS、HLEN、HVALS命令

Redis系列(九):資料結構Hash之HDEL、HEXISTS、HGETALL、HKEYS、HLEN、HVALS命令

1.HDEL

從 key 指定的雜湊集中移除指定的域。在雜湊集中不存在的域將被忽略。

如果 key 指定的雜湊集不存在,它將被認為是一個空的雜湊集,該命令將返回0。

時間複雜度:O(N)N是被刪除的欄位數量

127.0.0.1:> hset myhash field1 "foo"
(integer)
127.0.0.1:> hdel myhash field1
(integer)
127.0.0.1:>

原始碼解析

// t_hash.c,
void hdelCommand(client *c) {
robj *o;
int j, deleted = , keyremoved = ; if ((o = lookupKeyWriteOrReply(c,c->argv[],shared.czero)) == NULL ||
checkType(c,o,OBJ_HASH)) return;
// 迴圈刪除給定欄位列表
for (j = ; j < c->argc; j++) {
if (hashTypeDelete(o,c->argv[j]->ptr)) {
deleted++;
// 當沒有任何元素後,直接將key刪除
if (hashTypeLength(o) == ) {
dbDelete(c->db,c->argv[]);
keyremoved = ;
break;
}
}
}
if (deleted) {
signalModifiedKey(c->db,c->argv[]);
notifyKeyspaceEvent(NOTIFY_HASH,"hdel",c->argv[],c->db->id);
if (keyremoved)
notifyKeyspaceEvent(NOTIFY_GENERIC,"del",c->argv[],
c->db->id);
server.dirty += deleted;
}
addReplyLongLong(c,deleted);
}
// 具體刪除 field, 同樣區分編碼型別,不同處理邏輯
/* Delete an element from a hash.
* Return 1 on deleted and 0 on not found. */
int hashTypeDelete(robj *o, sds field) {
int deleted = ; if (o->encoding == OBJ_ENCODING_ZIPLIST) {
unsigned char *zl, *fptr; zl = o->ptr;
fptr = ziplistIndex(zl, ZIPLIST_HEAD);
if (fptr != NULL) {
// ziplist 刪除,依次刪除 field, value
fptr = ziplistFind(fptr, (unsigned char*)field, sdslen(field), );
if (fptr != NULL) {
// ziplistDelete 為原地刪除,所以只要呼叫2次,即把kv刪除
zl = ziplistDelete(zl,&fptr);
zl = ziplistDelete(zl,&fptr);
o->ptr = zl;
deleted = ;
}
}
} else if (o->encoding == OBJ_ENCODING_HT) {
if (dictDelete((dict*)o->ptr, field) == C_OK) {
deleted = ; /* Always check if the dictionary needs a resize after a delete. */
// hash 刪除的,可能需要進行縮容操作,這種處理方法相對特殊些
if (htNeedsResize(o->ptr)) dictResize(o->ptr);
} } else {
serverPanic("Unknown hash encoding");
}
return deleted;
}
// server.c, 是否需要進行 resize
int htNeedsResize(dict *dict) {
long long size, used; size = dictSlots(dict);
used = dictSize(dict);
// HASHTABLE_MIN_FILL=10, 即使用率小於 1/10 時,可以進行縮容操作了
return (size && used && size > DICT_HT_INITIAL_SIZE &&
(used*/size < HASHTABLE_MIN_FILL));
}

2.HEXISTS

返回hash裡面field是否存在

時間複雜度:O(1)

127.0.0.1:> hset myhash field1 "foo"
(integer)
127.0.0.1:> hexists myhash field1
(integer)
127.0.0.1:> hexists myhash field2
(integer)
127.0.0.1:>

原始碼解析

void hexistsCommand(client *c) {
robj *o;
if ((o = lookupKeyReadOrReply(c,c->argv[],shared.czero)) == NULL ||
checkType(c,o,OBJ_HASH)) return; addReply(c, hashTypeExists(o,c->argv[]->ptr) ? shared.cone : shared.czero);
}
hashTypeExists
int hashTypeExists(robj *o, sds field) {
if (o->encoding == OBJ_ENCODING_ZIPLIST) {
unsigned char *vstr = NULL;
unsigned int vlen = UINT_MAX;
long long vll = LLONG_MAX; if (hashTypeGetFromZiplist(o, field, &vstr, &vlen, &vll) == ) return ;
} else if (o->encoding == OBJ_ENCODING_HT) {
if (hashTypeGetFromHashTable(o, field) != NULL) return ;
} else {
serverPanic("Unknown hash encoding");
}
return ;
}

ziplist的型別判斷

/* Get the value from a ziplist encoded hash, identified by field.
* Returns -1 when the field cannot be found. */
int hashTypeGetFromZiplist(robj *o, sds field,
unsigned char **vstr,
unsigned int *vlen,
long long *vll)
{
unsigned char *zl, *fptr = NULL, *vptr = NULL;
int ret; serverAssert(o->encoding == OBJ_ENCODING_ZIPLIST); zl = o->ptr;
fptr = ziplistIndex(zl, ZIPLIST_HEAD);
if (fptr != NULL) {
fptr = ziplistFind(fptr, (unsigned char*)field, sdslen(field), );
if (fptr != NULL) {
/* Grab pointer to the value (fptr points to the field) */
vptr = ziplistNext(zl, fptr);
serverAssert(vptr != NULL);
}
} if (vptr != NULL) {
ret = ziplistGet(vptr, vstr, vlen, vll);
serverAssert(ret);
return ;
} return -;
}

ziplistFind

/* Find pointer to the entry equal to the specified entry. Skip 'skip' entries
* between every comparison. Returns NULL when the field could not be found. */
unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int vlen, unsigned int skip) {
int skipcnt = ;
unsigned char vencoding = ;
long long vll = ; while (p[] != ZIP_END) {
unsigned int prevlensize, encoding, lensize, len;
unsigned char *q; ZIP_DECODE_PREVLENSIZE(p, prevlensize);
ZIP_DECODE_LENGTH(p + prevlensize, encoding, lensize, len);
q = p + prevlensize + lensize; if (skipcnt == ) {
/* Compare current entry with specified entry */
if (ZIP_IS_STR(encoding)) {
if (len == vlen && memcmp(q, vstr, vlen) == ) {
return p;
}
} else {
/* Find out if the searched field can be encoded. Note that
* we do it only the first time, once done vencoding is set
* to non-zero and vll is set to the integer value. */
if (vencoding == ) {
if (!zipTryEncoding(vstr, vlen, &vll, &vencoding)) {
/* If the entry can't be encoded we set it to
* UCHAR_MAX so that we don't retry again the next
* time. */
vencoding = UCHAR_MAX;
}
/* Must be non-zero by now */
assert(vencoding);
} /* Compare current entry with specified entry, do it only
* if vencoding != UCHAR_MAX because if there is no encoding
* possible for the field it can't be a valid integer. */
if (vencoding != UCHAR_MAX) {
long long ll = zipLoadInteger(q, encoding);
if (ll == vll) {
return p;
}
}
} /* Reset skip count */
skipcnt = skip;
} else {
/* Skip entry */
skipcnt--;
} /* Move to next entry */
p = q + len;
} return NULL;
}

hashtable型別的

/* Get the value from a hash table encoded hash, identified by field.
* Returns NULL when the field cannot be found, otherwise the SDS value
* is returned. */
sds hashTypeGetFromHashTable(robj *o, sds field) {
dictEntry *de; serverAssert(o->encoding == OBJ_ENCODING_HT); de = dictFind(o->ptr, field);
if (de == NULL) return NULL;
return dictGetVal(de);
}

dictFInd

dictEntry *dictFind(dict *d, const void *key)
{
dictEntry *he;
uint64_t h, idx, table; if (dictSize(d) == ) return NULL; /* dict is empty */
if (dictIsRehashing(d)) _dictRehashStep(d);
h = dictHashKey(d, key);
for (table = ; table <= ; table++) {
idx = h & d->ht[table].sizemask;
he = d->ht[table].table[idx];
while(he) {
if (key==he->key || dictCompareKeys(d, key, he->key))
return he;
he = he->next;
}
if (!dictIsRehashing(d)) return NULL;
}
return NULL;
}

3.HGETALL、HKEYS、HVALS

HGetAll:返回 key 指定的雜湊集中所有的欄位和值。返回值中,每個欄位名的下一個是它的值,所以返回值的長度是雜湊集大小的兩倍

時間複雜度:O(N)

HKeys:返回 key 指定的雜湊集中所有欄位的名字。

時間複雜度:O(N)

HVals:返回 key 指定的雜湊集中所有欄位的值。

時間複雜度:O(N)

127.0.0.1:> hset myhash field1 "Hello"
(integer)
127.0.0.1:> hset myhash field2 "World"
(integer)
127.0.0.1:> hkeys myhash
) "field1"
) "field2"
127.0.0.1:> hgetall myhash
) "field1"
) "Hello"
) "field2"
) "World"
127.0.0.1:> hvals myhash
) "Hello"
) "World"
127.0.0.1:>

原始碼解析

void hkeysCommand(client *c) {
genericHgetallCommand(c,OBJ_HASH_KEY);
} void hvalsCommand(client *c) {
genericHgetallCommand(c,OBJ_HASH_VALUE);
} void hgetallCommand(client *c) {
genericHgetallCommand(c,OBJ_HASH_KEY|OBJ_HASH_VALUE);
}
void genericHgetallCommand(client *c, int flags) {
robj *o;
hashTypeIterator *hi;
int length, count = ; if ((o = lookupKeyReadOrReply(c,c->argv[],shared.emptymap[c->resp]))
== NULL || checkType(c,o,OBJ_HASH)) return; /* We return a map if the user requested keys and values, like in the
* HGETALL case. Otherwise to use a flat array makes more sense. */
length = hashTypeLength(o);
if (flags & OBJ_HASH_KEY && flags & OBJ_HASH_VALUE) {
addReplyMapLen(c, length);
} else {
addReplyArrayLen(c, length);
} hi = hashTypeInitIterator(o);
while (hashTypeNext(hi) != C_ERR) {
if (flags & OBJ_HASH_KEY) {
addHashIteratorCursorToReply(c, hi, OBJ_HASH_KEY);
count++;
}
if (flags & OBJ_HASH_VALUE) {
addHashIteratorCursorToReply(c, hi, OBJ_HASH_VALUE);
count++;
}
} hashTypeReleaseIterator(hi); /* Make sure we returned the right number of elements. */
if (flags & OBJ_HASH_KEY && flags & OBJ_HASH_VALUE) count /= ;
serverAssert(count == length);
}

4.HLEN

返回key指定的雜湊集包含的欄位的數量。

時間複雜度:O(1)

127.0.0.1:> hlen myhash
(integer)
127.0.0.1:>
void hlenCommand(client *c) {
robj *o; if ((o = lookupKeyReadOrReply(c,c->argv[],shared.czero)) == NULL ||
checkType(c,o,OBJ_HASH)) return; addReplyLongLong(c,hashTypeLength(o));
}
/* Return the number of elements in a hash. */
unsigned long hashTypeLength(const robj *o) {
unsigned long length = ULONG_MAX; if (o->encoding == OBJ_ENCODING_ZIPLIST) {
length = ziplistLen(o->ptr) / ;
} else if (o->encoding == OBJ_ENCODING_HT) {
length = dictSize((const dict*)o->ptr);
} else {
serverPanic("Unknown hash encoding");
}
return length;
}