在前面介紹壓縮列表ziplist的時候咱們提到過,zset內部有兩種存儲結構,一種是ziplist,另外一種是跳躍列表skiplist。爲了完全理解zset的內部結構,咱們就再來介紹一下skiplist。node
顧名思義,skiplist本質上是一個有序的多維的list。咱們先回顧一下一維列表是如何進行查找的。git
如上圖,咱們要查找一個元素,就須要從頭節點開始遍歷,直到找到對應的節點或者是第一個大於要查找的元素的節點(沒找到)。時間複雜度爲O(N)。github
這個查找效率是比較低的,若是咱們把列表的某些節點拔高一層,例如把每兩個節點中有一個節點變成兩層。那麼第二層的節點只有第一層的一半,查找效率也就會提升。數組
查找的步驟是從頭節點的頂層開始,查到第一個大於指定元素的節點時,退回上一節點,在下一層繼續查找。app
例如咱們要在上面的列表中查詢16。less
這個例子中遍歷的節點不比一維列表少,可是當節點更多,查找的數字更大時,這種作法的優點就體現出來了。仍是上面的例子,若是咱們要查找的是39,那麼只須要訪問兩個節點(七、39)就能夠找到了。這比一維列表要減小一半的數量。dom
爲了不插入操做的時間複雜度是O(N),skiplist每層的數量不會嚴格按照2:1的比例,而是對每一個要插入的元素隨機一個層數。ide
隨機層數的計算過程以下:函數
Redis中的實現是this
/* Returns a random level for the new skiplist node we are going to create. * The return value of this function is between 1 and ZSKIPLIST_MAXLEVEL * (both inclusive), with a powerlaw-alike distribution where higher * levels are less likely to be returned. */
int zslRandomLevel(void) {
int level = 1;
while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
level += 1;
return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
}
複製代碼
其中ZSKIPLIST_P的值是0.25,存在上一層的機率是1/4,也就是說相對於咱們上面的例子更加扁平化一些。ZSKIPLIST_MAXLEVEL的值是64,即最高容許64層。
Redis中的skiplist是做爲zset的一種內部存儲結構
/* ZSETs use a specialized version of Skiplists */
typedef struct zskiplistNode {
sds ele;
double score;
struct zskiplistNode *backward;
struct zskiplistLevel {
struct zskiplistNode *forward;
unsigned long span;
} level[];
} zskiplistNode;
typedef struct zskiplist {
struct zskiplistNode *header, *tail;
unsigned long length;
int level;
} zskiplist;
typedef struct zset {
dict *dict;
zskiplist *zsl;
} zset;
複製代碼
能夠看到zset是由一個hash和一個skiplist組成。
skiplist的結構包括頭尾指針,長度和當前跳躍列表的層數。
而在zskiplistNode,也就是跳躍列表的節點中包括
瞭解了zset和skiplist的結構以後,咱們就來看一下zset的基本操做的實現。
前面咱們介紹壓縮列表的插入過程的時候就有提到過skiplist的插入,在zsetAdd函數中,Redis對zset的編碼方式進行了判斷,分別處理skiplist和ziplist。ziplist的部分前文已經介紹過了,今天就來看一下skiplist的部分。
if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
zset *zs = zobj->ptr;
zskiplistNode *znode;
dictEntry *de;
de = dictFind(zs->dict,ele);
if (de != NULL) {
/* NX? Return, same element already exists. */
if (nx) {
*flags |= ZADD_NOP;
return 1;
}
curscore = *(double*)dictGetVal(de);
/* Prepare the score for the increment if needed. */
if (incr) {
score += curscore;
if (isnan(score)) {
*flags |= ZADD_NAN;
return 0;
}
if (newscore) *newscore = score;
}
/* Remove and re-insert when score changes. */
if (score != curscore) {
znode = zslUpdateScore(zs->zsl,curscore,ele,score);
/* Note that we did not removed the original element from * the hash table representing the sorted set, so we just * update the score. */
dictGetVal(de) = &znode->score; /* Update score ptr. */
*flags |= ZADD_UPDATED;
}
return 1;
} else if (!xx) {
ele = sdsdup(ele);
znode = zslInsert(zs->zsl,score,ele);
serverAssert(dictAdd(zs->dict,ele,&znode->score) == DICT_OK);
*flags |= ZADD_ADDED;
if (newscore) *newscore = score;
return 1;
} else {
*flags |= ZADD_NOP;
return 1;
}
}
複製代碼
首先是查找對應元素是否存在,若是存在而且沒有參數NX,就記錄下這個元素當前的分數。這裏能夠看出zset中的hash字典是用來根據元素獲取分數的。
接着判斷是否是要執行increment命令,若是是的話,就用當前分數加上指定分數,獲得新的分數newscore。若是分數發生了變化,就調用zslUpdateScore函數,來更新skiplist中的節點,另外還要多一步操做來更新hash字典中的分數。
若是要插入的元素不存在,那麼就直接調用zslInsert函數。
zskiplistNode *zslInsert(zskiplist *zsl, double score, sds ele) {
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
unsigned int rank[ZSKIPLIST_MAXLEVEL];
int i, level;
serverAssert(!isnan(score));
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
/* store rank that is crossed to reach the insert position */
rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
while (x->level[i].forward &&
(x->level[i].forward->score < score ||
(x->level[i].forward->score == score &&
sdscmp(x->level[i].forward->ele,ele) < 0)))
{
rank[i] += x->level[i].span;
x = x->level[i].forward;
}
update[i] = x;
}
/* we assume the element is not already inside, since we allow duplicated * scores, reinserting the same element should never happen since the * caller of zslInsert() should test in the hash table if the element is * already inside or not. */
level = zslRandomLevel();
if (level > zsl->level) {
for (i = zsl->level; i < level; i++) {
rank[i] = 0;
update[i] = zsl->header;
update[i]->level[i].span = zsl->length;
}
zsl->level = level;
}
x = zslCreateNode(level,score,ele);
for (i = 0; i < level; i++) {
x->level[i].forward = update[i]->level[i].forward;
update[i]->level[i].forward = x;
/* update span covered by update[i] as x is inserted here */
x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
update[i]->level[i].span = (rank[0] - rank[i]) + 1;
}
/* increment span for untouched levels */
for (i = level; i < zsl->level; i++) {
update[i]->level[i].span++;
}
x->backward = (update[0] == zsl->header) ? NULL : update[0];
if (x->level[0].forward)
x->level[0].forward->backward = x;
else
zsl->tail = x;
zsl->length++;
return x;
}
複製代碼
函數一開始定義了兩個數組,update數組用來存儲搜索路徑,rank數組用來存儲節點跨度。
第一步操做是找出要插入節點的搜索路徑,而且記錄節點跨度數。
接着開始插入,先隨機一個層數。若是隨機出的層數大於當前的層數,就須要繼續填充update和rank數組,並更新skiplist的最大層數。
而後調用zslCreateNode函數建立新的節點。
建立好節點後,就根據搜索路徑數據提供的位置,從第一層開始,逐層插入節點(更新指針),並其餘節點的span值。
最後還要更新回溯節點,以及將skiplist的長度加一。
這就是插入新元素的整個過程。
瞭解了插入過程之後咱們再回過頭來看更新過程
zskiplistNode *zslUpdateScore(zskiplist *zsl, double curscore, sds ele, double newscore) {
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
int i;
/* We need to seek to element to update to start: this is useful anyway, * we'll have to update or remove it. */
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward &&
(x->level[i].forward->score < curscore ||
(x->level[i].forward->score == curscore &&
sdscmp(x->level[i].forward->ele,ele) < 0)))
{
x = x->level[i].forward;
}
update[i] = x;
}
/* Jump to our element: note that this function assumes that the * element with the matching score exists. */
x = x->level[0].forward;
serverAssert(x && curscore == x->score && sdscmp(x->ele,ele) == 0);
/* If the node, after the score update, would be still exactly * at the same position, we can just update the score without * actually removing and re-inserting the element in the skiplist. */
if ((x->backward == NULL || x->backward->score < newscore) &&
(x->level[0].forward == NULL || x->level[0].forward->score > newscore))
{
x->score = newscore;
return x;
}
/* No way to reuse the old node: we need to remove and insert a new * one at a different place. */
zslDeleteNode(zsl, x, update);
zskiplistNode *newnode = zslInsert(zsl,newscore,x->ele);
/* We reused the old node x->ele SDS string, free the node now * since zslInsert created a new one. */
x->ele = NULL;
zslFreeNode(x);
return newnode;
}
複製代碼
和插入過程同樣,先保存了搜索路徑。而且定位到要更新的節點,若是更新後節點位置不變,則直接返回。不然,就要先調用zslDeleteNode函數刪除該節點,再插入新的節點。
Redis中skiplist的更新過程仍是比較容易理解的,就是先刪除再插入,那麼咱們接下來就看看它是如何刪除節點的。
void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
int i;
for (i = 0; i < zsl->level; i++) {
if (update[i]->level[i].forward == x) {
update[i]->level[i].span += x->level[i].span - 1;
update[i]->level[i].forward = x->level[i].forward;
} else {
update[i]->level[i].span -= 1;
}
}
if (x->level[0].forward) {
x->level[0].forward->backward = x->backward;
} else {
zsl->tail = x->backward;
}
while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
zsl->level--;
zsl->length--;
}
複製代碼
刪除過程的代碼也比較容易理解,首先按照搜索路徑,從下到上,逐層更新前向指針。而後更新回溯指針。若是刪除節點的層數是最大的層數,那麼還須要更新skiplist的level字段。最後長度減一。
skiplist是節點有層級的list,節點的查找過程能夠跨越多個節點,從而節省查找時間。
Redis的zset由hash字典和skiplist組成,hash字典負責數據到分數的對應,skiplist負責根據分數查找數據。
Redis中skiplist插入和刪除操做都依賴於搜索路徑,更新操做是先刪除再插入。
Skip Lists: A Probabilistic Alternative to Balanced Trees