1

我正在使用 Datastax Astra 数据库。我正在上传 csv 文件,并将所有列数据类型设置为浮点数,根据列。我通过 python http_method 与我的数据库连接。

res = astra_client.request(
    method=http_methods.GET,
    path=f"/api/rest/v2/keyspaces/{ASTRA_DB_KEYSPACE}/{ASTRA_DB_COLLECTION}/rows")

这给了我所有的行,但是响应中没有维护数据类型。所有的浮点数都转换为字符串。为什么以及如何解决这个问题?

{'PetalWidthCm': '0.2', 'Id': 23, 'PetalLengthCm': '1.0', 'SepalWidthCm': '3.6', 'Species': 'Iris-setosa', 'SepalLengthCm': '4.6'}
4

1 回答 1

3

您是如何创建表格和添加数据的?例如,以下对我有用。

import http.client
import json

ASTRA_TOKEN = ""
ASTRA_DB_ID = ""
ASTRA_DB_REGION = ""
ASTRA_DB_KEYSPACE = "testks"
ASTRA_DB_COLLECTION = "float_test"

conn = http.client.HTTPSConnection(f"{ASTRA_DB_ID}-{ASTRA_DB_REGION}.apps.astra.datastax.com")
headers = {
  'X-Cassandra-Token': ASTRA_TOKEN,
  'Content-Type': 'application/json'
}

# Create the table
createTablePayload = json.dumps({
  "name": f"{ASTRA_DB_COLLECTION}",
  "columnDefinitions": [
    {"name": "id", "typeDefinition": "text"},
    {"name": "floatval", "typeDefinition": "float"},
    {"name": "intval", "typeDefinition": "int"},
    {"name": "doubleval", "typeDefinition": "double"}
  ],
  "primaryKey": {"partitionKey": ["id"]},
  "ifNotExists": True
})

# Add some data
conn.request("POST", f"/api/rest/v2/schemas/keyspaces/{ASTRA_DB_KEYSPACE}/tables", createTablePayload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

addRowPayload = json.dumps({
  "id": "af2603d2-8c03-11eb-a03f-0ada685e0000",
  "floatval": 1.1,
  "intval": 2,
  "doubleval": 3.3
})

conn.request("POST", f"/api/rest/v2/keyspaces/{ASTRA_DB_KEYSPACE}/{ASTRA_DB_COLLECTION}", addRowPayload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

# Read back the data
conn.request("GET", f"/api/rest/v2/keyspaces/{ASTRA_DB_KEYSPACE}/{ASTRA_DB_COLLECTION}/rows", "", headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

对此的回应是

$ python3 get_rows.py
{"name":"float_test"}
{"id":"af2603d2-8c03-11eb-a03f-0ada685e0000"}
{"count":1,"data":[{"id":"af2603d2-8c03-11eb-a03f-0ada685e0000","doubleval":3.3,"intval":2,"floatval":1.1}]}
于 2021-10-06T14:30:41.790 回答