【问题标题】:How would you get the last 10 keys redis?你将如何获得最后 10 个键 redis?
【发布时间】:2013-05-10 12:43:18
【问题描述】:

假设我有一个包含 1,000,000 个键的数据库。有没有办法知道该数据库中的最后 10 个键?

【问题讨论】:

  • 不行,你必须自己实现
  • 你会怎么做呢?
  • 您可以将键存储在列表或排序集中
  • 我明白了。所以我需要制作一个存储所有可用密钥的列表?
  • “最后 10 个键”中的“最后一个”是什么?

标签: database web-applications nosql redis key


【解决方案1】:

您需要使用以下命令将其维护为另一个列表。

Add new key to the front of the list  
LPUSH last10keys key

Retain only the last 10
LTRIM last10keys 0 9

Get the last keys - will return 10 or less
LRANGE mylist 0 9 

【讨论】:

    【解决方案2】:

    如果我不想更改缓存中的任何内容,作为一种解决方法,我会跟踪 AOF 文件以查看那里的最新更改。

    tail -f /var/lib/redis/appendonly.aof

    从那里,您可以看到使用的键、值和命令。

    【讨论】:

    • 这需要在配置文件中将 appendonly 设置为 yes。这不是默认设置。
    【解决方案3】:

    一些命令有[LIMIT offset count],你可以填写并获得有限数量的项目。

    like zrevrangebyscore key +inf 0 LIMIT 0 20,它为您提供排序集中的前 20 个项目。

    【讨论】:

      【解决方案4】:

      您可以使用管道从 Redis 数据库中获取最后插入的密钥或特定密钥

      这是我的代码示例:

      r = redis.StrictRedis(host='localhost', port= 6379, db =0)
      # Day1 hash for 24 hours 
      # Key , Field , Value
      r.hset("31/8/21", "12am", "/home/user/video1.mp4")
      r.hset("31/8/21", "1am", "/home/user/video2.mp4")
      r.hset("31/8/21", "2am", "/home/user/video3.mp4")
      r.hset("31/8/21", "3am", "/home/user/video4.mp4")
      r.hset("31/8/21", "4am", "/home/user/video5.mp4")
      .
      .
      #Created sorted set for all the date hashes into single "date" key
      r.sadd("date", "25/8/21")
      r.sadd("date", "26/8/21")
      r.sadd("date", "27/8/21")
      r.sadd("date", "28/8/21")
      r.sadd("date", "29/8/21")
      r.sadd("date", "30/8/21")
      r.sadd("date", "31/8/21")
      r.save
      
      @app.get("/lastweek")
      def sortweek():
              lastweeklist = r.sort("date", 27, -1, alpha=True) #sorted set key > date
              pipe = r.pipeline()
              for keys in lastweeklist:
                      pipe.hgetall(keys) #hvals
              week1 = []
              for week in pipe.execute():
                      week1.append(week)
              return week1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-25
        • 1970-01-01
        • 1970-01-01
        • 2019-02-21
        • 1970-01-01
        • 2011-07-31
        • 1970-01-01
        • 2010-10-20
        相关资源
        最近更新 更多