我正在使用 NodeJS 应用程序使用 cassandra-driver连接到 Cassandra
在玩过 cassandra-driver 之后,我注意到我们已经预先为每个表定义了模式。谁能帮我理解每个表的架构是否需要事先在 Cassandra 中定义?
这是我尝试从我的 nodeJS 应用程序连接到 Cassandra DB 的方式:
const cassandra = require("cassandra-driver");
const client = new cassandra.Client({
contactPoints: ['127.0.0.1'],
localDataCenter: 'datacenter1',
keyspace: 'testdb'
});
const executeCassandraQuery = async (query, params) => {
let fetchData;
try {
fetchData = await client.execute(query, params, { prepare: false });
console.log(`Successfully executed the query: ${JSON.stringify(fetchData)}`);
} catch (error) {
console.log(`There was an error executing the query: ${error}`)
}
return fetchData;
}
client.connect(async function (err, data) {
if (err) {
console.log(`There was an error connecting to Cassandra...${err}`)
}
else {
console.log(`Connected to Cassandra...${data}`);
const insertQuery = 'INSERT INTO testtable (id, firstname, lastname) VALUES(?,?,?)';
const insertQueryParams = [1, "Tony", "Mathew"];
const insertQueryResponse = await executeCassandraQuery(insertQuery, insertQueryParams);
console.log(`insertQueryResponse : ${insertQueryResponse}`);
const fetchQuery = 'SELECT * FROM employees';
}
});
在运行上述 nodeJS 脚本之前,我使用以下 cql 命令创建了“testdb”键空间和“testtable”表:
CREATE KEYSPACE testdb WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
CREATE TABLE testtable(id int PRIMARY KEY, name text);