数据表支持使用字符串(String)和二进制(Binary)格式写入向量数据。使用字符串格式时可读性更好且问题调查更方便,使用二进制格式时成本更低。
前提条件
已将图片、视频和文本等内容经过大模型转换成向量数据。更多信息,请参见生成向量。
二进制格式
使用二进制格式存储向量数据占用的磁盘空间更小,向量存储成本更低。在成本敏感且向量维度较大的场景下,推荐通过二进制格式写入向量数据。
通过Binary格式写入向量数据时,需要通过表格存储SDK或者工具将向量转换为二进制数据。
重要
二进制格式写入的向量仍是Float32类型。
向量以二进制格式存储到数据表中,读取时也是二进制数据。如需提升可读性,建议使用工具类将其转换为字符串格式。
通过表格存储SDK转为二进制
说明
自 Java SDK 5.17.6 版本和 Python SDK 6.2.1 版本开始,表格存储支持通过 VectorUtils 工具类进行向量数据的二进制转换。
import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.model.*;
import com.alicloud.openservices.tablestore.model.search.vector.VectorUtils;
import java.util.Random;
import java.util.UUID;
// 生成随机向量的辅助方法。
private static float[] generateRandomFloats(int length, Random random) {
float[] result = new float[length];
for (int i = 0; i < length; i++) {
result[i] = random.nextFloat();
}
return result;
}
// 批量写入数据。
private static void batchWriteRow(SyncClient tableStoreClient) throws Exception {
Random random = new Random();
// 写入 1 千行数据,每 100 行一个批次。
for (int i = 0; i < 10; i++) {
BatchWriteRowRequest batchWriteRowRequest = new BatchWriteRowRequest();
for (int j = 0; j < 100; j++) {
// 用户的业务数据。
String text = "一段字符串,可用户全文检索。同时该字段生成 Embedding 向量,写入到下方 field_vector 字段中进行向量语义相似性查询";
// 转化好的向量,需用户进行转换。
float[] vector = generateRandomFloats(1024,random);
RowPutChange rowPutChange = new RowPutChange("TABLE_NAME");
// 设置主键。
rowPutChange.setPrimaryKey(PrimaryKeyBuilder.createPrimaryKeyBuilder().addPrimaryKeyColumn("PK_1", PrimaryKeyValue.fromString(UUID.randomUUID().toString())).build());
// 设置属性列。
rowPutChange.addColumn("field_string", ColumnValue.fromLong(i));
rowPutChange.addColumn("field_long", ColumnValue.fromLong(i * 100 + j));
rowPutChange.addColumn("field_text", ColumnValue.fromString(text));
// 通过binary格式写入向量数据
rowPutChange.addColumn("field_vector", ColumnValue.fromBinary(VectorUtils.toBytes(vector)));
batchWriteRowRequest.addRowChange(rowPutChange);
}
BatchWriteRowResponse batchWriteRowResponse = tableStoreClient.batchWriteRow(batchWriteRowRequest);
System.out.println("批量写入是否全部成功:" + batchWriteRowResponse.isAllSucceed());
if (!batchWriteRowResponse.isAllSucceed()) {
for (BatchWriteRowResponse.RowResult rowResult : batchWriteRowResponse.getFailedRows()) {
System.out.println("失败的行:" + batchWriteRowRequest.getRowChange(rowResult.getTableName(), rowResult.getIndex()).getPrimaryKey());
System.out.println("失败原因:" + rowResult.getError());
}
}
}
}import time
import tablestore.utils
from tablestore import *
def batch_write_vector(rows_count):
print('Begin prepare data: %d' % rows_count)
batch_write_row_reqs = BatchWriteRowRequest()
put_row_items = []
for i in range(rows_count):
pk = [('PK1', i)]
cols = [('field_string', 'key%03d' % i),
('field_long', i),
('field_text', '一些文本'),
('field_vector', tablestore.utils.VectorUtils.floats_to_bytes([0.1, 0.2, 0.3, 0.4]))]
put_row_item = PutRowItem(Row(pk,cols),Condition(RowExistenceExpectation.IGNORE))
put_row_items.append(put_row_item)
batch_write_row_reqs.add(TableInBatchWriteRowItem(table_name, put_row_items))
client.batch_write_row(batch_write_row_reqs)
print('End prepare data.')
print('Wait for data sync to search index.')
time.sleep(60)通过工具转为二进制
public class VectorUtils {
private static final ByteOrder order = ByteOrder.LITTLE_ENDIAN;
/**
* 将float[]转换为二进制
* @param vector 需要转换的向量
* @return byte 二进制化后的数据
*/
public static byte[] toBytes(float[] vector) {
if (vector == null || vector.length == 0) {
throw new ClientException("vector is null or empty");
}
ByteBuffer buffer = ByteBuffer.allocate(vector.length * 4);
buffer.order(order);
for (float value : vector) {
buffer.putFloat(value);
}
return buffer.array();
}
/**
* 将二进制化后的数据转换回float[]
* @param bytes 二进制化后的数据
* @return Float 原向量
*/
public static float[] toFloats(byte[] bytes) {
int length = bytes.length / 4;
if (bytes.length % 4 != 0 || length == 0) {
throw new ClientException("bytes length is not multiple of 4(SIZE_OF_FLOAT32) or length is 0");
}
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.order(order);
float[] vector = new float[length];
buffer.asFloatBuffer().get(vector);
return vector;
}
}// Float32ToBytes 将[]float32 转换为二进制数组
func Float32ToBytes(vector []float32) ([]byte, error) {
if len(vector) == 0 {
return nil, errors.New("vector is null or empty")
}
data := make([]byte, 4*len(vector))
for i, v := range vector {
binary.LittleEndian.PutUint32(data[i*4:(i+1)*4], math.Float32bits(v))
}
return data, nil
}
// ToFloat32 将二进制数组转回[]float32
func ToFloat32(data []byte) ([]float32, error) {
if data == nil {
return nil, errors.New("bytes is null")
}
if len(data)%4 != 0 || len(data) == 0 {
return nil, errors.New("bytes length is not multiple of 4(SIZE_OF_FLOAT32) or length is 0")
}
floats := make([]float32, len(data)/4)
buf := bytes.NewReader(data)
for i := range floats {
if err := binary.Read(buf, binary.LittleEndian, &floats[i]); err != nil {
return nil, err
}
}
return floats, nil
}class VectorUtils:
# 将floats转换为bytearray
@staticmethod
def floats_to_bytes(floats):
if not isinstance(floats, (list, tuple)) or not all(isinstance(f, float) for f in floats):
raise TypeError("Input must be a list/tuple of floats")
if len(floats) == 0:
raise ValueError("vector is empty")
return bytearray(struct.pack('<' + 'f' * len(floats), *floats))
# 将bytearray转换回floats
@staticmethod
def bytes_to_floats(byte_data):
if not isinstance(byte_data, bytearray):
raise TypeError("Input must be a bytearray object")
num_floats = len(byte_data) // 4
if len(byte_data) % 4 != 0 or num_floats == 0:
raise ValueError("bytes length is not multiple of 4(SIZE_OF_FLOAT32) or length is 0")
floats = struct.unpack('<' + 'f' * num_floats, byte_data)
return list(floats)验证转换的正确性
此处以Java SDK为例验证向量数据与二进制之间的转换是否正确。当转换后的浮点数数组与初始的浮点数数组相同时表示转换正确。
public class VectorUtilsTest {
public static void main(String[] args) {
float[] vector = new float[] { 1, 2, 3, 4 };
byte[] bytes = VectorUtils.toBytes(vector);
System.out.println("转换后的二进制数据:" + Arrays.toString(bytes));
float[] newVector = VectorUtils.toFloats(bytes);
System.out.println("转换后的浮点数数组:" + Arrays.toString(newVector));
}
}字符串格式
使用字符串格式存储向量通常会消耗较多的磁盘空间,但可读性更高。通过字符串格式写入向量数据时,需要将Float32数组(例如[0.1,0.2,0.3,0.4])转换为JSON字符串进行写入。
此处以Java SDK为例介绍字符串格式的向量数据写入操作。
// 批量写入数据。
private static void batchWriteRow(SyncClient tableStoreClient) throws Exception {
// 写入 1 千行数据,每 100 行一个批次。
for (int i = 0; i < 10; i++) {
BatchWriteRowRequest batchWriteRowRequest = new BatchWriteRowRequest();
for (int j = 0; j < 100; j++) {
// 用户的业务数据。
String text = "一段字符串,可用户全文检索。同时该字段生成 Embedding 向量,写入到下方 field_vector 字段中进行向量语义相似性查询";
// 文本转为向量。
String vector = "[1, 2, 3, 4]";
RowPutChange rowPutChange = new RowPutChange("TABLE_NAME");
// 设置主键。
rowPutChange.setPrimaryKey(PrimaryKeyBuilder.createPrimaryKeyBuilder().addPrimaryKeyColumn("PK_1", PrimaryKeyValue.fromString(UUID.randomUUID().toString())).build());
// 设置属性列。
rowPutChange.addColumn("field_string", ColumnValue.fromLong(i));
rowPutChange.addColumn("field_long", ColumnValue.fromLong(i * 100 + j));
rowPutChange.addColumn("field_text", ColumnValue.fromString(text));
// 向量格式为 float32 数组字符串,例如 [1, 5.1, 4.7, 0.08 ]。
rowPutChange.addColumn("field_vector", ColumnValue.fromString(vector));
batchWriteRowRequest.addRowChange(rowPutChange);
}
BatchWriteRowResponse batchWriteRowResponse = tableStoreClient.batchWriteRow(batchWriteRowRequest);
System.out.println("批量写入是否全部成功:" + batchWriteRowResponse.isAllSucceed());
if (!batchWriteRowResponse.isAllSucceed()) {
for (BatchWriteRowResponse.RowResult rowResult : batchWriteRowResponse.getFailedRows()) {
System.out.println("失败的行:" + batchWriteRowRequest.getRowChange(rowResult.getTableName(), rowResult.getIndex()).getPrimaryKey());
System.out.println("失败原因:" + rowResult.getError());
}
}
}
}该文章对您有帮助吗?