# @datastax/astra-db-ts 中文文档

规范地址：https://npmcn.com/package/%40datastax/astra-db-ts/

版本：2\.3\.0
npm 元数据更新时间：2026-07-15T08:32:35.684Z
中文译文更新时间：2026-11-11T15:08:46.669Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40datastax/astra-db-ts
原文对照：https://npmcn.com/package/%40datastax/astra-db-ts/?lang=original
项目主页：https://github.com/datastax/astra-db-ts
源码仓库：https://github.com/datastax/astra-db-ts

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.4 MB，222 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.0\.0
- 运行依赖：6 个
- 首次发布：2023-10-26T20:16:09.072Z
- 最新版本发布：2026-07-15T08:32:35.449Z
- 近 30 天下载量：268967（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：45（近 12 个月 3 个）

## 中文简介

数据 API TypeScript 客户端

## 安装

```sh
npm install @datastax/astra-db-ts
```

也可以使用：`pnpm add @datastax/astra-db-ts`、`yarn add @datastax/astra-db-ts`、`bun add @datastax/astra-db-ts`

## README

# @ datastax/ astra- db- ts

`astra-db-ts` 是用于交互的 TypeScript 客户端 [数据税 Astra DB](https://astra.datastax.com/signup)。 。 。 .

_这个README目标v2.0.0+,扩展了之前的 1.x API. 点击 [这里](https://github.com/datastax/astra-db-ts/tree/v1.x?tab=readme-ov-file#datastaxastra-db-ts) 对于先前存在的客户端读取._

## 目录

-   [快速启动](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-quickstart)
    -   [收款](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-collections)
    -   [表格](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-tables)
-   [高级别建筑](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-high-level-architecture)
    -   [选项等级](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-options-hierarchy)
-   [数据类型](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-datatypes)
-   [非支助](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-non-astra-support)
-   [浏览器支持](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-browser-support)
-   [使用 HTTP/2](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-using-http2)
-   [实例](https://npmcn.com/package/%40datastax/astra-db-ts/#readme-examples)

## 快速启动

使用您首选的软件包管理器安装 `@datastax/astra-db-ts`。 。 。 .

```bash
npm i @datastax/astra-db-ts # or your favorite package manager's equivalent
```

如果您使用 TypeScript, 您必须至少使用 5. 0.0 版本才能使用 `astra-db-ts 2.0`,因为它使用现代类型脚本特性,例如 `const` 类型参数.

```bash
npm i typescript@^5.0.0
```

拿着 _API 终点_ 还有你的 _应用程序符号_ 用于您的 Astra DB 实例 @ [astra.datastax.com (英语)](https://astra.datastax.com/)。 。 。 .

### 收款

```typescript
import { DataAPIClient, ObjectId, vector, VectorDoc, oid } from '@datastax/astra-db-ts';

// Connect to the db
const client = new DataAPIClient({ logging: 'all' });
const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! });

// The `VectorDoc` interface adds `$vector?: DataAPIVector` as a field to the collection type
interface Dream extends VectorDoc {
  _id: ObjectId,
  summary: string,
  tags?: string[],
}

(async () => {
  // Create the collection with a custom default ID type
  const collection = await db.createCollection<Dream>('dreams', {
    defaultId: { type: 'objectId' },
  });

  // Batch-insert some rows into the table. 
  // _id can be optionally provided, or be auto-generated @ the server side
  await collection.insertMany([{
    summary: 'A dinner on the Moon',
    $vector: vector([0.2, -0.3, -0.5]),
  }, {
    summary: 'Riding the waves',
    $vector: vector([0, 0.2, 1]),
    tags: ['sport'],
  }, {
    _id: oid('674f0f5c1c162131319fa09e'),
    summary: 'Meeting Beethoven at the dentist',
    $vector: vector([0.2, 0.6, 0]),
  }]);

  // Hm, changed my mind
  await collection.updateOne({ _id: oid('674f0f5c1c162131319fa09e') }, {
    $set: { summary: 'Surfers\' paradise' } 
  });

  // Let's see what we've got, by performing a vector search
  const cursor = collection.find({})
    .sort({ vector: vector([0, 0.2, 0.4]) })
    .includeSimilarity(true)
    .limit(2);

  // This would print:
  // - Surfers' paradise: 0.98238194
  // - Friendly aliens in town: 0.91873914
  for await (const result of cursor) {
    console.log(`${result.summary}: ${result.$similarity}`);
  }

  // Cleanup (if desired)
  await collection.drop();
})();
```

### 表格

```typescript
import { DataAPIClient, InferTableSchema, Table, vector } from '@datastax/astra-db-ts';

// Connect to the db
const client = new DataAPIClient({ logging: 'all' });
const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! });

// Define the table's schema so we can infer the type of the table automatically (TS v5.0+)
const DreamsTableSchema = Table.schema({
  columns: {
    id: 'int',
    summary: 'text',
    tags: { type: 'set', valueType: 'text' },
    vector: { type: 'vector', dimension: 3 },
  },
  primaryKey: 'id',
});

// Infer the TS-equivalent type from the table definition (like zod or arktype). Equivalent to:
//
// interface TableSchema {
//   id: number,
//   summary?: string | null,
//   tags?: Set<string>,
//   vector?: DataAPIVector | null,
// }
type Dream = InferTableSchema<typeof DreamsTableSchema>;

(async () => {
  // Create the table if it doesn't already exist
  // Table will be typed as `Table<Dream, { id: number }>`, where the former is the schema, and the latter is the primary key
  const table = await db.createTable('dreams', {
    definition: DreamsTableSchema,
    ifNotExists: true,
  });

  // Create a vector index on the vector column so we can perform ANN searches on the table
  await table.createVectorIndex('dreams_vector_idx', 'vector', {
    options: { metric: 'cosine' },
    ifNotExists: true,
  });

  // Batch-insert some rows into the table
  const rows: Dream[] = [{
    id: 102,
    summary: 'A dinner on the Moon',
    vector: vector([0.2, -0.3, -0.5]),
  }, {
    id: 103,
    summary: 'Riding the waves',
    vector: vector([0, 0.2, 1]),
    tags: new Set(['sport']),
  }, {
    id: 37,
    summary: 'Meeting Beethoven at the dentist',
    vector: vector([0.2, 0.6, 0]),
  }];
  await table.insertMany(rows);

  // Hm, changed my mind
  await table.updateOne({ id: 103 }, {
    $set: { summary: 'Surfers\' paradise' } 
  });

  // Let's see what we've got, by performing a vector search
  const cursor = table.find({})
    .sort({ vector: vector([0, 0.2, 0.4]) })
    .includeSimilarity(true)
    .limit(2);

  // This would print:
  // - Surfers' paradise: 0.98238194
  // - Friendly aliens in town: 0.91873914
  for await (const result of cursor) {
    console.log(`${result.summary}: ${result.$similarity}`);
  }

  // Cleanup (if desired)
  await table.drop();
})();
```

### 今后的步骤

-   分类和方法的ts-doc中给出了更多信息和使用模式
-   [TS 客户参考](https://docs.datastax.com/en/astra/astra-db-vector/clients/typescript.html)
-   [数据 API 参考](https://docs.datastax.com/en/astra/astra-db-vector/api-reference/data-api-commands.html)
-   软件包在 [无](https://www.npmjs.com/package/@datastax/astra-db-ts)

## 高级别建筑

`astra-db-ts`用于在数据层和管理员层工作的抽象结构由本图所描述:

```mermaid
flowchart TD
  DataAPIClient -->|".db(endpoint)"| Db
  DataAPIClient -->|".admin()"| AstraAdmin

  Db --->|".collection(name)
  .createCollection(name)"| Collection

  Db --->|".table(name)
  .createTable(name)"| Table

  AstraAdmin -->|".dbAdmin(endpoint)
  .dbAdmin(id, region)"| DbAdmin

  Db -->|".admin()"| DbAdmin
  DbAdmin -->|".db()"| Db
```

以下是一个面向行政的小例子:

```typescript
import { DataAPIClient } from '@datastax/astra-db-ts';

// Spawn an admin 
const client = new DataAPIClient('*TOKEN*');
const admin = client.admin();

(async () => {
  // list info about all databases
  const databases = await admin.listDatabases();
  const dbInfo = databases[0];
  console.log(dbInfo.name, dbInfo.id, dbInfo.regions);

  // list keyspaces for the first database
  const dbAdmin = admin.dbAdmin(dbInfo.id, dbInfo.regions[0].name);
  console.log(await dbAdmin.listKeyspaces());
})();
```

### 选项等级

和客户端的等级一样,每个类的选项也存在于一个等级中.

家长班的一般选择与子女班的选择紧密结合.

```mermaid
graph TD
  DataAPIClientOptions --> AdminOptions
  DataAPIClientOptions --> DbOptions
  DbOptions --> CollectionOptions
  DbOptions --> TableOptions
```

## 数据类型

见 [数据](https://npmcn.com/package/%40datastax/astra-db-ts/etc/docs/DATATYPES.md) 用于完整列表支持的数据类型及其类型脚本等同.

## 非支助

`astra-db-ts` 官方支持使用非AStra后端的数据 API 实例,例如DSE或HCD上的数据 API.

然而,虽然支持是本地的,但检测不是;您有时必须手动宣布环境.

```typescript
import { DataAPIClient, UsernamePasswordTokenProvider, DataAPIDbAdmin } from '@datastax/astra-db-ts';

// You'll need to pass in environment to the DataAPIClient when not using Astra
const tp = new UsernamePasswordTokenProvider('*USERNAME*', '*PASSWORD*');
const client = new DataAPIClient(tp, { environment: 'dse' });
const db = client.db('*ENDPOINT*');

// A common idiom may be to use `dbAdmin.createKeyspace` with `updateDbKeyspace` to initialize the keyspace when necessary
const dbAdmin = db.admin({ environment: 'dse' });
dbAdmin.createKeyspace('...', { updateDbKeyspace: true });
```

这个 `TokenProvider` 类是一个可扩展的概念,允许您创建甚至刷新您的符号 ,视数据 API 后端而定。 必要时甚至可以省略指指针.

`astra-db-ts` 提供两个 `TokenProvider` 默认实例 :

-   `StaticTokenProvider` - 这个单位提供商只是重新加价 任何信物被传递到它的构造器
-   `UsernamePasswordTokenProvider` - 将用户/通道对对转换成 DSE/HCD 的适当符号

(见 `examples/non-astra-backends` 以充分的例子说明这一点。 )

## 浏览器支持

`astra-db-ts` 设计在服务器侧环境工作,但它也可以在浏览器中技术上工作.

但是,如果出于某种原因,你真想在浏览器中使用这个,你可能需要安装 `events` 混合填充器, 并可能设立CORS代理(例如: [(简体中文) 任何地方](https://github.com/Rob--W/cors-anywhere))向数据API转发请求.

但记住,这可能是非常不安全的, 特别是如果你硬编码敏感数据 进入你的客户端 代码,因为任何人检查代码并取出信使(通过XSS攻击或其他方式)是微不足道的.

见 [`examples/browser`](https://npmcn.com/package/%40datastax/astra-db-ts/examples/browser) 浏览器在操作中的用法,以及如何使用的步骤 `astra-db-ts` 在您的浏览器应用程序中.

## 使用 HTTP/2

`astra-db-ts` 使用本地语言 `fetch` API 默认,但它也可以与 `HTTP/2` 使用 `fetch-h2` 模块.

然而,由于兼容性的原因, `fetch-h2` 默认不再动态导入,必须手动提供给客户端.

幸运的是,只有几步容易走 `HTTP/2` 在您的项目中工作 :

1.  安装 `fetch-h2` 通过运行 `npm i fetch-h2`。 。 。 .
2.  提供 `fetch-h2` 给客户的.

```ts
import * as fetchH2 from 'fetch-h2';
// or `const fetchH2 = require('fetch-h2');`

const client = new DataAPIClient({
  httpOptions: {
    client: 'fetch-h2',
    fetchH2: fetchH2,
  },
});
```

见 [使用 HTTP/2 实例](https://npmcn.com/package/%40datastax/astra-db-ts/examples/using-http2) 并提供更多关于如何使用的信息 `astra-db-ts` 与 `HTTP/2`。 。 。 .

## 实例

看看这个 [实例](https://npmcn.com/package/%40datastax/astra-db-ts/examples) 更多如何使用的实例的目录 `astra-db-ts` 在自己的项目.

## 常见问题

### @datastax/astra-db-ts 是什么？

数据 API TypeScript 客户端

### 如何安装 @datastax/astra-db-ts？

在项目目录运行 npm install @datastax/astra-db-ts，或使用 pnpm add / yarn add / bun add。

### @datastax/astra-db-ts 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @datastax/astra-db-ts 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @datastax/astra-db-ts 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @datastax/astra-db-ts 可以商用吗？

@datastax/astra-db-ts 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @datastax/astra-db-ts 的下载量有多少？

根据 npm 官方下载统计，@datastax/astra-db-ts 在 2026/10/12 – 2026/11/10 这 30 天内被下载 268,967 次，日均约 8,966 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @datastax/astra-db-ts 还在维护吗？

最新版本 2\.3\.0 发布于 2026/07/15（3 个月前）；至今共发布 45 个版本，其中过去 12 个月发布了 3 个；首次发布于 2023/10/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

