How to maintain data type in respond after connecting with Datastax Astra DB?

90 views Asked by At

I am using Datastax Astra database. I am uploading csv file and I am setting all the columns data type as float, as per column. I connected with my db via python http_method.

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

This gives me all the rows, but the data type is not maintained in the respond. All the float converted to string. Why and How can I solve this ?

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

There are 1 answers

0
dwettlaufer On

How are you creating your table and adding data? For example, the following works for me.

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"))

The response from this is

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