hashes类型及操作
Redis hash 是一个string类型的field和value的映射表.它的添加、删除操作都是O(1)平均.hash特别适用于存储对象.相对于讲对象的每个字段存成单个string类型.将一个对象存储在hash类型中会占用更少的内存,并且可以更方便的存取整个对象.省内存的原因是新建一个hash对象时开始用zipmap(又称为small hash)来存储的.这个zipmap其实并不是hash table,但是zipmap相比正常的hash实现可以节省不少hash本身需要的一些元数据存储开销.尽管zipmap的添加,删除,查找都是O(n),但是由于一般对象的field数量都不太多.所以使用zipmap也是很快的,也就是说添加删除平均还是O(1).如果field或者value的大小超出一定限制后,Redis会在内部自动将zipmap替换成正常的hash实现,这个限制可以在配置文件中指定
hash-max-zip-entries 64
配置字段最多64个
hash-max-zipmap-value 512
配置value最大为512字节
hset
设置hash filed为指定值,如果key不存在,则先创建.
heset myhash field1 Hello

hsetnx
设置hash field为指定值,如果key不存在,则先创建.如果field已经存在,则返回0.
hsetnx myhash field "Hello"

第一次执行是成功的,第二次失败,因为field已经存在
hmset
同时设置hash的多个field
hmset myhash field1 Hello field2 World

hget
获取指定的hash field
hget myhash field1

由于数据库没有field3,所以取到的是一个空值nil
hmget
获取全部指定的hash field
hmget myhash field1 field2 field3

hincrby
指定的hash field加上给定值
hset myhash field3 20

hexists
测试指定的field是否存在
hexists myhash field1

hlen
返回指定hash的field数量
hlen myhash

hdel
删除指定hash的field数量
hdel myhash field2

hkeys
返回hash的所有field
hkeys myhash

hvals
返回hash的所有value
hvals myhash

hgetall
获取某个hash中全部的filed及value
hgetall myhash

网友评论