You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Python使用BLOB类型将PDF文件存储至Cassandra?

Python 实现PDF文件存入Cassandra(BLOB类型方案)

Cassandra的BLOB类型本质是可变长二进制字节存储结构,本身不区分存储的二进制内容格式,PDF、图片、压缩包等任意二进制文件都可以直接转成字节流写入,官方文档只标注基础类型映射是因为所有二进制数据的操作逻辑完全通用,没有针对特定文件格式的特殊写法。


1. 表结构定义

先创建存储PDF的表,除了BLOB类型的文件内容字段,建议补充文件名、大小、上传时间等元数据方便检索:

-- 可根据自身集群情况调整副本策略
CREATE KEYSPACE IF NOT EXISTS file_storage 
WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};

USE file_storage;

CREATE TABLE IF NOT EXISTS pdf_files (
    file_id uuid PRIMARY KEY,
    file_name text,
    file_content blob,
    file_size bigint,
    upload_time timestamp
);

2. 环境准备

安装Cassandra官方Python驱动即可:

pip install cassandra-driver

3. PDF写入实现

核心逻辑是用二进制只读模式打开本地PDF,读取得到的bytes对象可以直接被驱动识别、转换为Cassandra的BLOB类型,不需要额外做编码转换:

from cassandra.cluster import Cluster
import uuid
import os
from datetime import datetime

# 初始化集群连接,替换为你自己的Cassandra节点地址
cluster = Cluster(["127.0.0.1"])
session = cluster.connect("file_storage")

# 预编译CQL提升写入性能
insert_sql = session.prepare("""
    INSERT INTO pdf_files (file_id, file_name, file_content, file_size, upload_time)
    VALUES (?, ?, ?, ?, ?)
""")

def save_pdf_to_cassandra(local_pdf_path: str) -> uuid.UUID:
    # 二进制模式读取文件
    with open(local_pdf_path, "rb") as f:
        pdf_binary = f.read()
    
    file_meta = [
        uuid.uuid4(),
        os.path.basename(local_pdf_path),
        pdf_binary,
        os.path.getsize(local_pdf_path),
        datetime.now()
    ]

    session.execute(insert_sql, file_meta)
    return file_meta[0]

实操提醒:不建议在Cassandra中存储单文件超过50MB的BLOB数据,大体积BLOB会显著增加集群节点间数据同步、修复的压力,拖慢整体查询性能,大文件优先存对象存储,Cassandra仅保留文件索引与访问路径即可。

4. PDF读取落地实现

从Cassandra查询返回的BLOB字段直接是Python原生bytes类型,直接以二进制写模式存入本地即可得到完整PDF:

select_sql = session.prepare("SELECT file_name, file_content FROM pdf_files WHERE file_id = ?")

def read_pdf_from_cassandra(file_id: uuid.UUID, save_dir: str):
    res = session.execute(select_sql, [file_id]).one()
    if not res:
        raise ValueError("未查询到对应ID的PDF文件")
    
    save_path = os.path.join(save_dir, res.file_name)
    with open(save_path, "wb") as f:
        f.write(res.file_content)
    return save_path

内容的提问来源于stack exchange,提问作者Tharun Teja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 13:33:24