我在雪花中的一些数据是json str格式,但实际上它是浮点数列表。我使用 udf 将 json str 转换为浮点数列表,但似乎雪花在内部再次自动将浮点数列表转换为字符串格式。 只是想知道这是否是雪花的工作方式,或者是否有更好的方法以实际格式存储浮点数列表。 我不想每次都处理数据以将其从 json str 转换为浮点数列表。
使用下面的代码来演示问题
connection_parameters = {
"account": "MY_ACCOUNT"
"user": "USER",
"password": "PASSWORD",
"role": "MY_ROLE",
"warehouse": "MY_WH",
"database": "MY_DB",
"schema": "MY_SCHEMA"
}
table = "MY_TABLE"
sf_session = Session.builder.configs(connection_parameters).create()
from snowflake.snowpark.functions import udf
from snowflake.snowpark.types import ArrayType, DoubleType, StringType
import json
from typing import List
def parse_embedding_from_string(x: str) -> List[float]:
res = json.loads(x)
return res
retrieve_embedding = udf(parse_embedding_from_string)
df = sf_session.createDataFrame(data=[['[0.4, 2.57, 3.47]'], ['[34.50, 16.34, 12.9]'], ['[413.0, 1.211, 8.41]'], ['[0.4, 8.1, 10.11]'], ['[-6.89, 7.1, -12.1]'], ['[14.0, -21.0, 3.12]'], ['[11.0, 44.1, 26.2]'], ['[-4.4, 5.8, -0.10]']], schema=["embedding"])
df = df.withColumn("embedding_new", retrieve_embedding(col("embedding")))
# Output -
df.toPandas().iloc[0]["EMBEDDING_NEW"]
下面是输出
'[ 0.4, 2.57, 3.47 ]'
雪花连接器不支持在任一方向传递阵列。传递数组会将其转换为 JSON 格式的字符串。在 Python 端,您可以解析字符串以将其转换回数组。
向 Snowflake 发送数据时,尤其是。使用绑定变量,您可以将数组转换为 JSON 格式的字符串,并使用 Snowflake 的
parse_json
函数将其转换回数组。这里有一个很好的例子:
在Python方面,您可以在将数组作为字符串检索后执行类似的操作:
import ast
my_array = ast.literal_eval(input_string)
这里有完整的解释:
最简单的方法是:
import json
#the method must be loads with 's' at the end,
#and load without 's' is for an object
json.loads(input_string)