You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redisearch模块与redis-py使用咨询:求多字段排序、分页等示例

Redisearch + redis-py 实用示例解答

1. 结合redis-py使用Redisearch模块

先安装依赖:

pip install redis redisearch

以下是索引创建、文档写入与查询的完整示例:

import redis
from redis.commands.search.indexDefinition import IndexDefinition, FieldDefinition
from redis.commands.search.query import Query

# 连接Redis实例
r = redis.Redis(host='localhost', port=6379, db=0)

# 定义可搜索、可排序的字段
fields = [
    FieldDefinition(name='title', type='TEXT', sortable=True),
    FieldDefinition(name='author', type='TEXT', sortable=True),
    FieldDefinition(name='year', type='NUMERIC', sortable=True)
]

# 创建索引(前缀为`book:`的哈希文档会被自动索引)
try:
    r.ft('books_idx').create_index(
        fields,
        definition=IndexDefinition(prefix=['book:'])
    )
except redis.ResponseError:
    # 索引已存在时跳过
    pass

# 写入示例文档
r.hset('book:1', mapping={
    'title': 'The Great Gatsby',
    'author': 'F. Scott Fitzgerald',
    'year': 1925
})
r.hset('book:2', mapping={
    'title': '1984',
    'author': 'George Orwell',
    'year': 1949
})
r.hset('book:3', mapping={
    'title': 'To Kill a Mockingbird',
    'author': 'Harper Lee',
    'year': 1960
})

# 执行基础查询
query = Query('Gatsby').return_fields('title', 'author', 'year')
result = r.ft('books_idx').search(query)
print([doc.__dict__ for doc in result.docs])

2. 按多个字段排序

排序的前提是字段在创建索引时设置了sortable=True,通过sort_by()方法指定多字段排序规则,支持ASC(升序,默认)和DESC(降序):

# 按出版年份降序、作者名字升序排序
query = Query('*').sort_by('year DESC, author ASC')

result = r.ft('books_idx').search(query)
for doc in result.docs:
    print(f"Year: {doc.year}, Author: {doc.author}, Title: {doc.title}")

也可使用链式调用写法:

query = Query('*').sort_by('year', desc=True).sort_by('author', asc=True)

3. 查询结果分页

使用limit(offset, count)方法实现分页,offset为跳过的记录数,count为每页返回的记录数:

page_size = 2

# 第1页(跳过0条,取2条)
page1_query = Query('*').limit(0, page_size)
page1_result = r.ft('books_idx').search(page1_query)
print("第1页结果:")
for doc in page1_result.docs:
    print(doc.title)

# 第2页(跳过2条,取2条)
page2_query = Query('*').limit(2, page_size)
page2_result = r.ft('books_idx').search(page2_query)
print("\n第2页结果:")
for doc in page2_result.docs:
    print(doc.title)

分页可与排序结合,保证分页结果的顺序一致性:

# 排序后分页
sorted_page_query = Query('*').sort_by('year DESC').limit(0, page_size)

内容的提问来源于stack exchange,提问作者Teodor Scorpan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:12:33