博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【译】Redis Hyperloglog 的转换
阅读量:6983 次
发布时间:2019-06-27

本文共 2171 字,大约阅读时间需要 7 分钟。

原文链接:

redis 中一个或多个 hyperloglog 数据进行合并时,结果会以稠密的结构进行存储,占用内存 12k,与之相对的是,以稀疏结构存储的数据(在我的数据库中)平均仅占 200B。

因此我写了个 Lua 脚本,用于将稠密的数据转回稀疏结构

在我的 MacBook Pro (2.4 GHz Intel Core i5) 上,这个脚本每称可转换 182 个 hyperloglog

local function hll_dense2sparse(key)    local exec = redis.call    local sub = string.sub    local byte = string.byte    local char = string.char    local insert = table.insert    local concat = table.concat    local floor = math.floor    local magic = "HYLL"    local dense = exec("GET", key)    if sub(dense, 1, 4) ~= magic then        -- not a hll        return -1    end    if byte(dense, 5) == 1 then        -- already sparse        return 0    end    if #dense ~= 12304 then        -- 12304 = 16 + 16384 * 6 / 8 is the length of a dense hll        return -1    end    local sparse = {magic, char(1), sub(dense, 6, 16)}    local c, v, _v = 1, nil, nil    for i = 0, 16384 do        local offset = i * 6 % 8        local j = (i * 6 - offset) / 8 + 17        local x, y = byte(dense, j, j + 1)        if x then            _v = (floor(x / 2 ^ offset) + (y or 0) * 2 ^ (8 - offset)) % 64        else            _v = nil        end        if _v and _v > 32 then            -- cannot translate to sparse representation            return -2        end        if _v == v then            c = c + 1        else            if v == 0 then                while c >= 16384 do                    insert(sparse, char(127) .. char(255))                    c = c - 16384                end                if c > 64 then                    c = c - 1                    insert(sparse, char(64 + floor(c / 256)) .. char(c % 256))                elseif c > 0 then                    insert(sparse, char(c - 1))                end            elseif v then                v = v - 1                while c >= 4 do                    insert(sparse, char(128 + v * 4 + 3))                    c = c - 4                end                if c > 0 then                    insert(sparse, char(128 + v * 4 + c - 1))                end            end            c, v = 1, _v        end    end    exec("SET", key, concat(sparse))    return 1end复制代码

转载于:https://juejin.im/post/5cc676d2f265da037129a8eb

你可能感兴趣的文章
ES6新特征总结与介绍——声明与表达式
查看>>
python3实现抓取网页资源的 N 种方法(内附200GPython学习资料)
查看>>
不用软件,手动修复双系统引导进win7,xp的多种方法
查看>>
python 访问需要HTTP Basic Authentication认证的资源
查看>>
java中比较字符串的大小用String的compareTo()
查看>>
plist使用
查看>>
Linux RAR 安装和使用
查看>>
【OC】【一秒就会】【collectionView 头部吸住功能】
查看>>
51CTO下载 好资料分享
查看>>
linux 下转换UTC到本地时间
查看>>
Linux的起源与各发行版的基本知识
查看>>
单播包、广播包、组播包、洪泛包
查看>>
iptables命令结构之命令
查看>>
RabbitMQ之Exchange分类
查看>>
综合布线系统的构成
查看>>
计算机硬件 — 计算机简介
查看>>
关于重写session实现的时候可能会导至nginx 502的问题
查看>>
7z(p7zip)压缩软件在Linux下的安装和使用
查看>>
jetbrick-template 1.1.0 发布,支持 #tag, #macro, layout
查看>>
TCP的六个控制位
查看>>