# Vector Search

> 在向量数据库中执行语义搜索。

Source: https://docs.sommatic.ai/zh/nodes/ai.vector.search/

- 标识: `ai.vector.search`
- 类别: AI
- 版本: 1.0.0
- 状态: 实验性. 该节点调用的后端向量检索接口尚未上线，因此无法返回结果。
- 执行方式: async

在向量数据库中执行语义搜索。

查找与查询向量语义相似的记录。它是 RAG 流水线中的核心检索步骤。

**功能特性：**
- **元数据过滤：** 将搜索限定在特定文档内（例如 `{ "user_id": "123" }`）。
- **Top-K：** 精确控制返回结果的数量。
- **度量方式：** 余弦相似度、欧氏距离等（取决于数据库）。

## 配置

- `index` (string, 必填): 向量索引/集合的名称。
- `k` (integer, 可选): 要检索的结果数量。 默认值: `5`.
- `min_score` (number, 可选): 相似度阈值（0.0 - 1.0）。 默认值: `0.7`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): 找到匹配的记录。
- `miss`: 没有高于阈值的匹配。
- `error`: Error

## 输入契约

- `vector` (array<number>, 必填): 要搜索的嵌入向量。
- `filter` (object, 可选): 元数据过滤对象。

## 输出契约

- `hits` (array<object>, 可选)

## 在表达式中

后续节点可通过 `$("Vector Search").item.json.<路径>` 读取此节点输出中的内容（请把 `Vector Search` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Vector Search").item.json.hits` (array) **worker 不返回：读取结果为 undefined.**
- `$("Vector Search").item.json.__port` (string) = `"success"` (编辑器不提示)
- `$("Vector Search").item.json.matches` (array) = `[…] (1)` (编辑器不提示)
- `$("Vector Search").item.json.count` (number) = `1` (编辑器不提示)


## 工作原理

实验性。将 `vector`、`top_k` 和 `filter` 发送到后端尚不存在的向量检索端点，因此该节点目前无法返回结果；调用失败后本次运行也随之失败。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 将传入条目与配置合并，并要求提供 `datasource_id`（而不是已声明的 `index`）和 `vector`；缺少任一项都会抛出异常。
3. 向后端 POST `{ datasource_id, vector, top_k, filter }`（`top_k` 默认 5）。404 会以 `Vector Search service not available on Backend` 抛出。
4. 如果后端成功响应，worker 会返回不含 `port` 的 `{ __port, matches, count }`，引擎会以整个对象作为数据路由到 `out`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-vector-search",
  "label": "Search similar chunks",
  "operator_slug": "ai.vector.search",
  "operator_version": "1.0.0",
  "config": {
    "index": "handbook",
    "datasource_id": "<datasource_id>",
    "top_k": 5
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "out",
  "data": {
    "__port": "success",
    "matches": [
      {
        "id": "doc-001#3",
        "score": 0.83,
        "metadata": {
          "source": "handbook.pdf",
          "page": 12
        },
        "text": "Refunds are processed within 5 business days."
      }
    ],
    "count": 1
  }
}
```

## 输出端口 (代码中的行为)

### `out`

仅当后端端点存在并返回 `success` 时。代码将返回的结构如下：

```json
{
  "__port": "success",
  "matches": [
    {
      "id": "doc-001#3",
      "score": 0.83,
      "metadata": {
        "source": "handbook.pdf",
        "page": 12
      },
      "text": "Refunds are processed within 5 business days."
    }
  ],
  "count": 1
}
```

### `miss`

永远不会触发。没有匹配时代码设置 `__port: "empty"`，引擎会忽略它，仍然路由到 `out`。

### `error`

从不以信封形式返回：所有失败都会抛出异常并使运行失败。

## 代码中的行为

- `datasource_id / top_k`: 代码会读取它们但未声明；`datasource_id` 为必填。请将它们添加到节点配置中。
- `index / k / min_score`: 已声明但被忽略。不会应用任何相似度阈值。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'datasource_id' config. Set a target datasource in the node configuration.` | `error` | 以异常抛出，而不是作为信封返回：引擎会将本次运行标记为失败，除非节点位于 `flow.try` 作用域内，此时错误会进入其 catch 分支。 |
| `Missing 'vector' input. Provide a vector to search with.` | `error` | 以异常抛出，而不是作为信封返回：引擎会将本次运行标记为失败，除非节点位于 `flow.try` 作用域内，此时错误会进入其 catch 分支。 |
| `Vector Search service not available on Backend` | `error` | 后端尚未提供向量检索端点（HTTP 404）。以异常抛出：除非被 `flow.try` 作用域捕获，否则运行失败。 |

## 说明与限制

- 后端尚未实现：没有可调用的向量检索。请勿在生产工作流中使用此节点。
- 后端请求未设置超时。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ai.vector.search",
  "name": "Vector Search",
  "category": "ai",
  "version": "1.0.0",
  "description": "Performs a semantic search against a Vector Database.\n\n  Finds records that are semantically similar to the query vector. Used as the core retrieval step in RAG pipelines.\n\n  **Features:**\n  - **Metadata Filtering:** Restrict search to specific documents (e.g., `{ \"user_id\": \"123\" }`).\n  - **Top-K:** precise control over number of results.\n  - **Metric:** Cosine Similarity, Euclidean Distance, etc. (DB dependent).",
  "capabilities": [
    "vector",
    "search",
    "rag",
    "retrieval"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "index"
    ],
    "properties": {
      "index": {
        "type": "string",
        "title": "Result Index",
        "description": "Name of the Vector Index/Collection."
      },
      "k": {
        "type": "integer",
        "default": 5,
        "title": "Top K",
        "description": "Number of results to retrieve."
      },
      "min_score": {
        "type": "number",
        "default": 0.7,
        "title": "Min Score",
        "description": "Similarity threshold (0.0 - 1.0)."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "vector": {
        "type": "array",
        "items": {
          "type": "number"
        },
        "description": "The embedding vector to search for."
      },
      "filter": {
        "type": "object",
        "description": "Metadata filter object."
      }
    },
    "required": [
      "vector"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "hits": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "id": {
              "type": "string"
            },
            "score": {
              "type": "number"
            },
            "metadata": {
              "type": "object"
            },
            "text": {
              "type": "string",
              "description": "Original text content (if stored)."
            }
          }
        }
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Hits",
      "is_default": true,
      "description": "Found matching records."
    },
    {
      "port_id": "miss",
      "label": "No Results",
      "description": "No matches above threshold."
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "vector",
    "search",
    "pinecone",
    "weaviate"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "index"
  ],
  "properties": {
    "index": {
      "type": "string",
      "title": "Result Index",
      "description": "Name of the Vector Index/Collection."
    },
    "k": {
      "type": "integer",
      "default": 5,
      "title": "Top K",
      "description": "Number of results to retrieve."
    },
    "min_score": {
      "type": "number",
      "default": 0.7,
      "title": "Min Score",
      "description": "Similarity threshold (0.0 - 1.0)."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "vector": {
      "type": "array",
      "items": {
        "type": "number"
      },
      "description": "The embedding vector to search for."
    },
    "filter": {
      "type": "object",
      "description": "Metadata filter object."
    }
  },
  "required": [
    "vector"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "hits": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "score": {
            "type": "number"
          },
          "metadata": {
            "type": "object"
          },
          "text": {
            "type": "string",
            "description": "Original text content (if stored)."
          }
        }
      }
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Hits",
    "is_default": true,
    "description": "Found matching records."
  },
  {
    "port_id": "miss",
    "label": "No Results",
    "description": "No matches above threshold."
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
