JSONデータの追加
固定スキーマ表へのJSONデータの追加方法について学習します。
ノート:
まず、クライアント・ドライバをOracle NoSQL Databaseに接続し、ハンドルを取得してから他のステップを実行します。このトピックでは、クライアント・ドライバの接続と表の作成に関するステップは省略しています。まだ表がない場合は、表および索引の作成を参照してください。表の行はAPIを使用して表に追加され、これにより、表の各フィールド値を個別に指定できます。たとえば、表に行全体を挿入する前に、MapValue.put()
メソッドを使用して、行の各フィールド値を入力します。
PutRequest
クラスには、JSON文字列を取得し、それを使用して表に挿入する行に値を移入するsetValueFromJson
メソッドも用意されています。JSON文字列では、表のフィールド名に対応するフィールド名を指定する必要があります。
JSONデータを表に追加するには、次のようにします。
/* Construct a simple row, specifying the values for each
* field. The value for the row is this:
*
* {
* "cookie_id": 123,
* "audience_data": {
* "ipaddr": "10.0.00.xxx",
* "audience_segment": {
* "sports_lover": "2018-11-30",
* "book_reader": "2018-12-01"
* }
* }
* }
*/
MapValue segments = new MapValue()
.put("sports_lover", new TimestampValue("2018-11-30"))
.put("book_reader", new TimestampValue("2018-12-01"));
MapValue value = new MapValue()
.put("cookie_id", 123) // fill in cookie_id field
.put("ipaddr", "10.0.00.xxx")
.put("audience_segment", segments);
PutRequest putRequest = new PutRequest()
.setValue(value)
.setTableName(tableName);
PutResult putRes = handle.put(putRequest);
同じ行をJSON文字列として表に挿入できます。
/* Construct a simple row in JSON */
String jsonString = "{\"cookie_id\":123,\"ipaddr\":\"10.0.00.xxx\",
\"audience_segment\":{\"sports_lover\":\"2018-11-30\",
\"book_reader\":\"2018-12-01\"}}";
PutRequest putRequest = new PutRequest()
.setValueFromJson(jsonString, null) // no options
.setTableName(tableName);
PutResult putRes = handle.put(putRequest);