通过 Java SDK 访问 OSS Tables

更新时间:
复制 MD 格式

Lance Java SDK(org.lance:lance-core)配合 osstables-lance-connector,可在 JVM 应用中直连 OSS Tables catalog,完成建库建表、Arrow 数据写入与读取、行级 DML、索引创建与 compaction 等操作。适用于自定义数据服务与 JVM 侧的数据集成。

前提条件

  • 已在 OSS Tables 中创建 Table Bucket,并获取阿里云AccessKey(AccessKey ID和AccessKey Secret)。

  • 使用 JDK 11 或 JDK 17;JDK 17 需追加 JVM 参数 --add-opens=java.base/java.nio=ALL-UNNAMED。

  • 构建工具 Maven。

步骤一:环境准备

在 Maven 工程中声明连接器与运行时依赖,无需手动下载 JAR:

<dependency>
  <groupId>com.aliyun.osstables</groupId>
  <artifactId>osstables-lance-connector</artifactId>
  <version>1.0.0-rc2</version>
</dependency>
<!-- 数据面 JNI(读写 Lance 数据文件) -->
<dependency>
  <groupId>org.lance</groupId>
  <artifactId>lance-core</artifactId>
  <version>12.0.0</version>
</dependency>
<!-- 必须显式覆盖为连接器配套的 namespace 版本 -->
<dependency>
  <groupId>org.lance</groupId>
  <artifactId>lance-namespace-core</artifactId>
  <version>0.8.6</version>
</dependency>
<dependency>
  <groupId>org.lance</groupId>
  <artifactId>lance-namespace-apache-client</artifactId>
  <version>0.8.6</version>
</dependency>
<!-- arrow-memory-core 必须显式声明为与 lance-core 一致的 18.3.0:不声明时 Maven 会选中
     lance-namespace-core 依赖的旧版 15.0.0,导致创建 RootAllocator 失败。arrow-memory-netty 保持同一版本 -->
<dependency>
  <groupId>org.apache.arrow</groupId>
  <artifactId>arrow-memory-core</artifactId>
  <version>18.3.0</version>
</dependency>
<dependency>
  <groupId>org.apache.arrow</groupId>
  <artifactId>arrow-memory-netty</artifactId>
  <version>18.3.0</version>
  <scope>runtime</scope>
</dependency>

步骤二:配置连接

控制面配置(osstables. 前缀)与数据面配置(storageOptions)均以 Map<String, String> 传入:

import java.util.HashMap;
import java.util.Map;
import org.apache.arrow.memory.RootAllocator;
import org.lance.namespace.LanceNamespace;

Map<String, String> props = new HashMap<>();
props.put("osstables.uri", "https://<tablebucket>-<uid>.cn-beijing-internal.oss-tables.aliyuncs.com/lance");
props.put("osstables.region", "cn-beijing");
props.put("osstables.access_key_id", "<控制面AccessKey ID>");
props.put("osstables.secret_access_key", "<控制面AccessKey Secret>");

Map<String, String> storageOptions = new HashMap<>();
storageOptions.put("access_key_id", "<数据面AccessKey ID>");
storageOptions.put("access_key_secret", "<数据面AccessKey Secret>");
storageOptions.put("endpoint", "https://oss-cn-beijing-internal.aliyuncs.com");
storageOptions.put("region", "cn-beijing");

try (RootAllocator allocator = new RootAllocator()) {
  LanceNamespace ns = LanceNamespace.connect(
      "com.aliyun.osstables.lance.OssTablesNamespace", props, allocator);
  // 在 allocator 关闭前完成步骤三中的全部操作
}

后续示例中的 ns、allocator 和 storageOptions 均指步骤二创建的对象,代码应放在同一个 try 块内执行。

也可先调用一次 OssTablesNamespace.register(),之后用别名 "osstables" 连接。数据面 storageOptions 的键名与含义同 Python SDK。

重要

控制面凭证与数据面凭证相互独立,读写数据时必须同时配置。

步骤三:操作数据

以下示例建库、用 Arrow IPC 数据建表写入与读回,并演示行级 DML、索引创建与 compaction。表标识用 List<String>,如 Arrays.asList("my_db", "my_table")。

建库、写入与读取

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.BigIntVector;
import org.apache.arrow.vector.VarCharVector;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.ipc.ArrowStreamReader;
import org.apache.arrow.vector.ipc.ArrowStreamWriter;
import org.apache.arrow.vector.types.pojo.*;
import org.lance.Dataset;
import org.lance.ReadOptions;
import org.lance.WriteParams;
import org.lance.namespace.model.*;

List<String> tableId = Arrays.asList("my_db", "my_table");

// 建库
ns.createNamespace(new CreateNamespaceRequest().id(Collections.singletonList("my_db")));

// 复用步骤二的 allocator,构造 Arrow 数据并序列化为 IPC 流字节
Schema schema = new Schema(Arrays.asList(
    new Field("id", FieldType.nullable(new ArrowType.Int(64, true)), null),
    new Field("name", FieldType.nullable(new ArrowType.Utf8()), null)));

byte[] ipc;

try (VectorSchemaRoot root = VectorSchemaRoot.create(schema, allocator);
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     ArrowStreamWriter w = new ArrowStreamWriter(root, null, out)) {
  BigIntVector id = (BigIntVector) root.getVector("id");
  VarCharVector name = (VarCharVector) root.getVector("name");
  id.allocateNew(3);
  name.allocateNew(3);
  for (int i = 0; i < 3; i++) {
    id.setSafe(i, i + 1);
    name.setSafe(i, ("row-" + (i + 1)).getBytes(StandardCharsets.UTF_8));
  }
  root.setRowCount(3);
  w.start();
  w.writeBatch();
  w.end();
  ipc = out.toByteArray();
}

// 写入(reader 为任意 ArrowReader)
try (ArrowStreamReader reader = new ArrowStreamReader(new ByteArrayInputStream(ipc), allocator)) {
  Dataset.write()
      .allocator(allocator).reader(reader)
      .namespaceClient(ns).tableId(tableId)
      .mode(WriteParams.WriteMode.CREATE)
      .storageOptions(storageOptions)
      .execute().close();
}

// 读取
try (Dataset ds = Dataset.open()
    .allocator(allocator)
    .namespaceClient(ns).tableId(tableId)
    .readOptions(new ReadOptions.Builder().setStorageOptions(storageOptions).build())
    .build()) {
  System.out.println(ds.countRows());   // 输出 3
}

WriteParams.WriteMode 支持 CREATE(新建)、APPEND(追加)、OVERWRITE(覆盖)等模式。

行级 DML(update / delete / mergeInsert)

行级修改在已打开的 Dataset 上执行。下例复用前文的 tableId、ipc、ns、allocator 和 storageOptions,并在操作结束后关闭数据集。

import java.util.Map;
import org.apache.arrow.c.ArrowArrayStream;
import org.apache.arrow.c.Data;
import org.lance.merge.MergeInsertParams;
import org.lance.update.UpdateParams;

try (Dataset ds = Dataset.open()
    .allocator(allocator)
    .namespaceClient(ns).tableId(tableId)
    .readOptions(new ReadOptions.Builder().setStorageOptions(storageOptions).build())
    .build()) {
  ds.delete("id = 3");

  long updated = ds.update(
      new UpdateParams(Map.of("name", "'updated'")).withWhere("id = 1"))
      .getNumRowsUpdated();

  try (ArrowStreamReader reader = new ArrowStreamReader(new ByteArrayInputStream(ipc), allocator);
       ArrowArrayStream stream = ArrowArrayStream.allocateNew(allocator)) {
    Data.exportArrayStream(allocator, reader, stream);
    MergeInsertParams p = new MergeInsertParams(Collections.singletonList("id"))
        .withMatchedUpdateAll()
        .withNotMatched(MergeInsertParams.WhenNotMatched.InsertAll);
    ds.mergeInsert(p, stream);
  }
}

UpdateParams 中的值是 SQL 表达式;字符串字面量需要保留内层单引号。

说明

delete 会推进当前 Dataset 到新版本,同一实例立即可读到删除后的状态;而 update 和 mergeInsert 的新版本落在返回值(UpdateResult.getDataset() / MergeInsertResult.dataset())中,原 Dataset 不自动推进。因此 update/mergeInsert 后若要读取变更后的数据,请使用返回值中的 Dataset,或重新 Dataset.open()。

catalog 操作

请求/响应模型都在 org.lance.namespace.model 包下,方法名与 Python 一一对应(驼峰命名):

// namespace
ns.namespaceExists(new NamespaceExistsRequest().id(Collections.singletonList("my_db")));
ns.describeNamespace(new DescribeNamespaceRequest().id(Collections.singletonList("my_db")));
ns.listNamespaces(new ListNamespacesRequest().id(Collections.emptyList()));   // 空 id 表示根

// table
ns.tableExists(new TableExistsRequest().id(tableId));
ns.listTables(new ListTablesRequest().id(Collections.singletonList("my_db")));  // 返回裸表名
ns.listAllTables(new ListTablesRequest().id(Collections.emptyList()));          // 跨所有 namespace
ns.describeTable(new DescribeTableRequest().id(tableId).loadDetailedMetadata(true)); // 返回 version/schema/stats

describeTable 的可选参数与 Python 一致:checkDeclared(true)、withTableUri(true)、loadDetailedMetadata(true)。

也可以复用前文由 ArrowStreamWriter 生成的 ipc,经 catalog 创建另一张表(由服务端写入数据):

ns.createTable(new CreateTableRequest().id(Arrays.asList("my_db", "t2")), ipc);

创建索引

Dataset.createIndex(IndexOptions) 创建标量索引与向量索引,IndexOptions.builder(columns, indexType, params) 构造参数,withIndexName(...) 指定索引名。标量索引参数在 org.lance.index.scalar 包下,向量索引参数在 org.lance.index.vector 包下。

前文的 my_table 含 id 列,可直接创建 BTREE:

import java.util.Collections;
import org.lance.index.IndexOptions;
import org.lance.index.IndexParams;
import org.lance.index.IndexType;
import org.lance.index.scalar.BTreeIndexParams;

try (Dataset ds = Dataset.open()
    .allocator(allocator).namespaceClient(ns).tableId(tableId)
    .readOptions(new ReadOptions.Builder().setStorageOptions(storageOptions).build())
    .build()) {
  IndexParams btreeParams = IndexParams.builder()
      .setScalarIndexParams(BTreeIndexParams.builder().build()).build();
  ds.createIndex(IndexOptions.builder(Collections.singletonList("id"), IndexType.BTREE, btreeParams)
      .withIndexName("id_btree").build());
}

以下全文与向量示例使用另一张 search_table,其中 body 为 Utf8,vector 为 64 维 FixedSizeList<Float32>。IVF_PQ 训练需要足够的非空向量,本示例使用 70000 行。先准备示例数据:

import org.apache.arrow.vector.Float4Vector;
import org.apache.arrow.vector.complex.FixedSizeListVector;
import org.apache.arrow.vector.types.FloatingPointPrecision;

int dimension = 64;
int rowCount = 70000;
Field item = new Field("item",
    FieldType.nullable(new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)), null);
Field vectorField = new Field("vector", FieldType.nullable(new ArrowType.FixedSizeList(dimension)),
    Collections.singletonList(item));
Schema searchSchema = new Schema(Arrays.asList(
    new Field("body", FieldType.nullable(new ArrowType.Utf8()), null), vectorField));


byte[] searchIpc;

try (VectorSchemaRoot root = VectorSchemaRoot.create(searchSchema, allocator);
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     ArrowStreamWriter writer = new ArrowStreamWriter(root, null, out)) {
  VarCharVector body = (VarCharVector) root.getVector("body");
  FixedSizeListVector vectors = (FixedSizeListVector) root.getVector("vector");
  body.allocateNew();
  vectors.setInitialCapacity(rowCount);
  vectors.allocateNew();
  Float4Vector values = (Float4Vector) vectors.getDataVector();
  for (int row = 0; row < rowCount; row++) {
    body.setSafe(row, ("the quick brown fox " + row).getBytes(StandardCharsets.UTF_8));
    vectors.setNotNull(row);
    for (int col = 0; col < dimension; col++) {
      values.setSafe(row * dimension + col, ((row * 31 + col * 17) % 1000) / 1000f);
    }
  }
  body.setValueCount(rowCount);
  vectors.setValueCount(rowCount);
  values.setValueCount(rowCount * dimension);
  root.setRowCount(rowCount);
  writer.start();
  writer.writeBatch();
  writer.end();
  searchIpc = out.toByteArray();
}

List<String> searchTableId = Arrays.asList("my_db", "search_table");
try (ArrowStreamReader reader = new ArrowStreamReader(
    new ByteArrayInputStream(searchIpc), allocator)) {
  Dataset.write().allocator(allocator).reader(reader)
      .namespaceClient(ns).tableId(searchTableId)
      .mode(WriteParams.WriteMode.CREATE)
      .storageOptions(storageOptions).execute().close();
}

创建索引:

import org.lance.index.DistanceType;
import org.lance.index.scalar.InvertedIndexParams;
import org.lance.index.vector.VectorIndexParams;

try (Dataset searchDs = Dataset.open()
    .allocator(allocator).namespaceClient(ns).tableId(searchTableId)
    .readOptions(new ReadOptions.Builder().setStorageOptions(storageOptions).build())
    .build()) {
  IndexParams invertedParams = IndexParams.builder().setScalarIndexParams(
      InvertedIndexParams.builder().baseTokenizer("simple").language("English").build()).build();
  searchDs.createIndex(IndexOptions.builder(Collections.singletonList("body"), IndexType.INVERTED,
      invertedParams).withIndexName("body_inv").build());

  IndexParams vectorParams = IndexParams.builder()
      .setVectorIndexParams(VectorIndexParams.ivfPq(4, 8, 8, DistanceType.L2, 256))
      .build();
  searchDs.createIndex(IndexOptions.builder(Collections.singletonList("vector"), IndexType.IVF_PQ,
      vectorParams).withIndexName("vec_idx").build());
}

常用的标量索引类型(IndexType 枚举)有 BTREE、BITMAP、INVERTED、NGRAM、ZONEMAP。

检索(向量检索与全文检索)

建好索引后,用 Dataset.newScan(ScanOptions) 得到 LanceScanner,再 scanBatches() 取 ArrowReader 逐批读取结果。下例继续使用前文含 body 和 64 维 vector 的 search_table。

import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.ipc.ArrowReader;
import org.lance.index.DistanceType;
import org.lance.ipc.FullTextQuery;
import org.lance.ipc.LanceScanner;
import org.lance.ipc.Query;
import org.lance.ipc.ScanOptions;

try (Dataset searchDs = Dataset.open()
    .allocator(allocator).namespaceClient(ns).tableId(searchTableId)
    .readOptions(new ReadOptions.Builder().setStorageOptions(storageOptions).build())
    .build()) {

  float[] key = new float[dimension];

  Query query = new Query.Builder()
      .setColumn("vector").setKey(key).setK(5)
      .setDistanceType(DistanceType.L2).build();
  ScanOptions vectorOptions = new ScanOptions.Builder().nearest(query).limit(5).build();
  try (LanceScanner scanner = searchDs.newScan(vectorOptions);
       ArrowReader reader = scanner.scanBatches()) {
    while (reader.loadNextBatch()) {
      VectorSchemaRoot root = reader.getVectorSchemaRoot();
      System.out.println("vector hits=" + root.getRowCount());
    }
  }

  FullTextQuery fullTextQuery = FullTextQuery.match("fox", "body");
  ScanOptions textOptions = new ScanOptions.Builder()
      .fullTextQuery(fullTextQuery).limit(10).build();
  try (LanceScanner scanner = searchDs.newScan(textOptions);
       ArrowReader reader = scanner.scanBatches()) {
    int rows = 0;
    while (reader.loadNextBatch()) {
      rows += reader.getVectorSchemaRoot().getRowCount();
    }
    System.out.println("fts hits=" + rows);
  }
}

FullTextQuery.match 的参数顺序为 match(queryText, column);向量检索结果包含 _distance 列。

compaction(小文件合并)

多次写入会在表内产生多个 fragment(数据文件),Dataset.compact() 将其合并:

import org.lance.Dataset;

try (Dataset ds = Dataset.open()
    .allocator(allocator).namespaceClient(ns).tableId(tableId)
    .readOptions(new ReadOptions.Builder().setStorageOptions(storageOptions).build())
    .build()) {
  System.out.println(ds.getFragments().size());   // 合并前的 fragment 数
  ds.compact();
}

需要控制目标 fragment 大小时,可使用 org.lance.compaction.CompactionOptions 构造参数后调用 ds.compact(options);默认参数适用于常规小文件合并。

说明

compact() 为 void,合并结果写入新版本;需重新 Dataset.open() 打开数据集才能读到合并后的 fragment 数,当前打开的 Dataset 仍钉扎旧版本。

重命名、注销与删除

以下操作会改变 catalog 或删除数据,请按实际目的选择:

ns.renameTable(new RenameTableRequest().id(tableId).newTableName("my_table_new"));
List<String> renamedTableId = Arrays.asList("my_db", "my_table_new");

仅注销 catalog 元数据并保留底层数据:

ns.deregisterTable(new DeregisterTableRequest().id(renamedTableId));

或者删除数据:

DropTableResponse dropped = ns.dropTable(new DropTableRequest().id(renamedTableId));

删除 Namespace 前,先删除其中的表:

ns.dropTable(new DropTableRequest().id(Arrays.asList("my_db", "t2")));
ns.dropTable(new DropTableRequest().id(searchTableId));
ns.dropNamespace(new DropNamespaceRequest().id(Collections.singletonList("my_db")));
重要

dropTable 会删除数据且不可恢复,请谨慎操作;仅需从 catalog 摘除表定义、保留数据时,请使用 deregisterTable。

注意事项

  • 表名与库名必须使用 ASCII 字符。