2016-08-24 54 views
3

我在cassandra中有一個非常簡單的表。
名稱:測試
從節點js在cassandra中插入BigInt

  • ID(BIGINT,主鍵)
  • 名(文本)

我試圖插入值到這一點使用的NodeJS(使用Cassandra的驅動程序)

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數據庫時,看起來好像我爲大int整數的垃圾值lumn。

enter image description here

爲什麼發生這種情況的任何說明?

+1

你可以嘗試顯式指定類型:'client.execute(」插入到測試(id,name)值(?,?)「,[123,」dskddjls「],{提示:[」bigint「,null]},函數(err,data){....})' –

+0

@VsevolodGoloviznin是的,這個工程。那麼我們需要明確指定類型嗎? – Sachin

回答

3

你需要作爲第三個參數明確指定類型execute功能:

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

的原因是,某些字段卡桑德拉司機無法猜測類型(如BIGINT或時間戳),所以你需要提示一下。對於字符串或常規數字,它將無需提示。

+0

「bigint」的預期JavaScript類型是「Long」:https://github.com/datastax/nodejs-driver/tree/master/doc/features/datatypes – jorgebg

1

CQL datatypes to JavaScript types documentation中,您可以看到bigint的預期JavaScript類型爲Long。 JavaScript Number類型是double-precision 64-bit binary format IEEE 754 value,由驅動程序用來表示Cassandra int,floatdouble(默認)。

在你的情況,如果你想插入您在您的應用程序的數量有一個值,你應該使用Long.fromNumber()方法:

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

此外,對於準確映射一個JavaScript類型和之間卡桑德拉類型(以及其他好處),你應該prepare your queries。在你的情況,如果你設置了prepare標誌,司機會確定的預期值是Long,做從Number轉換:

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

正確!另一種解決方法:)雖然,準備聲明可能並不總是奏效 –