• (七)7-2redis hash类型及其他常用操作


    Hash类型操作
    redis 在内存中存储hash类型是以name对应字典形式存储
    hset(name,key,value)
    name 对应hash中设置一个键值对(不存在,创建;否则,修改)
    hget(name,key)
    name对应的hash中获取根据key的value
    hmset(name,mapping)
    name对应的hash中批量设置键值对
    hmget(name,keys,*args)
    name对应的hash中获取对个key的值
    hgetall(name) 获取name对应hash的所有键值
    hlen(name) 获取name对应的hash中键值的个数
    hkeys(name) 获取name对应的hash中所有的key的值
    hvals(name) 获取name对应的hash中所有的value的值
    hexists(name,key) 检查name对应的hash是否存在当前传入的key
    hdel(name,*keys) 将name对应的hash中指定key的键值对删除
    例子:

    #!/usr/bin/env python 
    #coding:utf8
    import redis
    redis_config = {
    "host" : "192.168.88.100",
    "port":6379,
    "db":0
    }
    
    pool = redis.ConnectionPool(**redis_config)
    r = redis.Redis(connection_pool=pool)
    #hash类型的操作 一个name对应一个字典
    #hset hget hmset hmget
    
    r.hset("dict1","hello","world")
    print(r.hget("dict1","hello"))
    r.hmset("dict1",{"key1":"value1","key2":"value2","key3":"value3"})
    print(r.hmget("dict1","key1","hello"))
    print(r.hgetall("dict1"))
    
    print(r.hlen("dict1"))
    print (r.hkeys("dict1"))
    print(r.hvals("dict1"))
    print(r.hexists("dict1","hello"))
    print(r.hexists("dict1","hello11"))
    r.hdel("dict1","key2")
    print(r.hgetall("dict1"))

    运行结果:

    world
    ['value1', 'world']
    {'key3': 'value3', 'key2': 'value2', 'key1': 'value1', 'hello': 'world'}
    4
    ['hello', 'key3', 'key1', 'key2']
    ['world', 'value3', 'value1', 'value2']
    True
    False
    {'key3': 'value3', 'key1': 'value1', 'hello': 'world'}

    其他常用操作
    delete(*names)
    #根据name删除redis中的任意数据类型
    exists(name)
    #检测redis的name是否存在
    keys(pattern='*')
    #根据* ?等通配符匹配获取redis的name
    expire(name ,time)
    # 为某个name设置超时时间
    rename(src, dst)
    # 重命名
    move(name, db))
    将redis的某个值移动到指定的db下
    # 将redis的某个值移动到指定的db下
    type(name)
    # 获取name对应值的类型
    例子:

    import redis
    redis_config = {
    "host" : "192.168.88.100",
    "port":6379,
    "db":0
    }
    
    pool = redis.ConnectionPool(**redis_config)
    r = redis.Redis(connection_pool=pool)
    print(r.keys())
    r.delete("name1")
    print(r.keys())
    print(r.type("dict1"))
    # r.rename("cnblogs","blog")
    r.rename("blog","cnblogs")
    print(r.keys())
    print(r.exists("blog"))

    运行结果:

    ['set_name', 'dict1', 'name4', 'blog', 'name2', 'name3', 'name1', 'name']
    ['set_name', 'dict1', 'name4', 'blog', 'name2', 'name3', 'name']
    hash
    ['set_name', 'dict1', 'cnblogs', 'name4', 'name2', 'name3', 'name']
    False
  • 相关阅读:
    CentOS配置sshd
    求逆元 HDU 2516
    求逆元
    二分图的最大匹配
    博弈1
    几何多边形面积交模板
    LAMP服务器的搭建
    扩展欧几里得
    cf780c
    利用栈的逆波兰表达式
  • 原文地址:https://www.cnblogs.com/pythonlx/p/7990115.html
Copyright © 2020-2023  润新知