# Azure - CosmosDB

> 在 Azure CosmosDB NoSQL 容器上执行查询和 CRUD 操作。

Source: https://docs.sommatic.ai/zh/nodes/integrations.microsoft.azure.cosmos/

- 标识: `integrations.microsoft.azure.cosmos`
- 类别: 集成
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

在 Azure CosmosDB NoSQL 容器上执行查询和 CRUD 操作。

连接你的 Azure CosmosDB 账户，自动化数据库操作：运行 SQL 查询、按 ID 读取文档、upsert 记录以及删除条目。

**操作：**
- **Query：** 针对容器执行 SQL 查询，可带参数。
- **Read：** 按 ID 和分区键获取单个文档。
- **Upsert：** 在容器中创建或更新文档。
- **Delete：** 按 ID 和分区键删除文档。

## 配置

- `connection_id` (string, 必填): Azure CosmosDB（SQL API）的凭据。接受 `connection-string`（AccountEndpoint=...;AccountKey=...;）或 `basic-auth`（endpoint + key）类型的凭据。
- `database` (string, 必填, 支持表达式): CosmosDB 数据库名称。
- `container` (string, 必填, 支持表达式): 要操作的容器名称。
- `operation` (string, 可选): 要执行的数据库操作。 默认值: `query`. 可选值: `query`, `read`, `upsert`, `delete`.
- `query` (string, 可选, 支持表达式): 针对容器执行的 SQL 查询（例如“SELECT * FROM c WHERE c.status = @status”）。 显示条件: operation = `query`.
- `parameters` (array, 可选): 用于参数化 SQL 查询的 { name, value } 对象数组。 显示条件: operation = `query`.
- `item` (object, 可选, 支持表达式): 要 upsert 到容器中的文档对象。 显示条件: operation = `upsert`.
- `partitionKey` (string, 可选, 支持表达式): 目标文档的分区键值。 显示条件: operation = `read` | `upsert` | `delete`.

## 输出端口

- `out` (默认): 操作结果或条目
- `error`: 执行期间发生错误

## 输入契约

- `connection_id` (string, 必填)
- `database` (string, 必填)
- `container` (string, 必填)
- `operation` (string, 可选)
- `query` (string, 可选)
- `parameters` (array, 可选)
- `item` (object, 可选)
- `partitionKey` (string, 可选)

## 输出契约

- `result` (object, 可选): Cosmos 响应的 Resource 或 FeedResponse

## 在表达式中

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

- `$("Azure - CosmosDB").item.json.result` (object) = `[…] (1)`: Cosmos 响应的 Resource 或 FeedResponse


## 工作原理

对 Azure Cosmos DB（SQL API）容器执行一次操作：参数化 SQL 查询、点读、upsert 或删除，并将结果放在 `result` 中返回。

1. 解析节点配置中的表达式。`connection_id`、`database`、`container`、`operation`、`query`、`parameters`、`partitionKey` 为空时，从输入项的同名字段读取；`item` 只有在配置中至少包含一个键时才使用配置值。`operation` 默认为 `query`。
2. 从以下来源获取账户 endpoint 和密钥：写在 `connection_id` 中的 `AccountEndpoint=…;AccountKey=…;` 字符串；同格式的 `connection-string` 凭据；或包含 `endpoint` 与 `key`（或 `password` / `accountKey`）的 `basic-auth` / `object` 凭据。
3. 执行操作：`query` 使用 `parameters` 执行 `query` 并读取全部分页；`read` 和 `delete` 以 `item.id` 和 `partitionKey`（默认取 `item.id`）定位文档；`upsert` 写入 `item`。
4. 经 `out` 返回 `{ result }`：`query` 为文档数组，`read` 与 `upsert` 为文档本身，`delete` 为 `{ deleted: true, id }`。失败时以 `{ error }` 经 `error` 返回。

## 在工作流中

### 节点

```json
{
  "node_id": "node-open-orders",
  "label": "Find open orders",
  "operator_slug": "integrations.microsoft.azure.cosmos",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "database": "sales",
    "container": "orders",
    "operation": "query",
    "query": "SELECT * FROM c WHERE c.status = @status",
    "parameters": [
      {
        "name": "@status",
        "value": "open"
      }
    ]
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": [
      {
        "id": "ord_123",
        "status": "open",
        "total": 129.99,
        "_rid": "q7x1AKl0VxsBAAAAAAAAAA==",
        "_etag": "\"0b00a5c1-0000-0100-0000-6745f2b30000\"",
        "_ts": 1764165811
      }
    ]
  },
  "port": "out"
}
```

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

### `out`

操作成功。没有匹配结果的查询也从这里输出，`result` 为 `[]`。

```json
{
  "result": [
    {
      "id": "ord_123",
      "status": "open",
      "total": 129.99,
      "_rid": "q7x1AKl0VxsBAAAAAAAAAA==",
      "_etag": "\"0b00a5c1-0000-0100-0000-6745f2b30000\"",
      "_ts": 1764165811
    }
  ]
}
```

### `error`

校验、凭据解析或 Cosmos 调用失败。

```json
{
  "error": "Query string required for query operation"
}
```

## 代码中的行为

- `item`: `read` 和 `delete` 会使用它（仅取 `id`），`upsert` 使用整个文档。空对象视为未设置，会改用输入项中的 `item` 字段。
- `partitionKey`: `upsert` 会忽略此字段（SDK 从文档中获取分区键）。`read` 和 `delete` 默认取 `item.id`，仅当容器按 `/id` 分区时才正确。
- `parameters`: 由 `{ "name": "@status", "value": "open" }` 对象组成的数组，与 `query` 中的 `@` 占位符对应。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `connection_id is required` | `error` | 配置和输入项中都没有凭据。 |
| `Query string required for query operation` | `error` | `operation` 为 `query`，但 `query` 为空。 |
| `item.id required for <read\|delete>` | `error` | `read` 和 `delete` 需要带 `id` 的 `item`。即使表单只在 upsert 时显示，也请将 `item` 设为 `{ "id": "…" }`。 |
| `item object required for upsert` | `error` | 执行 `upsert` 时未提供文档。 |
| `Unsupported operation: <operation>` | `error` | `operation` 不是 query、read、upsert 或 delete。 |
| `Invalid Cosmos SQL connection string format` | `error` | 连接字符串缺少 `AccountEndpoint=` 或 `AccountKey=`。 |
| `Credential <connection_id> (type '<type>') missing endpoint / key` | `error` | 结构化凭据缺少 endpoint 或密钥。 |

## 说明与限制

- `query` 会将所有分页加载到内存中。对于大型容器，请使用 `TOP` 或 `OFFSET … LIMIT` 限制数量。
- `read` 不存在的文档不会失败：SDK 不返回资源，因此节点经 `out` 输出且 `result` 无值。
- 没有 `empty` 端口，worker 也不额外进行重试。


## 契约（JSON Schema）

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

```json
{
  "slug": "integrations.microsoft.azure.cosmos",
  "name": "Azure - CosmosDB",
  "category": "integrations",
  "group": [
    {
      "key": "microsoft",
      "name": "Microsoft",
      "icon_url": "/icons/integrations/microsoft/microsoft.svg"
    },
    {
      "key": "azure",
      "name": "Azure",
      "icon_url": "/icons/integrations/microsoft/azure.svg"
    }
  ],
  "icon_url": "/icons/integrations/microsoft/azure-cosmos.svg",
  "version": "1.0.0",
  "description": "Execute queries and CRUD operations on Azure CosmosDB NoSQL containers.\n\n  Connect your Azure CosmosDB account and automate database operations — run SQL queries, read documents by ID, upsert records, and delete items.\n\n  **Operations:**\n  - **Query:** Execute a SQL query against a container with optional parameters.\n  - **Read:** Retrieve a single document by its ID and partition key.\n  - **Upsert:** Create or update a document in the container.\n  - **Delete:** Remove a document by its ID and partition key.",
  "capabilities": [
    "nosql",
    "database",
    "cosmos",
    "azure",
    "cloud"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "CosmosDB Credential",
        "description": "Credential for Azure CosmosDB (SQL API). Accepts credentials of type `connection-string` (AccountEndpoint=...;AccountKey=...;) or `basic-auth` (endpoint + key).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "connection-string",
            "basic-auth"
          ],
          "types": [
            "cosmos"
          ]
        }
      },
      "database": {
        "type": "string",
        "title": "Database",
        "description": "Name of the CosmosDB database.",
        "format": "expression"
      },
      "container": {
        "type": "string",
        "title": "Container",
        "description": "Name of the container to operate on.",
        "format": "expression"
      },
      "operation": {
        "type": "string",
        "title": "Operation",
        "enum": [
          "query",
          "read",
          "upsert",
          "delete"
        ],
        "default": "query",
        "description": "The database operation to perform."
      },
      "query": {
        "type": "string",
        "title": "SQL Query",
        "description": "SQL query to execute against the container (e.g., \"SELECT * FROM c WHERE c.status = @status\").",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "query"
            ]
          }
        }
      },
      "parameters": {
        "type": "array",
        "title": "Query Parameters",
        "description": "Array of { name, value } objects for parameterized SQL queries.",
        "displayOptions": {
          "show": {
            "operation": [
              "query"
            ]
          }
        }
      },
      "item": {
        "type": "object",
        "title": "Document",
        "description": "The document object to upsert into the container.",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "upsert"
            ]
          }
        }
      },
      "partitionKey": {
        "type": "string",
        "title": "Partition Key",
        "description": "Partition key value for the target document.",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "read",
              "upsert",
              "delete"
            ]
          }
        }
      }
    },
    "required": [
      "connection_id",
      "database",
      "container"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "database": {
        "type": "string"
      },
      "container": {
        "type": "string"
      },
      "operation": {
        "type": "string"
      },
      "query": {
        "type": "string"
      },
      "parameters": {
        "type": "array"
      },
      "item": {
        "type": "object"
      },
      "partitionKey": {
        "type": "string"
      }
    },
    "required": [
      "connection_id",
      "database",
      "container"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "object",
        "description": "Cosmos response Resource or FeedResponse"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Result",
      "description": "Operation result or items",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Error occurred during execution",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "cloud-io"
  ],
  "tags": [
    "nosql",
    "azure"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://sommatic.ai",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "CosmosDB Credential",
      "description": "Credential for Azure CosmosDB (SQL API). Accepts credentials of type `connection-string` (AccountEndpoint=...;AccountKey=...;) or `basic-auth` (endpoint + key).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "connection-string",
          "basic-auth"
        ],
        "types": [
          "cosmos"
        ]
      }
    },
    "database": {
      "type": "string",
      "title": "Database",
      "description": "Name of the CosmosDB database.",
      "format": "expression"
    },
    "container": {
      "type": "string",
      "title": "Container",
      "description": "Name of the container to operate on.",
      "format": "expression"
    },
    "operation": {
      "type": "string",
      "title": "Operation",
      "enum": [
        "query",
        "read",
        "upsert",
        "delete"
      ],
      "default": "query",
      "description": "The database operation to perform."
    },
    "query": {
      "type": "string",
      "title": "SQL Query",
      "description": "SQL query to execute against the container (e.g., \"SELECT * FROM c WHERE c.status = @status\").",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "query"
          ]
        }
      }
    },
    "parameters": {
      "type": "array",
      "title": "Query Parameters",
      "description": "Array of { name, value } objects for parameterized SQL queries.",
      "displayOptions": {
        "show": {
          "operation": [
            "query"
          ]
        }
      }
    },
    "item": {
      "type": "object",
      "title": "Document",
      "description": "The document object to upsert into the container.",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "upsert"
          ]
        }
      }
    },
    "partitionKey": {
      "type": "string",
      "title": "Partition Key",
      "description": "Partition key value for the target document.",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "read",
            "upsert",
            "delete"
          ]
        }
      }
    }
  },
  "required": [
    "connection_id",
    "database",
    "container"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "database": {
      "type": "string"
    },
    "container": {
      "type": "string"
    },
    "operation": {
      "type": "string"
    },
    "query": {
      "type": "string"
    },
    "parameters": {
      "type": "array"
    },
    "item": {
      "type": "object"
    },
    "partitionKey": {
      "type": "string"
    }
  },
  "required": [
    "connection_id",
    "database",
    "container"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "object",
      "description": "Cosmos response Resource or FeedResponse"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Result",
    "description": "Operation result or items",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Error occurred during execution",
    "is_default": false,
    "supports_condition": false
  }
]
```
