搜索索引

搜索索引 API

描述
SearchIndex 主要类,用于在 Redis 中的数据结构之间进行写入、读取和搜索。
AsyncSearchIndex SearchIndex 的异步版本,用于在 Redis 中的数据结构之间进行写入、读取和搜索。

SearchIndex

class SearchIndex(schema, redis_client=None, redis_url=None, connection_args={}, **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")
index.connect(redis_url="redis://#:6379")

# create the index
index.create(overwrite=True)

# 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 (Union *[*redis.Redis , aredis.Redis ] , optional) – 实例化的 redis 客户端。
    • redis_url (str , optional) – 要连接的 Redis 服务器的 URL。
    • connection_args (Dict *[*str , Any ] , optional) – Redis 客户端连接参数。

connect(redis_url=None, **kwargs)

使用提供的 redis_url 连接到 Redis 实例,如果未提供,则回退到 REDIS_URL 环境变量(如果可用)。

注意:可以使用其他关键字参数 (**kwargs) 提供特定于 Redis 连接的额外选项。

  • 参数: redis_url (Optional *[*str ] , optional) – 要连接的 Redis 服务器的 URL。如果未提供,该方法默认使用 REDIS_URL 环境变量。
  • 引发
    • redis.exceptions.ConnectionError – 如果与 Redis 服务器的连接失败。
    • ValueError – 如果未提供 Redis URL,也无法通过 REDIS_URL 环境变量访问。
index.connect(redis_url="redis://#:6379")

create(overwrite=False, drop=False)

使用当前 schema 和属性在 Redis 中创建索引。

  • 参数
    • overwrite (bool , optional) – 如果索引已存在,是否覆盖。默认为 False。
    • drop (bool , optional) – 如果要覆盖,是否删除与索引关联的所有键。默认为 False。
  • 引发
    • RuntimeError – 如果索引已存在且 ‘overwrite’ 为 False。
    • ValueError – 如果未为索引定义任何字段。
  • 返回类型: 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。
  • 引发: redis.exceptions.ResponseError – 如果索引不存在。

disconnect()

断开与 Redis 数据库的连接。

exists()

检查索引是否在 Redis 中存在。

  • 返回值: 如果索引存在,则为 True,否则为 False。
  • 返回类型: bool

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 的字典。
    • connection_args (Dict *[*str , Any ] , optional) – Redis 客户端连接参数。
  • 返回值: 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"}
    ]
})

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")

info()

获取有关索引的信息。

  • 返回值: 包含有关索引的信息的字典。
  • 返回类型: dict

key(id)

将 redis 键构造为索引键前缀(可选)和指定 id 的组合。

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 管道执行中写入的对象数量。默认为类的默认批处理大小。
  • 返回值: 加载到 Redis 的键列表。
  • 返回类型: List[str]
  • 引发: ValueError – 如果提供的键的长度与对象的长度不匹配。
data = [{"test": "foo"}, {"test": "bar"}]

# simple case
keys = index.load(data)

# set 360 second ttl policy on data
keys = index.load(data, ttl=360)

# load data with predefined keys
keys = index.load(data, keys=["rvl:foo", "rvl:bar"])

# load data with preprocessing step
def add_field(d):
    d["new_field"] = 123
    return d
keys = index.load(data, preprocess=add_field)

paginate(query, page_size=30)

对索引执行给定查询,并以分页批次返回结果。

此方法接受 RedisVL 查询实例,允许对结果进行分页,从而允许使用生成器对每个批次进行后续处理。

  • 参数
    • query (BaseQuery) – 要执行的搜索查询。
    • page_size (int , optional) – 每个批次中返回的结果数量。默认为 30。
  • 产出: 生成器生成搜索结果的批次。
  • 引发
    • TypeError – 如果 page_size 参数的类型不是 int。
    • ValueError – 如果 page_size 参数小于或等于零。
  • 返回类型: Generator

示例

以 10 批的形式迭代分页的搜索结果

for result_batch in index.paginate(query, page_size=10)

处理每批结果

pass

注意
page_size 参数控制每个结果批次包含的项数。根据性能考虑因素和预期的搜索结果数量调整此值。

query(query)

对索引执行查询。

此方法直接获取 BaseQuery 对象,运行搜索并处理搜索的后处理。

  • 参数: query (BaseQuery) – 要运行的查询。
  • 返回值: 搜索结果列表。
  • 返回类型: 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)

对索引执行搜索。

redis.search.Search 的包装器,它将索引名称添加到搜索查询中,并将其余参数传递给 redis-py ft.search() 方法。

  • 返回值: 原始 Redis 搜索结果。
  • 返回类型: Result

set_client(client)

手动设置要与搜索索引一起使用的 Redis 客户端。

此方法将搜索索引配置为使用特定的 Redis 或 Async Redis 客户端。它适用于希望使用外部自定义配置的客户端而不是创建新客户端的情况。

  • 参数: client (redis.Redis) – 要用于连接的 Redis 或 Async Redis 客户端实例。
  • 引发: TypeError – 如果提供的客户端无效。
import redis
from redisvl.index import SearchIndex

client = redis.Redis.from_url("redis://#:6379")
index = SearchIndex.from_yaml("schemas/schema.yaml")
index.set_client(client)

property client : Redis | 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_client=None, redis_url=None, connection_args={}, **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")
index.connect(redis_url="redis://#:6379")

# create the index
await index.create(overwrite=True)

# data is an iterable of dictionaries
await index.load(data)

# delete index and data
await index.delete(drop=True)

使用 schema、Redis 客户端(或包含其他连接参数的 URL 字符串)、connection_args 和其他 kwargs 初始化 RedisVL 搜索索引。

  • 参数
    • schema (IndexSchema) – 索引 schema 对象。
    • redis_client (Union *[*redis.Redis , aredis.Redis ] , optional) – 实例化的 redis 客户端。
    • redis_url (str , optional) – 要连接的 Redis 服务器的 URL。
    • connection_args (Dict *[*str , Any ] , optional) – Redis 客户端连接参数。

connect(redis_url=None, **kwargs)

使用提供的 redis_url 连接到 Redis 实例,如果未提供,则回退到 REDIS_URL 环境变量(如果可用)。

注意:可以使用其他关键字参数 (**kwargs) 提供特定于 Redis 连接的额外选项。

  • 参数: redis_url (Optional *[*str ] , optional) – 要连接的 Redis 服务器的 URL。如果未提供,该方法默认使用 REDIS_URL 环境变量。
  • 引发
    • redis.exceptions.ConnectionError – 如果与 Redis 服务器的连接失败。
    • ValueError – 如果未提供 Redis URL,也无法通过 REDIS_URL 环境变量访问。
index.connect(redis_url="redis://#:6379")

async create(overwrite=False, drop=False)

异步在 Redis 中创建具有当前 schema 的索引
和属性。
  • 参数
    • overwrite (bool , optional) – 如果索引已存在,是否覆盖。默认为 False。
    • drop (bool , optional) – 如果要覆盖,是否删除与索引关联的所有键。默认为 False。
  • 引发
    • RuntimeError – 如果索引已存在且 ‘overwrite’ 为 False。
    • ValueError – 如果未为索引定义任何字段。
  • 返回类型: 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)

删除搜索索引。

  • 参数: drop (bool , optional) – 删除索引中的文档。默认为 True。
  • 引发: redis.exceptions.ResponseError – 如果索引不存在。

disconnect()

断开与 Redis 数据库的连接。

async exists()

检查索引是否在 Redis 中存在。

  • 返回值: 如果索引存在,则为 True,否则为 False。
  • 返回类型: bool

async fetch(id)

异步从 Redis 中通过 id 获取对象。id 通常是唯一标识符,或来自某些特定于域的元数据组合(如文档 id 或块 id)。

  • 参数: id (str) – 在 Redis 中索引的特定文档的唯一标识符。
  • 返回值: 获取的对象。
  • 返回类型: Dict[str, Any]

classmethod from_dict(schema_dict, **kwargs)

从字典创建 SearchIndex。

  • 参数
    • schema_dict (Dict *[*str , Any ]) – 包含 schema 的字典。
    • connection_args (Dict *[*str , Any ] , optional) – Redis 客户端连接参数。
  • 返回值: 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"}
    ]
})

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")

async info()

获取有关索引的信息。

  • 返回值: 包含有关索引的信息的字典。
  • 返回类型: dict

key(id)

将 redis 键构造为索引键前缀(可选)和指定 id 的组合。

id 通常是唯一标识符,或来自某些特定于域的元数据组合(如文档 id 或块 id)。

  • 参数: id (str) – 在 Redis 中索引的特定文档的唯一标识符。
  • 返回值: 包含键前缀和值的完整 Redis 键(作为字符串)。
  • 返回类型: str

async listall()

列出 Redis 数据库中的所有搜索索引。

  • 返回值: 数据库中的索引列表。
  • 返回类型: List[str]

async load(data, id_field=None, keys=None, ttl=None, preprocess=None, concurrency=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。
    • concurrency (Optional *[*int ] , optional) – 并发写入操作的最大数量。默认为类的默认并发级别。
  • 返回值: 加载到 Redis 的键列表。
  • 返回类型: List[str]
  • 引发: ValueError – 如果提供的键的长度与对象的长度不匹配。
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
async 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。
  • 产出: 异步生成器生成搜索结果的批次。
  • 引发
    • TypeError – 如果 page_size 参数的类型不是 int。
    • ValueError – 如果 page_size 参数小于或等于零。
  • 返回类型: AsyncGenerator

示例

以 10 批的形式迭代分页的搜索结果

async for result_batch in index.paginate(query, page_size=10)

处理每批结果

pass

注意
page_size 参数控制每个结果批次包含的项数。根据性能考虑因素和预期的搜索结果数量调整此值。

async query(query)

异步对索引执行查询。

此方法直接获取 BaseQuery 对象,运行搜索并处理搜索的后处理。

  • 参数: query (BaseQuery) – 要运行的查询。
  • 返回值: 搜索结果列表。
  • 返回类型: 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(client)

手动设置要与搜索索引一起使用的 Redis 客户端。

此方法将搜索索引配置为使用特定的 Async Redis 客户端。它适用于希望使用外部自定义配置的客户端而不是创建新客户端的情况。

  • 参数: client (aredis.Redis) – 要用于连接的 Async Redis 客户端实例。
  • 引发: TypeError – 如果提供的客户端无效。
import redis.asyncio as aredis
from redisvl.index import AsyncSearchIndex

# async Redis client and index
client = aredis.Redis.from_url("redis://#:6379")
index = AsyncSearchIndex.from_yaml("schemas/schema.yaml")
index.set_client(client)

property client : Redis | Redis | None

底层 redis-py 客户端对象。

property key_separator : str

在形成 Redis 键时,定义的前缀和键值之间的可选分隔符。

property name : str

Redis 搜索索引的名称。

property prefix : str

在形成 Redis 键时,出现在唯一键值之前的可选键前缀。

property storage_type : StorageType

搜索索引的底层存储类型;hash 或 json。

RATE THIS PAGE
Back to top ↑