Redis入门 – 数据类型 – hashes

Redis入门 – 数据类型 – hashes

 

原文地址:http://alanland.iteye.com/admin/blogs/1599419(转载请注明)

 

本文介绍 Redis 的数据类型 hashes,文中的例子在 http://redis.io/commands/ 进行录入的。

 

hashes就像java中的 Mappython中的Dict这样的结构,下面是hashes常用的操作方法。

1添加/设置值

通过 hset 命令来向 hashes 中添加键值对。

> hset 员工地址 张三 张三家

true

> hset 员工地址 李四 李四的地址

true

> hset 员工地址 李四 李四的

false

2获取值

通过 hget 命令获取值。

redis> hget 员工地址 张三

"张三家"

redis> hget 员工地址 李四

"李四的"

redis> hget 员工地址 李六

(nil)

 

如果值不存在则返回控(nil)。

3如果不存在创建,存在则返回

Hsetnx 命令设置不存在的值,如果存在则不进行设置。

redis> hsetnx 员工地址 王舞 XXXXX

(integer) 1

redis> hsetnx 员工地址 李四 XXXXX

(integer) 0

redis> hget 员工地址 王舞

"XXXXX"

redis> hget 员工地址 李四

"李四的"

如果更新成功则返回1,更新失败返回0

4一次设置多个字段

Hmset 命令可以设置同时设置多个字段,用法如下:

redis> hmset 员工地址 alan "alan's home" tom "tom's home"

OK

redis> hget 员工地址 alan

"alan's home"

redis> hget 员工地址 tom

"tom's home"

5一次获取多个字段的值

Hmget 命令可以一次获得多个字段值,用法如下:

redis> hmget 员工地址 alan tom bruce

1) "alan's home"

2) "tom's home"

3) (nil)

由于 bruce 不存在,所以获得空值。

6获取所有元素

redis> hgetall 员工地址

1) "李四"

2) "李四的"

3) "张三"

4) "张三家"

5) "王舞"

6) "XXXXX"

7) "alan"

8) "alan's home"

9) "tom"

10) "tom's home"

7对整数进行增加

redis> hset myhash field 100

(integer) 0

redis> hincrby myhash field 1

(integer) 101

redis> hincrby myhash field 100

(integer) 201

redis> hincrby myhash field -10

(integer) 191

如果这个值不是数字,会报错提示:

redis> hincrby myhash field2 1

ERR hash value is not an integer

如果这个值不存在,会先被设置为0,然后再进行增加操作:

redis> hincrby myhash field3 100

(integer) 100

redis> hget myhash field3

"100"

8对浮点数增加操作

redis> hset myhash field 3.14

(integer) 1

redis> hincrbyfloat myhash field 1.1

"4.24"

9获得key的集合

redis> hset the.hash field.a xxx

(integer) 1

redis> hset the.hash field.b xxx

(integer) 1

redis> hkeys the.hash

1) "field.a"

2) "field.b"

redis>

10获得value的集合

redis> hvals the.hash

1) "xxx"

2) "xxx"

redis>

11获得hashes的长度

redis> hlen the.hash

(integer) 2

猜你喜欢

转载自alanland.iteye.com/blog/1599419