从节点js在cassandra中插入BigInt

Insert BigInt in cassandra from node js

我在 cassandra 中有一个非常简单的 table。
姓名: 测试

我正在尝试使用 nodejs(使用 cassandra-driver)向其中插入值

client.execute("insert into test (id, name) values (?, ?)", [123, "dskddjls"], function (err, response) {
            if (err) {
                console.log("An error occured, ", err)
                //...
            }
            else { 
                console.log("Added to table, ", response)
                //...
            }
        })

插入成功完成,但是当我检查我的 cassandra 数据库时,我似乎有 big int 列的垃圾值。

任何解释为什么会发生这种情况?

您需要明确指定类型作为 execute 函数的第三个参数:

client.execute("insert into test (id, name) values (?, ?)", [123, "dskddjls"], {hints: ["bigint", null]}, function (err, response) {
   ...
})

原因是有些字段cassandra driver无法猜测类型(比如bigint或timestamp),所以你需要提示一下。对于字符串或常规数字,它将在没有提示的情况下工作。

CQL datatypes to JavaScript types documentation you can see that expected JavaScript type for bigint is Long. The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value中,由驱动程序用来表示Cassandra intfloatdouble(默认)。

在您的情况下,如果您想插入应用程序中的数值作为数字,您应该使用 Long.fromNumber() 方法:

const query = "insert into test (id, name) values (?, ?)";
client.execute(query, [ Long.fromNumber(123), "my name" ], callback);

此外,为了在 JavaScript 类型和 Cassandra 类型之间进行准确映射(以及其他好处),您应该 prepare your queries。在您的情况下,如果您设置 prepare 标志,驱动程序将识别预期值为 Long 并从 Number 进行转换:

client.execute(query, [ 123, "my name" ], { prepare: true }, callback);