python - 如何在python中将元素添加到已排序的redis集中

标签 python django redis

我有一个 Django 应用程序,用户可以上传照片供公众查看和评论。一个要求是上传的照片不能是网站最近看过的照片。为此,我计算了 average (perceptual) hash为上传而呈现的每张图像,将其保存在数据库中。稍后,当张贴新图像时,会将其平均哈希值与 1000 张最新图像的哈希值进行比较。

现在,我想通过将最近的平均哈希值保存在一个排序的 redis 集合 中来加快这个过程,而不是我的 Postgresql 数据库。

我正在尝试弄清楚如何做到这一点。第一步是构建一组 avg 哈希值进行比较,确保集合大小保持在 1000,并包含最新的 1000 个 kay-value 对。

代码会是什么样子?

import redis

POOL = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)

def insertValue(photo_hash):
    my_server = redis.Redis(connection_pool=POOL)
    try:
        size = my_server.zcard("my_set")
        if size < 1001:
            my_server.zadd("my_set", int(time.time() * 1000), photo_hash)    #time.time() equals seconds since epoch
        else:
           #zrem the element with the lowest score, and then ...
           my_server.zadd("my_set", int(time.time() * 1000), photo_hash)    
    except:
        my_server.zadd("my_set", int(time.time() * 1000), photo_hash)

首先zadd 的语法是否正确(我找不到与我正在尝试做的近似的在线 python 示例),其次,如何zrem排序集中得分最低的元素?

请指教。

最佳答案

是的,zadd有点棘手。

NOTE: The order of arguments differs from that of the official ZADD command. For backwards compatability, this method accepts arguments in the form of name1, score1, name2, score2, while the official Redis documents expects score1, name1, score2, name2.

If you’re looking to use the standard syntax, consider using the StrictRedis class. See the API Reference section of the docs for more information.

因为您没有使用 StrictRedis,所以您上面的代码所做的是将名为 time,time()*1000 的元素添加到名为 my_set 的集合中,其值为 photo_hash 这似乎没问题。因为您同时拥有 zrankzscore 函数,它们允许您通过名称或值来检查是否存在。这些操作非常快。比使用 memcached 快得多,因为您需要事先获取整个集合。

与删除元素类似,您可以使用 zremrangebyrankzremrangebyscore 所以本质上您选择什么作为值,您选择什么作为名称以及您选择什么如果两者都是唯一的,那么选择成为值(value)并不是很重要。在您的情况下,它们都可以是唯一的。

我能看到的唯一改进是使用图像的主键而不是时间。因为有可能两个人同时上传一张图片。

关于python - 如何在python中将元素添加到已排序的redis集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38318573/

相关文章:

python - Django 中的非捕获可选 URL 元素

python - docker 撰写 : redis connection refused between containers

python - OpenCV Python : rotate image without cropping sides

Python Anaconda - 命令窗口中出现 "import cx_Oracle"错误

django - 使用 Supervisor 启动 Celery 时如何避免 SECRET_KEY 错误?

redis - StackExchange.Redis - 等待锁的最佳方式

java - Spring Boot Redis 在 dockerized 时出错,但在 maven 运行时不会出错

Python ImageIO 警告 :root:IMAGEIO FFMPEG_WRITER WARNING

python - pytest.ini 值未正确设置

django - 两个独立的 Django 应用程序需要相同的模型