Python向TypeDB插入CSV日期时遇类型转换错误的技术问询
解决TypeDB插入日期字段时的类型转换错误
问题描述
从CSV文件通过Python向TypeDB插入数据时,日期字段触发如下错误:
typedb.common.exception.TypeDBClientException: [QRY01] Invalid Query Pattern: The class 'ValueConstraint.Constant.String' cannot be casted to 'ValueConstraint.Constant.DateTime'.
用到的日期格式化及查询拼接代码:
def format_date_time(date_string): date_obj = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%f") return date_obj.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] # 插入查询拼接逻辑 typeql_insert_query += ', has opening-date "'+format_date_time(account["opening-date"])+'";'
已尝试调整的日期格式:
- yyyy-mm-dd
- yyyy-mm-ddThh:mm
- yyyy-mm-ddThh:mm:ss
- yyyy-mm-ddThh:mm:ss.f
- yyyy-mm-ddThh:mm:ss.ff
- yyyy-mm-ddThh:mm:ss.fff
也尝试过在查询中用datetime()包裹日期字符串:
typeql_insert_query += ', has opening-date datetime("'+format_date_time(account["opening-date"])+'");'
解决方法
1. 先验证Schema字段类型
确保TypeDB Schema中,opening-date的类型定义为datetime,而非string:
define account entity, has opening-date datetime;
字段类型不匹配是触发类型转换错误的常见根源。
2. 优先使用参数化查询(推荐)
TypeDB Python客户端支持直接传入Python的datetime对象作为参数,无需手动格式化字符串,客户端会自动处理类型映射,彻底避免拼接错误:
from typedb.client import TypeDB, SessionType, TransactionType import datetime def parse_csv_date(date_str): # 解析CSV日期字符串为datetime对象 return datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f") # 连接TypeDB并执行插入 with TypeDB.core_client("localhost:1729") as client: with client.session("你的数据库名", SessionType.DATA) as session: with session.transaction(TransactionType.WRITE) as tx: for account in 你的CSV数据集: opening_date = parse_csv_date(account["opening-date"]) # 参数化查询,用$date绑定datetime对象 insert_qry = ''' insert $account isa account, has opening-date $date; ''' tx.query().insert(insert_qry, {"date": opening_date}) tx.commit()
3. 若坚持字符串拼接,需严格遵循语法
如果必须用字符串拼接生成查询,需注意两点:
- 日期字符串必须是ISO 8601标准格式(如
2024-05-20T14:30:45.123) datetime()包裹的字符串无需额外嵌套引号(确保最终生成的查询是datetime("2024-05-20T14:30:45.123"))
修正后的拼接代码:
def format_date_time(date_string): date_obj = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%f") # 直接生成ISO 8601毫秒精度格式 return date_obj.isoformat(timespec='milliseconds') # 拼接查询 typeql_insert_query += f', has opening-date datetime("{format_date_time(account["opening-date"])}");'
内容的提问来源于stack exchange,提问作者Sébastien Pannatier
相关产品推荐
相关产品推荐

