搜索索引类
类 | 描述 |
---|---|
SearchIndex | 用于在 Redis 中写入、读取和搜索数据结构的主要类。 |
AsyncSearchIndex | SearchIndex 的异步版本,用于在 Redis 中写入、读取和搜索数据结构。 |
SearchIndex
class SearchIndex(schema, redis_client=None, redis_url=None, connection_kwargs=None, validate_on_load=False, **kwargs)
用于将 Redis 作为矢量数据库交互的搜索索引类。
SearchIndex 通过引用 Redis 数据库和描述各种设置和字段配置的 IndexSchema(YAML 路径或字典对象)进行实例化。
from redisvl.index import SearchIndex
# initialize the index object with schema from file
index = SearchIndex.from_yaml(
"schemas/schema.yaml",
redis_url="redis://localhost:6379",
validate_on_load=True
)
# create the index
index.create(overwrite=True, drop=False)
# data is an iterable of dictionaries
index.load(data)
# delete index and data
index.delete(drop=True)
使用 schema、Redis 客户端(或带有其他连接参数的 URL 字符串)、connection_args 和其他 kwargs 初始化 RedisVL 搜索索引。
- 参数
- schema (IndexSchema) – 索引 schema 对象。
- redis_client (Optional [ redis.Redis ]) – 一个已实例化的 redis 客户端。
- redis_url (Optional [ str ]) – 要连接的 Redis 服务器的 URL。
- connection_kwargs (Dict [ str , Any ] , optional) – Redis 客户端连接参数。
- validate_on_load (bool , optional) – 加载时是否根据 schema 验证数据。默认为 False。
aggregate(*args, **kwargs)
对索引执行聚合操作。
这是对聚合 API 的包装,它将索引名称添加到查询中,并将其余参数传递给 redis-py 的 ft().aggregate() 方法。
- 返回值: 原始 Redis 聚合结果。
- 返回类型: Result
batch_query(queries, batch_size=10)
执行一批查询并处理结果。
- 参数
- queries (List [ BaseQuery ])
- batch_size (int)
- Return type: List[List[Dict[str, Any]]]
batch_search(queries, batch_size=10)
对索引执行多个查询的搜索。
此方法接受一个查询列表和可选的查询参数,并返回每个查询的 Result 对象列表。结果按与查询相同的顺序返回。
- 参数
- queries (List [ SearchParams ]) – 要搜索的查询。batch_size
- *( *int – 每次搜索的查询数量。默认为 10。
- optional**)** – 每次搜索的查询数量。默认为 10。
- batch_size (int)
- 返回值: 每个查询的搜索结果。
- Return type: List[Result]
clear()
清除与索引关联的 Redis 中的所有键,使索引保持可用状态以便将来进行插入或更新。
- 返回值: 从 Redis 删除的记录数。
- 返回类型: int
connect(redis_url=None, **kwargs)
使用提供的 redis_url 连接到 Redis 实例,如果不可用则回退到 REDIS_URL 环境变量。
注意:可以使用附加关键字参数(**kwargs)来提供特定于 Redis 连接的额外选项。
- 参数: redis_url (Optional [ str ] , optional) – 要连接的 Redis 服务器的 URL。
- 引发
- redis.exceptions.ConnectionError – 如果连接到 Redis 服务器失败。
- ValueError – 如果未提供 Redis URL,也无法通过 REDIS_URL 环境变量访问。
- ModuleNotFoundError – 如果未安装所需的 Redis 模块。
create(overwrite=False, drop=False)
使用当前 schema 和属性在 Redis 中创建索引。
- 参数
- overwrite (bool , optional) – 如果索引已存在,是否覆盖。默认为 False。
- drop (bool , optional) – 在覆盖的情况下,是否删除与索引关联的所有键。默认为 False。
- 引发
- RuntimeError – 如果索引已存在且 ‘overwrite’ 为 False。
- ValueError – 如果未为索引定义任何字段。
- Return type: None
# create an index in Redis; only if one does not exist with given name
index.create()
# overwrite an index in Redis without dropping associated data
index.create(overwrite=True)
# overwrite an index in Redis; drop associated data (clean slate)
index.create(overwrite=True, drop=True)
delete(drop=True)
删除搜索索引,同时可选择删除与索引关联的所有键。
- 参数: drop (bool , optional) – 删除索引中的键/文档对。默认为 True。
- Raises: redis.exceptions.ResponseError – 如果索引不存在。
disconnect()
断开与 Redis 数据库的连接。
drop_keys(keys)
通过键 ID 从索引中移除特定条目或多个条目。
- 参数: keys (Union [ str , List [ str ] ]) – 要从索引中移除的文档 ID 或 ID 列表。
- 返回值: 从 Redis 删除的记录数。
- 返回类型: int
exists()
检查索引是否在 Redis 中存在。
- 返回值: 如果索引存在,则返回 True,否则返回 False。
- 返回类型: bool
expire_keys(keys, ttl)
设置 Redis 中特定条目或多个条目的过期时间。
- 参数
- keys (Union [ str , List [ str ] ]) – 要设置过期时间的条目 ID 或 ID 列表。
- ttl (int) – 生存时间(秒)。
- Return type: int | List[int]
fetch(id)
根据 ID 从 Redis 中获取对象。
ID 通常是唯一的标识符,或者派生自某些领域特定的元数据组合(如文档 ID 或块 ID)。
- 参数: id (str) – Redis 中特定索引文档的唯一标识符。
- 返回值: 获取的对象。
- 返回类型: Dict[str, Any]
classmethod from_dict(schema_dict, **kwargs)
从字典创建 SearchIndex。
- 参数: schema_dict (Dict [ str , Any ]) – 包含 schema 的字典。
- 返回值: 一个 RedisVL SearchIndex 对象。
- 返回类型: SearchIndex
from redisvl.index import SearchIndex
index = SearchIndex.from_dict({
"index": {
"name": "my-index",
"prefix": "rvl",
"storage_type": "hash",
},
"fields": [
{"name": "doc-id", "type": "tag"}
]
}, redis_url="redis://localhost:6379")
classmethod from_existing(name, redis_client=None, redis_url=None, **kwargs)
根据索引名称从 Redis 中的现有搜索索引初始化。
- 参数
- name (str) – Redis 中搜索索引的名称。
- redis_client (Optional [ redis.Redis ]) – 一个已实例化的 redis 客户端。
- redis_url (Optional [ str ]) – 要连接的 Redis 服务器的 URL。
- 引发
- ValueError – 如果未提供 redis_url 或 redis_client。
- RedisModuleVersionError – 如果未安装所需的 Redis 模块。
classmethod from_yaml(schema_path, **kwargs)
从 YAML schema 文件创建 SearchIndex。
- 参数: schema_path (str) – YAML schema 文件路径。
- 返回值: 一个 RedisVL SearchIndex 对象。
- 返回类型: SearchIndex
from redisvl.index import SearchIndex
index = SearchIndex.from_yaml("schemas/schema.yaml", redis_url="redis://localhost:6379")
info(name=None)
获取索引信息。
- 参数: name (str , optional) – 要获取信息的索引名称。默认为 None。
- 返回值: 包含索引信息的字典。
- 返回类型: dict
key(id)
将索引键前缀(可选)和指定 ID 组合构造为 Redis 键。
ID 通常是唯一的标识符,或者派生自某些领域特定的元数据组合(如文档 ID 或块 ID)。
- 参数: id (str) – Redis 中特定索引文档的唯一标识符。
- 返回值: 包括键前缀和值在内的完整 Redis 键字符串。
- 返回类型: str
listall()
列出 Redis 数据库中的所有搜索索引。
- 返回值: 数据库中的索引列表。
- 返回类型: List[str]
load(data, id_field=None, keys=None, ttl=None, preprocess=None, batch_size=None)
将对象加载到 Redis 数据库。返回加载到 Redis 的键列表。
RedisVL 自动处理对象键的构造、批量处理、可选的预处理步骤以及设置键的可选过期时间 (TTL 策略)。
- 参数
- data (Iterable [ Any ]) – 要存储的对象的可迭代对象。
- id_field (Optional [ str ] , optional) – 指定字段用作每个对象 Redis 键(前缀之后)的 ID 部分。默认为 None。
- keys (Optional [ Iterable [ str ] ] , optional) – 可选的键的可迭代对象。如果提供,长度必须与对象长度匹配。默认为 None。
- ttl (Optional [ int ] , optional) – 每个键的生存时间(秒)。默认为 None。
- preprocess (Optional [ Callable ] , optional) – 在存储前预处理对象的函数。默认为 None。
- batch_size (Optional [ int ] , optional) – 在单个 Redis pipeline 执行中写入的对象数量。默认为类的默认批处理大小。
- 返回值: 加载到 Redis 的键列表。
- 返回类型: List[str]
- 引发
- SchemaValidationError – 如果启用 validate_on_load 时验证失败。
- RedisVLError – 如果将数据加载到 Redis 时出错。
paginate(query, page_size=30)
对索引执行给定查询并以分页批次返回结果。
此方法接受一个 RedisVL 查询实例,启用结果的分页,从而可以使用生成器对每个批次进行后续处理。
- 参数
- query (BaseQuery) – 要执行的搜索查询。
- page_size (int , optional) – 每批返回的结果数量。默认为 30。
- Yields: 生成器,生成搜索结果的批次。
- 引发
- TypeError – 如果 page_size 参数不是 int 类型。
- ValueError – 如果 page_size 参数小于或等于零。
- Return type: Generator
# Iterate over paginated search results in batches of 10
for result_batch in index.paginate(query, page_size=10):
# Process each batch of results
pass
注意
page_size 参数控制每个结果批次包含的条目数量。根据性能考虑和预期的搜索结果量调整此值。
query(query)
在索引上执行查询。
此方法直接接受 BaseQuery 或 AggregationQuery 对象,并处理搜索的后处理。
- 参数: query (Union [ BaseQuery , AggregateQuery ]) – 要运行的查询。
- 返回值: 搜索结果列表。
- Return type: List[Result]
from redisvl.query import VectorQuery
query = VectorQuery(
vector=[0.16, -0.34, 0.98, 0.23],
vector_field_name="embedding",
num_results=3
)
results = index.query(query)
search(*args, **kwargs)
对索引执行搜索。
这是对搜索 API 的包装,它将索引名称添加到查询中,并将其余参数传递给 redis-py 的 ft().search() 方法。
- 返回值: 原始 Redis 搜索结果。
- 返回类型: Result
set_client(redis_client, **kwargs)
手动设置用于搜索索引的 Redis 客户端。
此方法配置搜索索引以使用特定的 Redis 或 Async Redis 客户端。对于需要使用外部、自定义配置的客户端而不是创建新客户端的情况非常有用。
- 参数: redis_client (redis.Redis) – 用于连接的 Redis 或 Async Redis 客户端实例。
- Raises: TypeError – 如果提供的客户端无效。
property client: Redis | None
底层的 redis-py 客户端对象。
property key_separator: str
在形成 Redis 键时,定义的前缀和键值之间的可选分隔符。
property name: str
Redis 搜索索引的名称。
property prefix: str
在形成 Redis 键时,唯一键值前面的可选键前缀。
property storage_type: StorageType
搜索索引的底层存储类型;可以是 hash 或 json。
AsyncSearchIndex
class AsyncSearchIndex(schema, *, redis_url=None, redis_client=None, connection_kwargs=None, validate_on_load=False, **kwargs)
用于在异步模式下将 Redis 作为矢量数据库交互的搜索索引类。
AsyncSearchIndex 通过引用 Redis 数据库和描述各种设置和字段配置的 IndexSchema(YAML 路径或字典对象)进行实例化。
from redisvl.index import AsyncSearchIndex
# initialize the index object with schema from file
index = AsyncSearchIndex.from_yaml(
"schemas/schema.yaml",
redis_url="redis://localhost:6379",
validate_on_load=True
)
# create the index
await index.create(overwrite=True, drop=False)
# data is an iterable of dictionaries
await index.load(data)
# delete index and data
await index.delete(drop=True)
使用 schema 初始化 RedisVL 异步搜索索引。
- 参数
- schema (IndexSchema) – 索引 schema 对象。
- redis_url (Optional [ str ] , optional) – 要连接的 Redis 服务器的 URL。
- redis_client (Optional [ aredis.Redis ]) – 一个已实例化的 redis 客户端。
- connection_kwargs (Optional [ Dict [ str , Any ] ]) – Redis 客户端连接参数。
- validate_on_load (bool , optional) – 加载时是否根据 schema 验证数据。默认为 False。
async aggregate(*args, **kwargs)
对索引执行聚合操作。
这是对聚合 API 的包装,它将索引名称添加到查询中,并将其余参数传递给 redis-py 的 ft().aggregate() 方法。
- 返回值: 原始 Redis 聚合结果。
- 返回类型: Result
async batch_query(queries, batch_size=10)
异步执行一批查询并处理结果。
- 参数
- queries (List [ BaseQuery ])
- batch_size (int)
- Return type: List[List[Dict[str, Any]]]
async batch_search(queries, batch_size=10)
对索引执行多个查询的搜索。
此方法接受一个查询列表,并返回每个查询的 Result 对象列表。结果按与查询相同的顺序返回。
- 参数
- queries (List [ SearchParams ]) – 要搜索的查询。batch_size
- *( *int – 每次搜索的查询数量。默认为 10。
- optional**)** – 每次搜索的查询数量。默认为 10。
- batch_size (int)
- 返回值: 每个查询的搜索结果。
- Return type: List[Result]
async clear()
清除与索引关联的 Redis 中的所有键,使索引保持可用状态以便将来进行插入或更新。
- 返回值: 从 Redis 删除的记录数。
- 返回类型: int
connect(redis_url=None, **kwargs)
[已废弃] 连接到 Redis 实例。请在 __init__ 中使用连接参数。
- Parameters: redis_url (str | None)
async create(overwrite=False, drop=False)
- 异步创建具有当前 schema 和属性的 Redis 索引。
- 和属性。
- 参数
- overwrite (bool , optional) – 如果索引已存在,是否覆盖。默认为 False。
- drop (bool , optional) – 在覆盖的情况下,是否删除与索引关联的所有键。默认为 False。
- 引发
- RuntimeError – 如果索引已存在且 ‘overwrite’ 为 False。
- ValueError – 如果未为索引定义任何字段。
- Return type: None
# create an index in Redis; only if one does not exist with given name
await index.create()
# overwrite an index in Redis without dropping associated data
await index.create(overwrite=True)
# overwrite an index in Redis; drop associated data (clean slate)
await index.create(overwrite=True, drop=True)
async delete(drop=True)
删除搜索索引。
- Parameters: drop (bool , optional) – 删除索引中的文档。默认为 True。
- Raises: redis.exceptions.ResponseError – 如果索引不存在。
async disconnect()
断开与 Redis 数据库的连接。
async drop_keys(keys)
通过键 ID 从索引中移除特定条目或多个条目。
- 参数: keys (Union [ str , List [ str ] ]) – 要从索引中移除的文档 ID 或 ID 列表。
- 返回值: 从 Redis 删除的记录数。
- 返回类型: int
async exists()
检查索引是否在 Redis 中存在。
- 返回值: 如果索引存在,则返回 True,否则返回 False。
- 返回类型: bool
async expire_keys(keys, ttl)
设置 Redis 中特定条目或多个条目的过期时间。
- 参数
- keys (Union [ str , List [ str ] ]) – 要设置过期时间的条目 ID 或 ID 列表。
- ttl (int) – 生存时间(秒)。
- Return type: int | List[int]
async fetch(id)
异步根据 ID 从 Redis 获取对象。ID 通常是唯一的标识符,或者派生自某些领域特定的元数据组合(如文档 ID 或块 ID)。
- 参数: id (str) – Redis 中特定索引文档的唯一标识符。
- 返回值: 获取的对象。
- 返回类型: Dict[str, Any]
classmethod from_dict(schema_dict, **kwargs)
从字典创建 SearchIndex。
- 参数: schema_dict (Dict [ str , Any ]) – 包含 schema 的字典。
- 返回值: 一个 RedisVL SearchIndex 对象。
- 返回类型: SearchIndex
from redisvl.index import SearchIndex
index = SearchIndex.from_dict({
"index": {
"name": "my-index",
"prefix": "rvl",
"storage_type": "hash",
},
"fields": [
{"name": "doc-id", "type": "tag"}
]
}, redis_url="redis://localhost:6379")
async classmethod* from_existing(name, redis_client=None, redis_url=None, **kwargs)
根据索引名称从 Redis 中的现有搜索索引初始化。
- 参数
- name (str) – Redis 中搜索索引的名称。
- redis_client (Optional [ redis.Redis ]) – 一个已实例化的 redis 客户端。
- redis_url (Optional [ str ]) – 要连接的 Redis 服务器的 URL。
classmethod from_yaml(schema_path, **kwargs)
从 YAML schema 文件创建 SearchIndex。
- 参数: schema_path (str) – YAML schema 文件路径。
- 返回值: 一个 RedisVL SearchIndex 对象。
- 返回类型: SearchIndex
from redisvl.index import SearchIndex
index = SearchIndex.from_yaml("schemas/schema.yaml", redis_url="redis://localhost:6379")
async info(name=None)
获取索引信息。
- 参数: name (str , optional) – 要获取信息的索引名称。默认为 None。
- 返回值: 包含索引信息的字典。
- 返回类型: dict
key(id)
将索引键前缀(可选)和指定 ID 组合构造为 Redis 键。
ID 通常是唯一的标识符,或者派生自某些领域特定的元数据组合(如文档 ID 或块 ID)。
- 参数: id (str) – Redis 中特定索引文档的唯一标识符。
- 返回值: 包括键前缀和值在内的完整 Redis 键字符串。
- 返回类型: str
async listall()
列出 Redis 数据库中的所有搜索索引。
- 返回值: 数据库中的索引列表。
- 返回类型: List[str]
load(data, id_field=None, keys=None, ttl=None, preprocess=None, concurrency=None, batch_size=None)
异步将对象加载到 Redis。返回加载到 Redis 的键列表。
RedisVL 自动处理对象键的构造、批量处理、可选的预处理步骤以及设置键的可选过期时间 (TTL 策略)。
- 参数
- data (Iterable [ Any ]) – 要存储的对象的可迭代对象。
- id_field (Optional [ str ] , optional) – 指定字段用作每个对象 Redis 键(前缀之后)的 ID 部分。默认为 None。
- keys (Optional [ Iterable [ str ] ] , optional) – 可选的键的可迭代对象。如果提供,长度必须与对象长度匹配。默认为 None。
- ttl (Optional [ int ] , optional) – 每个键的生存时间(秒)。默认为 None。
- preprocess (Optional [ Callable ] , optional) – 在存储前预处理对象的函数。默认为 None。
- batch_size (Optional [ int ] , optional) – 在单个 Redis pipeline 执行中写入的对象数量。默认为类的默认批处理大小。
- concurrency (int | None)
- 返回值: 加载到 Redis 的键列表。
- 返回类型: List[str]
- 引发
- SchemaValidationError – 如果启用 validate_on_load 时验证失败。
- RedisVLError – 如果将数据加载到 Redis 时出错。
data = [{"test": "foo"}, {"test": "bar"}]
# simple case
keys = await index.load(data)
# set 360 second ttl policy on data
keys = await index.load(data, ttl=360)
# load data with predefined keys
keys = await index.load(data, keys=["rvl:foo", "rvl:bar"])
# load data with preprocessing step
def add_field(d):
d["new_field"] = 123
return d
keys = await index.load(data, preprocess=add_field)
async paginate(query, page_size=30)
对索引执行给定查询并以分页批次返回结果。
此方法接受一个 RedisVL 查询实例,启用结果的异步分页,从而可以使用生成器对每个批次进行后续处理。
- 参数
- query (BaseQuery) – 要执行的搜索查询。
- page_size (int , optional) – 每批返回的结果数量。默认为 30。
- Yields: 异步生成器,生成搜索结果的批次。
- 引发
- TypeError – 如果 page_size 参数不是 int 类型。
- ValueError – 如果 page_size 参数小于或等于零。
- Return type: AsyncGenerator
# Iterate over paginated search results in batches of 10
async for result_batch in index.paginate(query, page_size=10):
# Process each batch of results
pass
注意
page_size 参数控制每个结果批次包含的条目数量。根据性能考虑和预期的搜索结果量调整此值。
async query(query)
在索引上异步执行查询。
此方法直接接受 BaseQuery 或 AggregationQuery 对象,运行搜索并处理搜索的后处理。
- 参数: query (Union [ BaseQuery , AggregateQuery ]) – 要运行的查询。
- 返回值: 搜索结果列表。
- Return type: List[Result]
from redisvl.query import VectorQuery
query = VectorQuery(
vector=[0.16, -0.34, 0.98, 0.23],
vector_field_name="embedding",
num_results=3
)
results = await index.query(query)
async search(*args, **kwargs)
在此索引上执行搜索。
这是对 redis.search.Search 的包装,它将索引名称添加到搜索查询中,并将其余参数传递给 redis-py 的 ft.search() 方法。
- 返回值: 原始 Redis 搜索结果。
- 返回类型: Result
set_client(redis_client)
[已废弃] 手动设置用于搜索索引的 Redis 客户端。此方法已废弃;请在 __init__ 中提供连接参数。
- Parameters: redis_client (Redis | Redis)
property client: Redis | None
底层的 redis-py 客户端对象。
property key_separator: str
在形成 Redis 键时,定义的前缀和键值之间的可选分隔符。
property name: str
Redis 搜索索引的名称。
property prefix: str
在形成 Redis 键时,唯一键值前面的可选键前缀。
property storage_type: StorageType
搜索索引的底层存储类型;可以是 hash 或 json。