Using Put API to insert data

Add rows to your table. When you store data in table rows, your application can easily retrieve, add to, or delete information from a table.

You can use the PutRequest class / put method to perform unconditional and conditional puts to:
  • Overwrite any existing row. Overwrite is the default functionality.
  • Succeed only if the row does not exist. Use the IfAbsent method in this case.
  • Succeed only if the row exists. Use the IfPresent method in this case.
  • Succeed only if the row exists and the version matches a specific version. Use IfVersion method for this case and the setMatchVersion method to specify the version to match.

The PutRequest class provides the setValueFromJson method which takes a JSON string and uses that to populate a row to insert into the table. The JSON string should specify field names that correspond to the table field names.

Download the full code AddData.java from the examples here.
private static void writeRows(NoSQLHandle handle, MapValue value) 
                                               throws Exception {
   PutRequest putRequest =
     new PutRequest().setValue(value).setTableName(tableName);
   PutResult putResult = handle.put(putRequest);

   if (putResult.getVersion() != null) {
      System.out.println("Added a row to the stream_acct table");
   } else {
      System.out.println("Put failed");
   }
}
Inserting data into a JSON collection table: You can insert the top-level fields of the document in the JSON collection table using a sequence of PutRequest operations. For nested-level JSON fields, you can supply the JSON string in the putFromJson operation. You can also use the createFromJson method which takes the fields as a JSON string and uses that to populate a row in the table.
/*
 * Construct a row for JSON collection table with the following data:
 * {
 *   "id": 1,
 *   "name": "John Doe",
 *   "age": 25,
 *   "college" : {"name" : "Presidency", "branch" : "Biotechnology"}
 *   }
 * }
 */

String tableName = "usersJSON";

MapValue value = new MapValue().put("id", 1)

            .put("name", "John Doe")
            .put("age", 25)
            .putFromJson("college",  
                 "{\"name\" : \"Presidency\"," +
                 "\"branch\" : \"Biotechnology\"" +
                 " }", null); 

            PutRequest putRequest = new PutRequest()
                .setValue(value)
                .setTableName(tableName);

            PutResult putRes = handle.put(putRequest);
            System.out.println("Put row: " + value + " result=" + putRes);

The borneo.PutRequest class represents input to the borneo.NoSQLHandle.put() method which is used to insert single rows.

You can also add JSON data to your table. In the case of a fixed-schema table the JSON is converted to the target schema. JSON data can be directly inserted into a column of type JSON. The use of the JSON data type allows you to create table data without a fixed schema, allowing more flexible use of the data.

Download the full code AddData.py from the examples here.
def insert_record(handle,table_name,acct_data):
  request = PutRequest().set_table_name(table_name)
                        .set_value_from_json(acct_data)

  handle.put(request)
  print('Added a row to the stream_acct table')
Inserting data into a JSON collection table: You can add a row directly into the JSON collection table as a JSON string.
from borneo import PutRequest
request = PutRequest().set_table_name('usersJSON').request.set_value_from_json('{"id": 1, "name": "John Doe", "age": 25, "college" : {"name" : "Presidency", "branch" : "Biotechnology"}}')
handle.put(request)

The nosqldb.PutRequest represents an input to the nosqldb.Put() function and is used to insert single rows.

The data value provided for a row (in PutRequest) is a *types.MapValue. The key portion of each entry in the MapValue must match the column name of target table, and the value portion must be a valid value for the column. JSON data can also be directly inserted into a column of type JSON. The use of the JSON data type allows you to create table data without a fixed schema, allowing more flexible use of the data.

Download the full code AddData.go from the examples here.
func insertData(client *nosqldb.Client, err error, 
                tableName string,value1 *types.MapValue )(){
  putReq := &nosqldb.PutRequest{
    	TableName: tableName,
    	Value: value1,
  }
  putRes, err := client.Put(putReq)
  if err != nil {
     fmt.Printf("failed to put single row: %v\n", err)
     return
  }
  fmt.Printf("Added a row to the stream_acct table\n")
}
Inserting data into a JSON collection table: You can create a map value from JSON data and add the row to the JSON collection table.
value, err:=types.NewMapValueFromJSON(`{"id": 1, "name": "John Doe", "age": 25, "college" : {"name" : "Presidency", "branch" : "Biotechnology"}}`)
iferr!=nil {
    return
}
req:=&nosqldb.PutRequest{
    TableName: "usersJSON",
    Value: value,
}
res, err:=client.Put(req) 

You use the put method to insert a single row into the table. For method details, see NoSQLClient class.

JavaScript: Download the full code AddData.js from the examples here.
/* Adding 3 records in acct_stream table */
let putResult = await handle.put(TABLE_NAME, JSON.parse(acct1));
let putResult1 = await handle.put(TABLE_NAME, JSON.parse(acct2));
let putResult2 = await handle.put(TABLE_NAME, JSON.parse(acct3));

console.log("Added rows to the stream_acct table");
TypeScript: Download the full code AddData.ts from the examples here.
interface StreamInt {
   acct_Id: Integer;
   profile_name: String;
   account_expiry: TIMESTAMP;
   acct_data: JSON;
}
/* Adding 3 records in acct_stream table */
let putResult = await handle.put<StreamInt>(TABLE_NAME, JSON.parse(acct1));
let putResult1 = await handle.put<StreamInt>(TABLE_NAME, JSON.parse(acct2));
let putResult2 = await handle.put<StreamInt>(TABLE_NAME, JSON.parse(acct3));

console.log("Added rows to the stream_acct table");
Inserting data into a JSON collection table: You can add a row into the JSON collection table by supplying a plain JavaScript object with supported JSON types.
import { NoSQLClient, ServiceType } from 'oracle-nosqldb';
const client = new NoSQLClient('config.json');
const TABLE_NAME = 'usersJSON';
const record = {id : 1, 
    name : 'John Doe',
    age : 25,
    college : {
        name : 'Presidency', 
        branch : 'Biotechnology'
        }
}


async function writeARecord(client, record) {
    await client.put(TABLE_NAME, record);
}

The method PutAsync and related methods PutIfAbsentAsync , PutIfPresentAsync and PutIfVersionAsync are used to insert a single row into the table or update a single row.

Each of the Put methods above returns Task<PutResult<RecordValue>>. PutResult instance contains info about a completed Put operation, such as success status (conditional put operations may fail if the corresponding condition was not met) and the resulting RowVersion. Note that Success property of the result only indicates successful completion as related to conditional Put operations and is always true for unconditional Puts. If the Put operation fails for any other reason, an exception will be thrown. Using fields of data type JSON allows more flexibility in the use of data as the data in JSON field does not have a predefined schema. To put value into a JSON field, supply a MapValue instance as its field value as part of the row value. You may also create its value from a JSON string via FieldValue.FromJsonString.

Download the full code AddData.cs from the examples here.
private static async Task insertData(NoSQLClient client, String acctdet){
   var putResult = await client.PutAsync(TableName, 
                              FieldValue.FromJsonString(acctdet).AsMapValue);
   if (putResult.ConsumedCapacity != null)
   {
      Console.WriteLine(" Added a row to the stream_acct table");      
   }
}
Inserting data into a JSON collection table: You add a row in the JSON collection table by putting its value from a JSON string created through FromJsonString method.
var tableName = "usersJSON";

private const string data= @"{
"id": 1,
"name": "John Doe",
"age": 25,
"college" : {"name" : "Presidency", "branch" : "Biotechnology"}
}

var result = await client.PutAsync(tableName, FieldValue.FromJsonString(data).AsMapValue);