如何通过DataStax Node.js驱动获取Cassandra更新/插入语句返回结果及更新行数
Hey there! I’ve worked with the DataStax Node.js driver for Cassandra quite a bit, so let’s tackle your two questions clearly:
By default, regular Cassandra write operations (like unconditional INSERT or UPDATE) are "fire-and-forget"—the driver returns a ResultSet, but its rows array will be empty because there's no data to return.
However, if you use lightweight transactions (e.g., INSERT ... IF NOT EXISTS or UPDATE ... IF [condition]), the driver will return a ResultSet with meaningful results that tell you whether the operation succeeded, and even return existing data if the condition failed.
Here's a practical example:
const { Client } = require('cassandra-driver'); const client = new Client({ contactPoints: ['127.0.0.1'], localDataCenter: 'datacenter1', keyspace: 'my_keyspace' }); async function insertUser(userId, userName) { const query = 'INSERT INTO users (id, name) VALUES (?, ?) IF NOT EXISTS'; const result = await client.execute(query, [userId, userName], { prepare: true }); // Check if the insert was successful if (result.rows[0].applied) { console.log('User inserted successfully!'); } else { console.log(`User already exists with name: ${result.rows[0].name}`); } } insertUser('123', 'Alice');
Unfortunately, Cassandra does not natively return the number of rows updated for regular write operations. This is by design—Cassandra prioritizes performance and scalability, and counting affected rows across a distributed, eventually consistent cluster would be slow and impractical.
That said, there are a few workarounds for specific scenarios:
- Counter columns: If you're updating a
COUNTERtype column, you can use a lightweight transaction to get the updated counter value (which indirectly tells you the change):async function incrementLoginCount(userId) { // Update counter only if it's less than 100 const query = 'UPDATE user_stats SET login_count = login_count + 1 WHERE user_id = ? IF login_count < 100'; const result = await client.execute(query, [userId], { prepare: true }); if (result.rows[0].applied) { console.log(`New login count: ${result.rows[0].login_count}`); } else { console.log('Login count already hit 100—no update done.'); } } - Check if an operation took effect: If you don't need the exact number of rows, just want to know if the update modified anything, you can use a lightweight transaction with a condition. The
appliedfield in the result will tell you if the condition was met and the update ran. Keep in mind, though, lightweight transactions add overhead since they require cross-node coordination.
If you absolutely need the exact number of updated rows, the only way is to run a SELECT query before and after the update, then compare the results. But this isn't reliable in high-concurrency environments (other writes could happen in between) and adds extra read/write load.
内容的提问来源于stack exchange,提问作者Southsouth

