Blob supports nested types and metadata extensions
The Blob (Binary Large Object) data type stores unstructured binary large objects such as images, audio, videos, and documents, and further provides metadata capabilities and nested type support. Blob writes can carry metadata such as the MIME type and file name, and this metadata can be read through SQL or SDKs. A Blob can be used as a member of ARRAY and STRUCT types, so that a multimodal sample can be expressed more completely in a single table.
Blob overview
This topic describes how to use Blob metadata and nested types, the related SQL functions, and SDK interfaces. For basic concepts, storage modes, and performance benefits of the Blob data type, see Blob data type and multimodal storage.
Prerequisites
Enable the MaxCompute 2.0 data types.
-- Enable MaxCompute 2.0 data types
SET odps.sql.type.system.odps2=true;Delta tables support the Blob type. When creating a table, specify table.format.version='2'.
CREATE TABLE t (
id BIGINT,
content BLOB
) TBLPROPERTIES('table.format.version'='2');Blob reads, writes, and metadata management
Blob metadata describes attributes of Blob content, such as type, size, compression, and storage tier, and is stored in the same object as the Blob binary content. No separate metadata columns are required. Metadata falls into two categories:
User-specified:
filename(file name) andcontent_type(MIME type), specified by theto_blob()function at write time.System-generated:
content_length(content length) andchecksum(checksum value), automatically maintained by MaxCompute during storage.
Use the get_blob_metadata() function to read all of this metadata.
Write metadata: to_blob()
The to_blob() function converts a string or binary value into a Blob object and can attach metadata such as content type and file name during conversion. value supports BINARY and STRING inputs, which are used in the same way. The following table uses BINARY as an example.
Function | Description |
| Converts the entire content to a Blob |
| Converts the content starting at the offset to a Blob |
| Converts the specified length starting at the offset to a Blob |
| Converts to a Blob and records the MIME type |
| Converts to a Blob and records the MIME type and file name |
| Extracts a sub-content and records the MIME type |
| Extracts a sub-content and records the MIME type and file name |
Parameters:
Parameter | Type | Description |
| STRING / BINARY | The content to encapsulate. |
| BIGINT | Start offset, starting from 0. |
| BIGINT | Length to extract. |
| STRING | MIME type of the content, such as |
| STRING | File name, such as |
content_type values:
content_type is specified explicitly by users in to_blob(); MaxCompute does not infer it. The value must follow the RFC type/subtype format and can be empty. Common examples:
Data form | content_type |
PNG image |
|
JPEG image |
|
MP4 video |
|
WAV audio |
|
PDF document |
|
JSON text |
|
Plain text / logs |
|
HTML fragment |
|
Unknown binary |
|
Automatic compression for text types
For Blobs with text MIME types (such as text/plain, text/html, and application/json), MaxCompute automatically compresses data on write and decompresses data on access, saving about 5x storage space on average. This process is transparent to SQL and SDKs. To obtain compression benefits for text corpora, explicitly specify the MIME type in to_blob(), that is, set the correct content_type.
Usage notes:
When
offsetorlengthis not specified, the values are equivalent tooffset=0andlength=-1, which encapsulates the entire content.When
length>=0, the actual write length ismin(remaining input length, length).When
offsetexceeds the input length, a Blob with empty content is returned.If
valueis NULL, NULL is returned. Ifoffsetorlengthis NULL, NULL is returned.If
content_typeorfilenameis NULL, the corresponding metadata is treated as not set.content_typemust follow the RFCtype/subtypeformat.offsetcannot be negative; otherwise, a runtime error occurs.
Example:
-- Create a Blob from a string
SELECT to_blob('hello world');
-- Create a Blob from hexadecimal binary
SELECT to_blob(X'89504E47'); -- PNG file header
-- Extract with an offset
SELECT to_blob('hello world', 6); -- Result: 'world'
SELECT to_blob('hello world', 0, 5); -- Result: 'hello'
-- Record the MIME type on write
SELECT to_blob('{"a":1}', 'application/json');
-- Record the MIME type and file name on write
SELECT to_blob('report body', 'text/plain', 'report.txt');
-- Extract a sub-content and record metadata
SELECT to_blob('abcdef', 1, 3, 'text/plain', 'part.txt');Query metadata: get_blob_metadata()
The get_blob_metadata() function reads Blob metadata and returns a JSON object. It does not return the Blob binary content.
Function | Description |
| Returns the Blob metadata as a JSON object |
The returned JSON contains the following fields:
Field | Type | Description |
| STRING | File name. The value is null if not set. |
| STRING | MIME type. The value is null if not set. |
| BIGINT | Content length in bytes. |
| STRING | Content checksum. The value is null if unavailable. |
Usage notes:
If
valueis NULL, NULL is returned. If the underlying Blob data is empty or its size is invalid, NULL is returned.Combine this function with JSON functions such as
get_json_object()andjson_length()to extract individual fields.get_blob_metadata()reads only metadata and does not read Blob binary content. It is suitable for filtering and inventory scenarios based on conditions such as type and size.
Example:
-- Read all metadata
SELECT get_blob_metadata(content) FROM t;
-- Extract individual fields
SELECT get_json_object(get_blob_metadata(content), '$.content_type') AS content_type,
get_json_object(get_blob_metadata(content), '$.content_length') AS content_length,
get_json_object(get_blob_metadata(content), '$.filename') AS filename
FROM t;
-- Filter by MIME type
SELECT id
FROM t
WHERE get_json_object(get_blob_metadata(content), '$.content_type') = 'image/png';Read Blob content: read_blob()
The read_blob() function reads Blob binary content and returns a value of the BINARY type.
Function | Description |
| Reads the entire Blob content |
| Reads content starting at the offset |
| Reads the specified length starting at the offset |
Usage notes:
When
offsetorlengthis not specified, the values are equivalent tooffset=0andlength=-1, which reads the entire content.When
length>=0, the actual read length ismin(remaining Blob length, length).When
offsetexceeds the content length, an empty BINARY value is returned.If
valueis NULL, NULL is returned. Ifoffsetorlengthis NULL, NULL is returned.read_blob()reads Blob binary content. If only filtering or inventory based on conditions such as type and size is required, useget_blob_metadata()to avoid the overhead of reading content.
Example:
-- Read Blob content
SELECT id, read_blob(image) FROM image_dataset WHERE label = 'cat' LIMIT 10;
-- Read part of the content (for example, a file header to determine the type)
SELECT id, read_blob(content, 0, 4) AS file_header FROM media_library;
-- Nested use
SELECT read_blob(to_blob('hello world'));Blob nested types
A Blob can be used as an ARRAY element or a STRUCT field, so that multiple files associated with one sample, such as video frames, document pages, or attachments of one session, can be stored in a single row.
Tables that contain nested Blob types can transfer data between each other by using INSERT INTO ... SELECT. NULL Blob elements and Blobs with empty content can be stored and read normally.
Limits
A Blob cannot be used as a
MAPkey, which meansMAP<BLOB, ...>and any nested structure that contains a Blob in the key position are not supported. To map file names to files, useMAP<STRING, BLOB>orARRAY<STRUCT<name:STRING, data:BLOB>>.Blob columns cannot be used as primary key columns or partition key columns.
Blob columns are not supported in ORDER BY, GROUP BY, or JOIN ON conditions.
array<blob>
CREATE TABLE frame_bundle (
id BIGINT,
frames ARRAY<BLOB>
) TBLPROPERTIES('table.format.version'='2');
-- Write multiple frames; metadata can be specified for each element
INSERT INTO frame_bundle VALUES
(1, ARRAY(to_blob('<frame0>', 'image/png', 'f0.png'),
to_blob('<frame1>', 'image/png', 'f1.png'),
CAST(NULL AS BLOB)));
-- Read by index
SELECT id,
SIZE(frames) AS frame_cnt,
read_blob(frames[0]) AS first_frame
FROM frame_bundle;struct<blob>
CREATE TABLE sample_with_cover (
id BIGINT,
label STRING,
cover STRUCT<seq:INT, image:BLOB>
) TBLPROPERTIES('table.format.version'='2');
INSERT INTO sample_with_cover VALUES
(1, 'traffic', named_struct('seq', 0, 'image', to_blob('<cover>', 'image/jpeg', 'cover.jpg')));
-- Read by field
SELECT id,
cover.seq AS cover_seq,
read_blob(cover.image) AS cover_image
FROM sample_with_cover;Examples
Example 1: Document asset library with metadata
Store documents, attachments, and other files together with their MIME types and file names, so that downstream services can preview and download files based directly on the metadata.
SET odps.sql.type.system.odps2=true;
CREATE TABLE doc_asset_store (
doc_id BIGINT,
biz_line STRING,
payload BLOB,
uploaded_at DATETIME
) TBLPROPERTIES('table.format.version'='2');
-- Write with the MIME type and file name
INSERT INTO doc_asset_store VALUES
(1, 'contract', to_blob('<pdf bytes>', 'application/pdf', 'contract-2026-001.pdf'), getdate()),
(2, 'contract', to_blob('{"k":"v"}', 'application/json', 'terms-2026-001.json'), getdate()),
(3, 'marketing', to_blob('<png bytes>', 'image/png', 'banner-q3.png'), getdate());
-- Asset inventory: read metadata only, without reading binary content
SELECT doc_id,
get_json_object(get_blob_metadata(payload), '$.filename') AS file_name,
get_json_object(get_blob_metadata(payload), '$.content_type') AS mime_type,
get_json_object(get_blob_metadata(payload), '$.content_length') AS content_length
FROM doc_asset_store
WHERE biz_line = 'contract';Example 2: Write multiple files of the same session into a Blob array in one row
Aggregate multiple files scattered in the same session into an ARRAY<BLOB> in one row, and store and read them at session granularity. This is suitable for scenarios such as conversation attachments and multi-frame collection.
Create a source table, where each row stores one file and the session it belongs to:
SET odps.sql.type.system.odps2=true; -- Source table: one file per row, with the session and metadata CREATE TABLE session_files ( session_id BIGINT, file BLOB ) TBLPROPERTIES('table.format.version'='2'); -- Construct data: images use the hexadecimal bytes of 1×1 solid-color PNGs (X'...' is a binary literal); text files use normal strings -- Session 1 writes 2 images and 1 text; session 2 writes 1 image and 1 text INSERT INTO session_files VALUES (1, to_blob(X'89504E470D0A1A0A0000000D4948445200000001000000010802000000907753DE0000000C4944415478DA63F8CFC0000003010100F70341430000000049454E44AE426082', 'image/png', 'red.png')), (1, to_blob(X'89504E470D0A1A0A0000000D4948445200000001000000010802000000907753DE0000000C4944415478DA636068600000010400814E0B14090000000049454E44AE426082', 'image/png', 'green.png')), (1, to_blob('session 1 notes: red and green swatches', 'text/plain', 'notes.txt')), (2, to_blob(X'89504E470D0A1A0A0000000D4948445200000001000000010802000000907753DE0000000C4944415478DA63F8FF9F010004FF01FF6380D12B0000000049454E44AE426082', 'image/png', 'yellow.png')), (2, to_blob('session 2 readme: yellow swatch', 'text/plain', 'readme.txt'));Create a destination table, and use
COLLECT_LISTto aggregate bysession_id, collecting multiple files asARRAY<BLOB>into one row:-- Destination table: one session per row, aggregating all files of the session CREATE TABLE session_file_bundle ( session_id BIGINT, files ARRAY<BLOB> ) TBLPROPERTIES('table.format.version'='2'); -- Aggregate by session_id and collect multiple Blobs into an array INSERT INTO session_file_bundle SELECT session_id, COLLECT_LIST(file) AS files FROM session_files GROUP BY session_id;Query the aggregation result, count the number of files in each session, and read array elements:
-- View the number of attachments in each session SELECT session_id, SIZE(files) AS file_cnt FROM session_file_bundle; -- View the attachment list of each session SELECT session_id, files FROM session_file_bundle;
Example 3: Route multimodal processing by MIME type
Route objects of different types to the corresponding processing pipelines based on the content_type metadata, without reading binary content to determine file types.
SELECT doc_id,
CASE
WHEN get_json_object(get_blob_metadata(payload), '$.content_type') LIKE 'image/%' THEN 'image_pipeline'
WHEN get_json_object(get_blob_metadata(payload), '$.content_type') LIKE 'video/%' THEN 'video_pipeline'
WHEN get_json_object(get_blob_metadata(payload), '$.content_type') LIKE 'audio/%' THEN 'audio_pipeline'
WHEN get_json_object(get_blob_metadata(payload), '$.content_type')
IN ('application/pdf', 'text/plain', 'text/html', 'application/json') THEN 'doc_pipeline'
ELSE 'unknown_pipeline'
END AS route
FROM doc_asset_store;Read Blob metadata through the SDK
MaxCompute Java SDK supports reading ARRAY<BLOB> and download metadata such as the MIME type and file name of each Blob.
Environment requirements
Use MaxCompute Java SDK 0.59.3 or later, and make sure that the versions of related modules such as odps-sdk-core and odps-sdk-storage-api are consistent.
<properties>
<odps.version>0.59.3</odps.version>
</properties>
<dependency>
<groupId>com.aliyun.odps</groupId>
<artifactId>odps-sdk-core</artifactId>
<version>${odps.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun.odps</groupId>
<artifactId>odps-sdk-storage-api</artifactId>
<version>${odps.version}</version>
</dependency>Read ARRAY<BLOB>
When reading with RecordReader in Storage API, an ARRAY<BLOB> column returns List<Blob>, and the list elements are com.aliyun.odps.data.Blob.
import com.aliyun.odps.data.ArrayRecord;
import com.aliyun.odps.data.Blob;
// Read an ARRAY<BLOB> column from a record
List<Blob> blobs = ((ArrayRecord) record).getArray(Blob.class, "files");A Blob read from a table record is a Blob reference and does not contain binary content or download metadata. Download the Blob through BlobManager, and then read the content and metadata from BlobDataStream.
Batch download and read metadata
BlobManager#batchDownload() returns BlobDataIterator. Each BlobDataStream obtained by iteration is both a content input stream and provides methods to read metadata. The return order is the same as the input Blob list.
import com.aliyun.odps.data.Blob;
import com.aliyun.odps.storage.MaxStorageClient;
import com.aliyun.odps.storage.internal.io.BlobDataStream;
import com.aliyun.odps.storage.read.BlobDataIterator;
try (BlobDataIterator iterator = client.openBlobManager().batchDownload(blobs)) {
int index = 0;
while (iterator.hasNext()) {
try (BlobDataStream stream = iterator.next()) {
String mimeType = stream.getMimeType(); // MIME type
String fileName = stream.getCustomFileName(); // File name
String effectiveMimeType = (mimeType == null || mimeType.isBlank())
? "application/octet-stream" : mimeType;
String effectiveFileName = (fileName == null || fileName.isBlank())
? "blob-" + index : fileName;
// The stream is an InputStream; consume or save the content here
consumeOneBlob(index, effectiveFileName, effectiveMimeType, stream);
}
index++;
}
}Usage notes:
BlobDataIteratorand eachBlobDataStreammust be closed. try-with-resources is recommended.The current
BlobDataStreammust be consumed and closed before the next Blob is read.Large files must be processed as streams. Avoid unbounded reads into
byte[].If metadata is also required for a single Blob, use
batchDownloadwith a single element.BlobManager#download(Blob)returns a normalInputStreamand does not provide metadata methods.For historical data or Blobs whose metadata was not set during upload,
getMimeType()andgetCustomFileName()may return null. The caller must provide default values.
Metadata mapping recommendations
When Blobs are exposed to the frontend for preview or download, map the metadata as follows:
SDK metadata | HTTP / business field | Default value when missing |
|
|
|
|
| A secure file name generated by the product |
Before a file name is written to Content-Disposition or the local file system, it must be securely sanitized to handle path separators, control characters, empty file names, and platform-reserved names.