架构

RedisVL 中的 Schema 提供了一种结构化格式,用于使用以下三个组件定义索引设置和字段配置

组件 描述
version schema 规范的版本。当前支持的版本是 0.1.0。
index 索引特定设置,例如名称、键前缀、键分隔符和存储类型。
fields 要包含在索引中的数据字段子集以及任何自定义设置。

IndexSchema

class IndexSchema(*, index, fields={}, version='0.1.0')

Redis 搜索索引的 schema 定义,用于 RedisVL 中配置索引设置和组织向量及元数据字段。

该类提供了从 YAML 文件或 Python 字典创建索引 schema 的方法,支持灵活的 schema 定义,易于集成到各种工作流程中。

一个 example.yaml 文件可能看起来像这样

version: '0.1.0'

index:
    name: user-index
    prefix: user
    key_separator: ":"
    storage_type: json

fields:
    - name: user
      type: tag
    - name: credit_score
      type: tag
    - name: embedding
      type: vector
      attrs:
        algorithm: flat
        dims: 3
        distance_metric: cosine
        datatype: float32

从 yaml 加载 RedisVL 的 schema 就像这样简单

from redisvl.schema import IndexSchema

schema = IndexSchema.from_yaml("schema.yaml")

从 dict 加载 RedisVL 的 schema 就像这样简单

from redisvl.schema import IndexSchema

schema = IndexSchema.from_dict({
    "index": {
        "name": "user-index",
        "prefix": "user",
        "key_separator": ":",
        "storage_type": "json",
    },
    "fields": [
        {"name": "user", "type": "tag"},
        {"name": "credit_score", "type": "tag"},
        {
            "name": "embedding",
            "type": "vector",
            "attrs": {
                "algorithm": "flat",
                "dims": 3,
                "distance_metric": "cosine",
                "datatype": "float32"
            }
        }
    ]
})

注意

schema 中的 fields 属性必须包含唯一的字段名,以确保字段引用的正确性和明确性。

通过解析和验证来自关键字参数的输入数据来创建新模型。

如果输入数据无法验证以形成有效模型,则引发 [ValidationError][pydantic_core.ValidationError]。

self 被明确指定为仅位置参数,以便 self 可以作为字段名使用。

  • 参数
    • index (IndexInfo)
    • fields (Dict [ str , BaseField ])
    • version (Literal [ '0.1.0' ])

add_field(field_inputs)

根据指定的字段类型和属性向索引 schema 添加单个字段。

此方法允许向 schema 添加单个字段,提供了定义索引结构的灵活性。

  • 参数: field_inputs (Dict [ str , Any ]) – 要添加的字段。
  • 引发: ValueError – 如果未提供字段名或类型,或名称在 schema 中已存在。
# Add a tag field
schema.add_field({"name": "user", "type": "tag})

# Add a vector field
schema.add_field({
    "name": "user-embedding",
    "type": "vector",
    "attrs": {
        "dims": 1024,
        "algorithm": "flat",
        "datatype": "float32"
    }
})

add_fields(fields)

用附加字段扩展 schema。

此方法允许动态地向索引 schema 添加新字段。它处理字段定义的列表。

  • 参数: fields (List [ Dict [ str , Any ] ]) – 要添加的字段列表。
  • 引发: ValueError – 如果 schema 中已存在同名字段。
schema.add_fields([
    {"name": "user", "type": "tag"},
    {"name": "bio", "type": "text"},
    {
        "name": "user-embedding",
        "type": "vector",
        "attrs": {
            "dims": 1024,
            "algorithm": "flat",
            "datatype": "float32"
        }
    }
])

classmethod from_dict(data)

从字典创建 IndexSchema。

  • 参数: data (Dict [ str , Any ]) – 索引 schema 数据。
  • 返回: 索引 schema。
  • 返回类型: IndexSchema
from redisvl.schema import IndexSchema

schema = IndexSchema.from_dict({
    "index": {
        "name": "docs-index",
        "prefix": "docs",
        "storage_type": "hash",
    },
    "fields": [
        {
            "name": "doc-id",
            "type": "tag"
        },
        {
            "name": "doc-embedding",
            "type": "vector",
            "attrs": {
                "algorithm": "flat",
                "dims": 1536
            }
        }
    ]
})

classmethod from_yaml(file_path)

从 YAML 文件创建 IndexSchema。

  • 参数: file_path (str) – YAML 文件路径。
  • 返回: 索引 schema。
  • 返回类型: IndexSchema
from redisvl.schema import IndexSchema
schema = IndexSchema.from_yaml("schema.yaml")

remove_field(field_name)

根据指定的名称从 schema 中删除字段。

此方法对于通过删除现有字段来动态修改 schema 非常有用。

  • 参数: field_name (str) – 要删除的字段名。

to_dict()

将索引 schema 模型序列化为字典,正确处理 Enum 和其他特殊情况。

  • 返回: 作为字典的索引 schema。
  • 返回类型: Dict[str, Any]

to_yaml(file_path, overwrite=True)

将索引 schema 写入 YAML 文件。

  • 参数
    • file_path (str) – YAML 文件路径。
    • overwrite (bool) – 如果文件已存在是否覆盖。
  • 引发: FileExistsError – 如果文件已存在且 overwrite 为 False。
  • 返回类型: None

property field_names: List[str]

与索引 schema 关联的字段名列表。

  • 返回: schema 中的字段名列表。
  • 返回类型: List[str]

fields: Dict[str, BaseField]

与搜索索引及其属性关联的字段

index: IndexInfo

基本索引配置的详细信息。

model_config: ClassVar[ConfigDict] = {}

模型配置,应为符合 [ConfigDict][pydantic.config.ConfigDict] 的字典。

version: Literal['0.1.0']

底层索引 schema 的版本。

定义字段

schema 中的字段可以以 YAML 格式或 Python 字典形式定义,指定名称、类型、可选路径以及用于自定义的属性。

YAML 示例:

- name: title
  type: text
  path: $.document.title
  attrs:
    weight: 1.0
    no_stem: false
    withsuffixtrie: true

Python 字典示例:

{
    "name": "location",
    "type": "geo",
    "attrs": {
        "sortable": true
    }
}

支持的字段类型和属性

每种字段类型都支持特定的属性,用于自定义其行为。以下是字段类型及其可用属性

文本字段属性:

  • weight: 字段在结果计算中的重要性。
  • no_stem: 在索引期间禁用词干提取。
  • withsuffixtrie: 通过维护后缀树来优化查询。
  • phonetic_matcher: 启用语音匹配。
  • sortable: 允许在此字段上进行排序。

标签字段属性:

  • separator: 将文本拆分为单个标签的字符。
  • case_sensitive: 标签匹配中的大小写敏感性。
  • withsuffixtrie: 查询的后缀树优化。
  • sortable: 基于标签字段启用排序。

数值和地理字段属性:

  • 数值字段和地理字段都支持 sortable 属性,允许在这些字段上进行排序。

通用向量字段属性:

  • dims: 向量的维度。
  • algorithm: 索引算法(flat 或 hnsw)。
  • datatype: 向量的浮点数据类型(bfloat16, float16, float32, float64)。
  • distance_metric: 测量查询相关性的指标(COSINE, L2, IP)。

HNSW 向量字段特定属性:

  • m: 每层每个节点的最大出边数。
  • ef_construction: 构建时的最大边候选数。
  • ef_runtime: 搜索时的最大顶部候选数。
  • epsilon: 范围搜索边界因子。
注意
在此处查看 Redis 支持的字段和选项的完整文档: https://redis.ac.cn/commands/ft.create/
为此页评分
返回顶部 ↑