Hash collection of Redis (personal notes, with demo)

Introduction

Redis hash is a collection of key-value pairs

Redis hash is a mapping table of string type field and value, hash is especially suitable for storing objects

Similar to Map<String, Object> in Java

basic command

hset command

#给<key>集合中的<field>键赋值<value>
hset <key> <field> <value>
    #写个demo
    hset user:001 id 1
    hset user:001 name zhangsan
    #注意:如果赋值已经存在的field,则覆盖旧的值

hget command

#从<key1>集合<field>取出value
hget <key1> <field>
    #写个demo
    hget user:001 id   #返回1
    hget user:001 name #返回zhangsan 

hmset command

##批量设置hash的值
hmset <key1> <field1> <value1> <field2> <value2>...
    #写个demo
    hmset user:002 id 2 name lisi age 18  #{user:002:{id:2,name:lisi,age:18}}

hexists command

hexists <key1><field>
    #写个demo
    hexists user:001 age  #检查user:001有没有对应field为age

hkeys command

#列出该hash集合的所有field
hkeys <key>
    #写个demo
    hkeys user:001
    #返回结果
    id、name、age

hvals command

#列出该hash集合的所有value
hvals <key>

hincrby command

#为哈希表key中的域field的值加上增量1,这个field的数据类型必须为integer,且increment必须填写,不可缺失
hincrby <key> <field> <increment>
    #写个demo
    hincrby user:002 age 3  #给user:002的年龄增加3

hsetnx command

#将哈希表中的域field的值设置为value,当且仅当域field不存在
hsetnx <key> <field> <value>
	#下面这个语句赋值会失败,因为user:002的age已经存在
	hsetnx user:002 age 18
	#与hset的区别:
	hset对已经存在的field赋值会覆盖旧的值

The data structure used by Hash

There are two data structures corresponding to the Hash type: ziplist (compressed list) and hashtable (hash table). When the field-value length is short and the number is small, use ziplist, otherwise use hashtable

Guess you like

Origin blog.csdn.net/calm_programmer/article/details/127158980