【问题标题】:How to maintain data type in respond after connecting with Datastax Astra DB?与 Datastax Astra DB 连接后如何维护响应中的数据类型?
【发布时间】:2021-11-25 13:12:29
【问题描述】:

我正在使用 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'}

【问题讨论】:

  • 通过切换到 CQL? ;-)
  • 我想在我的 python 文件中做这件事。我想发送请求并在字典或 json 中得到响应。

标签: datastax-astra stargate-oss


【解决方案1】:

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

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}]}

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2021-11-28
    • 2022-10-05
    • 2022-01-16
    • 2018-03-02
    • 2022-10-05
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多