> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dify.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 从知识库检索分段 / 测试检索

> 对知识库执行搜索查询，检索最相关的分段。此接口可用于生产环境检索和测试检索。



## OpenAPI

````yaml /zh/api-reference/openapi_knowledge.json post /datasets/{dataset_id}/retrieve
openapi: 3.0.1
info:
  title: 知识库 API
  description: >-
    用于管理知识库、文档、分段、元数据和标签的 API，包括创建、检索和配置操作。**注意：**单个知识库 API
    密钥有权操作同一账户下所有可见的知识库。请注意数据安全。
  version: 1.0.0
servers:
  - url: https://{api_base_url}
    description: Knowledge API 的基础 URL。自部署时，替换为你的 API 基础 URL。
    variables:
      api_base_url:
        default: api.dify.ai/v1
        description: API 基础 URL 的主机与路径，不含 `https://` 前缀。
security:
  - ApiKeyAuth: []
tags:
  - name: 知识库
    description: 用于管理知识库的操作，包括创建、配置和检索。
  - name: 文档
    description: 用于在知识库中创建、更新和管理文档的操作。
  - name: 分段
    description: 用于管理分段和子分段的操作。
  - name: 元数据
    description: 用于管理知识库元数据字段和文档元数据值的操作。
  - name: 标签
    description: 用于管理知识库标签和标签绑定的操作。
  - name: 模型
    description: 用于获取可用模型的操作。
  - name: 知识流水线
    description: 用于管理和运行知识流水线的操作，包括数据源插件和流水线执行。
paths:
  /datasets/{dataset_id}/retrieve:
    post:
      tags:
        - 知识库
      summary: 从知识库检索分段 / 测试检索
      description: 对知识库执行搜索查询，检索最相关的分段。此接口可用于生产环境检索和测试检索。
      operationId: retrieveSegments
      parameters:
        - name: dataset_id
          in: path
          required: true
          schema:
            type: string
            format: uuid
          description: 知识库 ID。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - query
              properties:
                query:
                  type: string
                  maxLength: 250
                  description: 搜索查询文本。
                retrieval_model:
                  $ref: '#/components/schemas/RetrievalModel'
                  description: 检索模型配置。控制查询此知识库时如何搜索和排序分段。
                external_retrieval_model:
                  type: object
                  description: 外部知识库的检索设置。
                  properties:
                    top_k:
                      type: integer
                      description: 返回的最大结果数。
                    score_threshold:
                      type: number
                      description: 用于过滤结果的最低相关性分数阈值。
                    score_threshold_enabled:
                      type: boolean
                      description: 是否启用分数阈值过滤。
                attachment_ids:
                  type: array
                  items:
                    type: string
                  nullable: true
                  description: 要包含在检索上下文中的附件 ID 列表。
      responses:
        '200':
          description: 检索结果。
          content:
            application/json:
              schema:
                type: object
                properties:
                  query:
                    type: object
                    description: 原始查询对象。
                    properties:
                      content:
                        type: string
                        description: 查询文本。
                  records:
                    type: array
                    items:
                      type: object
                      properties:
                        segment:
                          type: object
                          description: 从知识库中匹配的分段。
                          properties:
                            id:
                              type: string
                              description: 分段的唯一标识符。
                            position:
                              type: integer
                              description: 分段在文档中的位置。
                            document_id:
                              type: string
                              description: 该分段所属文档的 ID。
                            content:
                              type: string
                              description: 分段的文本内容。
                            sign_content:
                              type: string
                              description: 用于完整性验证的签名内容哈希。
                            answer:
                              type: string
                              description: 回答内容，用于问答模式文档。
                            word_count:
                              type: integer
                              description: 分段内容的字数。
                            tokens:
                              type: integer
                              description: 分段内容的令牌数。
                            keywords:
                              type: array
                              description: 与该分段关联的关键词，用于基于关键词的检索。
                              items:
                                type: string
                            index_node_id:
                              type: string
                              description: 向量存储中索引节点的 ID。
                            index_node_hash:
                              type: string
                              description: 索引内容的哈希值，用于检测变更。
                            hit_count:
                              type: integer
                              description: 该分段在检索查询中被匹配的次数。
                            enabled:
                              type: boolean
                              description: 该分段是否启用检索。
                            disabled_at:
                              type: number
                              nullable: true
                              description: 分段被禁用的时间戳。启用时为 `null`。
                            disabled_by:
                              type: string
                              nullable: true
                              description: 禁用该分段的用户 ID。启用时为 `null`。
                            status:
                              type: string
                              description: 分段的索引状态。
                            created_by:
                              type: string
                              description: 创建该分段的用户 ID。
                            created_at:
                              type: number
                              description: 创建时间戳（Unix 纪元，单位为秒）。
                            indexing_at:
                              type: number
                              nullable: true
                              description: 索引开始的时间戳。尚未开始时为 `null`。
                            completed_at:
                              type: number
                              nullable: true
                              description: 索引完成的时间戳。尚未完成时为 `null`。
                            error:
                              type: string
                              nullable: true
                              description: 索引失败时的错误消息。无错误时为 `null`。
                            stopped_at:
                              type: number
                              nullable: true
                              description: 索引停止的时间戳。未停止时为 `null`。
                            document:
                              type: object
                              description: 匹配分段的父文档信息。
                              properties:
                                id:
                                  type: string
                                  description: 文档的唯一标识符。
                                data_source_type:
                                  type: string
                                  description: 文档的创建方式。
                                name:
                                  type: string
                                  description: 文档名称。
                                doc_type:
                                  type: string
                                  nullable: true
                                  description: 文档类型分类。未设置时为 `null`。
                                doc_metadata:
                                  type: object
                                  nullable: true
                                  description: 文档的元数据值。未配置元数据时为 `null`。
                        child_chunks:
                          type: array
                          description: 使用分层索引时，分段内匹配的子分段。
                          items:
                            type: object
                            properties:
                              id:
                                type: string
                                description: 子分段的唯一标识符。
                              content:
                                type: string
                                description: 子分段的文本内容。
                              position:
                                type: integer
                                description: 子分段在父分段中的位置。
                              score:
                                type: number
                                description: 子分段的相关性得分。
                        score:
                          type: number
                          description: 相关性得分。
                        tsne_position:
                          type: object
                          nullable: true
                          description: t-SNE 可视化位置。
                        files:
                          type: array
                          description: 附加到该分段的文件。
                          items:
                            type: object
                            properties:
                              id:
                                type: string
                                description: 附件文件标识符。
                              name:
                                type: string
                                description: 原始文件名。
                              size:
                                type: integer
                                description: 文件大小（字节）。
                              extension:
                                type: string
                                description: 文件扩展名。
                              mime_type:
                                type: string
                                description: 文件的 MIME 类型。
                              source_url:
                                type: string
                                description: 访问附件的 URL。
                        summary:
                          type: string
                          nullable: true
                          description: 通过摘要索引检索到的摘要内容。
                    description: 匹配的检索记录列表。
              examples:
                success:
                  summary: 响应示例
                  value:
                    query:
                      content: What is Dify?
                    records:
                      - segment:
                          id: f3d1c7be-9f3a-40d8-8eb8-3a1ef9c3f2c1
                          position: 1
                          document_id: a8e0e5b5-78c6-4130-a5ce-25feb0e0b4ac
                          content: Dify is an open-source LLM app development platform.
                          sign_content: ''
                          answer: ''
                          word_count: 9
                          tokens: 12
                          keywords:
                            - dify
                            - platform
                            - llm
                          index_node_id: a1b2c3d4-e5f6-7890-abcd-000000000001
                          index_node_hash: abc123def456
                          hit_count: 1
                          enabled: true
                          disabled_at: null
                          disabled_by: null
                          status: completed
                          created_by: ad313dd6-ef04-4dd1-a5b0-c0f0b9e2e7e4
                          created_at: 1741267200
                          indexing_at: 1741267200
                          completed_at: 1741267200
                          error: null
                          stopped_at: null
                          document:
                            id: a8e0e5b5-78c6-4130-a5ce-25feb0e0b4ac
                            data_source_type: upload_file
                            name: guide.txt
                            doc_type: null
                            doc_metadata: null
                        child_chunks: []
                        score: 0.92
                        tsne_position: null
                        files: []
                        summary: null
        '400':
          description: >-
            - `dataset_not_initialized` : 知识库仍在初始化或索引中。请稍候。

            - `provider_not_initialize` : 未找到有效的模型提供商凭据。请前往设置 -> 模型提供商完成凭据配置。

            - `provider_quota_exceeded` : Your quota for Dify Hosted OpenAI has
            been exhausted. Please go to Settings -> Model Provider to complete
            your own provider credentials.

            - `model_currently_not_support` : Dify Hosted OpenAI trial currently
            not support the GPT-4 model.

            - `completion_request_error` : Completion request failed.

            - `invalid_param` : Invalid parameter value.
          content:
            application/json:
              examples:
                dataset_not_initialized:
                  summary: dataset_not_initialized
                  value:
                    status: 400
                    code: dataset_not_initialized
                    message: >-
                      The dataset is still being initialized or indexing. Please
                      wait a moment.
                provider_not_initialize:
                  summary: provider_not_initialize
                  value:
                    status: 400
                    code: provider_not_initialize
                    message: >-
                      No valid model provider credentials found. Please go to
                      Settings -> Model Provider to complete your provider
                      credentials.
                provider_quota_exceeded:
                  summary: provider_quota_exceeded
                  value:
                    status: 400
                    code: provider_quota_exceeded
                    message: >-
                      Your quota for Dify Hosted OpenAI has been exhausted.
                      Please go to Settings -> Model Provider to complete your
                      own provider credentials.
                model_currently_not_support:
                  summary: model_currently_not_support
                  value:
                    status: 400
                    code: model_currently_not_support
                    message: >-
                      Dify Hosted OpenAI trial currently not support the GPT-4
                      model.
                completion_request_error:
                  summary: completion_request_error
                  value:
                    status: 400
                    code: completion_request_error
                    message: Completion request failed.
                invalid_param:
                  summary: invalid_param
                  value:
                    status: 400
                    code: invalid_param
                    message: Invalid parameter value.
        '403':
          description: '`forbidden` : 权限不足。'
          content:
            application/json:
              examples:
                forbidden:
                  summary: forbidden
                  value:
                    status: 403
                    code: forbidden
                    message: Insufficient permissions.
        '404':
          description: '`not_found` : 知识库未找到。'
          content:
            application/json:
              examples:
                not_found:
                  summary: not_found
                  value:
                    status: 404
                    code: not_found
                    message: Dataset not found.
        '500':
          description: '`internal_server_error` : 检索过程中发生内部错误。'
          content:
            application/json:
              examples:
                internal_server_error:
                  summary: internal_server_error
                  value:
                    status: 500
                    code: internal_server_error
                    message: An internal error occurred.
components:
  schemas:
    RetrievalModel:
      type: object
      required:
        - search_method
        - reranking_enable
        - top_k
        - score_threshold_enabled
      properties:
        search_method:
          type: string
          description: 用于检索的搜索方法。
          enum:
            - keyword_search
            - semantic_search
            - full_text_search
            - hybrid_search
        reranking_enable:
          type: boolean
          description: 是否启用重排序。
        reranking_model:
          type: object
          description: 重排序模型配置。
          properties:
            reranking_provider_name:
              type: string
              description: 重排序模型的提供商名称。
            reranking_model_name:
              type: string
              description: 重排序模型名称。
        reranking_mode:
          type: string
          enum:
            - reranking_model
            - weighted_score
          nullable: true
          description: 重排序模式。当 `reranking_enable` 为 `true` 时必填。
        top_k:
          type: integer
          description: 返回的最大结果数。
        score_threshold_enabled:
          type: boolean
          description: 是否启用分数阈值过滤。
        score_threshold:
          type: number
          nullable: true
          description: 结果的最低相关性分数。仅在 `score_threshold_enabled` 为 `true` 时生效。
        weights:
          type: object
          nullable: true
          description: 混合搜索的权重配置。
          properties:
            weight_type:
              type: string
              description: 平衡语义搜索和关键词搜索权重的策略。
              enum:
                - semantic_first
                - keyword_first
                - customized
            vector_setting:
              type: object
              description: 语义搜索权重设置。
              properties:
                vector_weight:
                  type: number
                  description: 分配给语义（向量）搜索结果的权重。
                embedding_provider_name:
                  type: string
                  description: 用于向量搜索的嵌入模型提供商。
                embedding_model_name:
                  type: string
                  description: 用于向量搜索的嵌入模型名称。
            keyword_setting:
              type: object
              description: 关键词搜索权重设置。
              properties:
                keyword_weight:
                  type: number
                  description: 分配给关键词搜索结果的权重。
        metadata_filtering_conditions:
          type: object
          nullable: true
          description: 仅检索文档元数据匹配指定条件的分段。条件由服务端基于文档元数据字段评估。
          properties:
            logical_operator:
              type: string
              enum:
                - and
                - or
              default: and
              nullable: true
              description: 多个条件之间的组合方式。
            conditions:
              type: array
              nullable: true
              description: 要评估的元数据条件列表。
              items:
                type: object
                required:
                  - name
                  - comparison_operator
                properties:
                  name:
                    type: string
                    description: 用于比较的元数据字段名称。
                  comparison_operator:
                    type: string
                    description: >-
                      应用的比较方式。字符串运算符（`contains`、`not contains`、`start with`、`end
                      with`、`is`、`is not`、`empty`、`not empty`、`in`、`not
                      in`）作用于字符串或数组类型的元数据。数值运算符（`=`、`≠`、`>`、`<`、`≥`、`≤`）作用于数值类型的元数据。时间运算符（`before`、`after`）作用于时间类型的元数据。
                    enum:
                      - contains
                      - not contains
                      - start with
                      - end with
                      - is
                      - is not
                      - empty
                      - not empty
                      - in
                      - not in
                      - '='
                      - ≠
                      - '>'
                      - <
                      - ≥
                      - ≤
                      - before
                      - after
                  value:
                    nullable: true
                    description: >-
                      用于比较的值。类型取决于 `comparison_operator`：大多数字符串运算符使用字符串；`in` 和
                      `not in` 使用字符串数组；数值运算符使用数字；`empty` 和 `not empty` 时省略。
                    oneOf:
                      - type: string
                      - type: array
                        items:
                          type: string
                      - type: number
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      bearerFormat: API_KEY
      description: >-
        API Key 认证。对于所有 API 请求，请在 `Authorization` HTTP 头中包含您的 API Key，并加上
        `Bearer ` 前缀。示例：`Authorization: Bearer {API_KEY}`。**强烈建议将 API Key
        存储在服务端，不要在客户端共享或存储，以避免 API Key 泄漏导致严重后果。**

````