<?php require_once( dirname(dirname(dirname( __FILE__ ))) . '/wp-load.php' ); ?>
<!-- START of header -->
<?php get_header(); ?>
<!-- END of header -->

<!-- warapper -->

<div class="docs-content">
<!-- START of page navigation -->
<?php get_template_part( 'docs_navigation' ); ?>
<!-- END of page navigation -->
<!-- START of pusher -->
<div class="docs-content-body">
<div id="content" class="docs-content-body__inner">

<div id="outline-container-1" class="outline-3">
<h1 id="sec-1"><span class="section-number-3">3.4</span> CRUD Operations </h1>
<div class="outline-text-3" id="text-1">



<p>
CRUD operations are present in all databases as the foundational actions that allow the most basic of actions. GridDB's CRUD operations are most easily executed by using its very own Java-based API, though it does also accept TQL. </p>

	
<p><b> What is CRUD?</b></p>
	
<ul>
<li><b>Create:</b> writing new data (containers, rows, etc)</li>
<li><b>Read:</b> viewing, or "pulling up" any data</li>
<li><b>Update:</b> to modify already existing data (as opposed to writing NEW data) to reflect changes</li>
<li><b>Delete:</b> erasing or removing data from a container or row </li>
</ul>
</div>

<h3> Native API </h3>

	
<p>GridDB can be accessed using TQL or through its native API. The native API willl be looked at first, followed by some examples of use with TQL. </p>
	
<p><b> Creating a Container</b></p>
	
<p>Containers can be made easily by defining the data as a class.
	

<pre class="prettyprint linenums:33">
// Create Collection
Collection<String, WeatherStation> weatherStationCol =
		store.putCollection("weather_station", WeatherStation.class);
return weatherStationCol;
</pre>

34-35 line: create the collection by using the GridStore.putCollection (String, Class) method. The String Specifies the name of the container. The Class specifies the WeatherStation class that was created in the schema definition.
</p>

<b><p>Register the Data</p></b>
	
<p>
Ready access to GridDB in the above process is now ready. Let's try to register the data in GridDB.
	
<pre class="prettyprint linenums:29">
// Set the value to Row data
WeatherStation weatherStation1 = new WeatherStation ();
weatherStation1.id = "1";
weatherStation1.name = "WeatherStation 01";
weatherStation1.latitude = 35.68944;
weatherStation1.longitude = 139.69167;
weatherStation1.hasCamera = true;

WeatherStation weatherStation2 = new WeatherStation ();
weatherStation2.id = "2";
weatherStation2.name = "WeatherStation 02";
weatherStation2.latitude = 35.02139;
weatherStation2.longitude = 135.75556;
weatherStation2.hasCamera = false;

// Register Collection
weatherStationCol.put (weatherStation1);
weatherStationCol.put (weatherStation2);
</pre>
	
* 30-42 line: Set the values of the data to be registered.
<br> * 45-46 line: Pack data and register it in the container
</p>
	
<p><b>Read The Data (Retrieval) </b></p>

<p>Now the registered data can be retrieved from the GridDB server.</p>

<strong>List.6 data acquisition process</strong> (FirstGridDB.java)
<pre class="prettyprint linenums:48">
// Retrieve Collection
System.out.println("get by key");
System.out.println("ID\tName\t\t\tLongitude\tLatitude\tCamera");
weatherStationCol = store.getCollection("weather_station", WeatherStation.class);

for (int i = 0; i <2; i ++) {
	WeatherStation weatherStation = weatherStationCol.get (String.valueOf (i + 1));
	System.out.println (String.format("% - 3s\t% -20s\t% s\t% s\t% -5s", weatherStation.id,
			weatherStation.name, weatherStation.latitude, weatherStation.longitude,
			weatherStation.hasCamera));
}
</pre>

* 51 line: First get the container by specifying the container name and class.
<br>* 54 line: Then get row data by specifying the key.

<br>Here is the output:

<br><br><strong>List.7 data acquisition result</strong>
<pre class="prettyprint linenums">
get by key
ID Name Longitude Latitude Camera
1 WeatherStation 01 35.68944 139.69167 true
2 WeatherStation 02 35.02139 135.75556 false
</pre>

</p>

<b><p> Deleting A Container</p></b>

<p>
The command to delete a container looks like this: 
	
<pre class="prettyprint linenums">Container.dropCollection (String)</pre>
</p>
	
</div>


<h3> TQL </h3>


<p> Put simply, TQL is a simplified SQL prepared for NoSQL products. The support range is limited to functions such as search, aggregation, etc. TQL is employed by using the client API (Java, C language). To register and search for data in GridDB, a container or table (NewSQL products only) needs to be created to store the data. This section describes the data types that can be registered in a container or table, data size, index and data management functions.</p>
	<p>
The naming rules for containers and tables are the same as those for databases.</p>
	
<ul>
<li>
A string consisting of alphanumeric characters and the underscore mark can be specified. However, the first character cannot be a number.   
</li>    
<li>
Although the case sensitivity of the name is maintained, a container (table) which has the same name when it is not case-sensitive cannot be created. 
</li>    
</ul>
	
<p><b>Container Creation</b></p>
<pre class="prettyprint linenums:x">
Container (collection)	
createcollection	Container name Column name Type [Column name Type …]
Container (time series container)	
createtimeseries	Container name Compression method Column name type [Column name Type …]</pre>
	
	</li>
</ul>
</li>
<li>
Description of each argument
<table  border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
<caption></caption>
<colgroup><col align="left" /><col align="left" />
</colgroup>
<thead>
<tr><th scope="col">Argument</th><th scope="col">Description</th></tr>
</thead>
<tbody>
<tr><td>Container name</td><td>Specify the name of the container to be created. If the name is omitted in the createcontainer command, a container with the name given in the container data file will be created.</td></tr>
</tbody>
<tbody>
<tr><td>Column name</td><td>Specify the column name.</td></tr>
</tbody>
<tbody>
<tr><td>Type</td><td>Specify the column type.</td></tr>
</tbody>
<tbody>
<tr><td>Compression method</td><td>For TimeSeries data, specify the data compression method.</td></tr>
</tbody>
<tbody>
<tr><td>Container definition file</td><td>Specify the file storing the container data in JSON format.</td></tr>
</tbody>
</table>
	
	<p><b>Detailed version</b> 
</p>
<p>
Specify the container definition data in the json file to create a container.
</p>
<ul>
<li>
The container definition data has the same definition as the metadata file output by the export tool. See <a href="#impexp_metadata">Metadata files</a> with <a href="#container_dataform">the container data file format</a> for the column type and data compression method, container definition format, etc. However, the following data will be invalid in this command even though it is defined in the metadata file of the export command.
<ul>
<li>
version  Export tool version
</li>
<li>
database  Database name
</li>
<li>
containerFileType  Export data file type
</li>
<li>
containerFile  Export file name
</li>
<li>
partitionNo Partition no.
</li>
</ul>
</li>
<li>
Describe a single container definition in a single container definition file.
</li>
<li>
If the container name is omitted in the argument, create the container with the name described in the container definition file.
</li>
<li>
If the container name is omitted in the argument, ignore the container name in the container definition file and create the container with the name described in the argument.
</li>
<li>
An error will not result even if the database name is described in the container definition file but the name will be ignored and the container will be created in the database currently being connected.
</li>
<li>
When using the container definition file, <a href="#impexp_export"> the metadata file will be output when the --out option is specified in the export function</a>. The output metadata file can be edited and used as a container definition file.
</li>
</ul>
</li>
</ul>

<p>　　Example: When using the output metadata file as a container definition file
</p>


<pre class="prettyprint linenums">{
	"version":"2.1.00",　　　　　　　　　　　　　　　←invalid
	"container":"container_354",
	"database":"db2",　　　　　　　　　　　　　　　　←invalid
	"containerType":"TIME_SERIES",
	"containerFileType":"binary",　　　　　　　　　　←invalid
	"containerFile":"20141219_114232_098_div1.mc", 　←invalid
	"rowKeyAssigned":true,
	"partitionNo":0,　　　　　　　　　　　　　　　　 ←invalid
	"columnSet":[
		{
			"columnName":"timestamp",
			"type":"timestamp"
		},
		{
			"columnName":"active",
			"type":"boolean"
		},
		{
			"columnName":"voltage",
			"type":"double"
		}
	],
	"timeSeriesProperties":{
		"compressionMethod":"NO",
		"compressionWindowSize":-1,
		"compressionWindowSizeUnit":"null",
		"expirationDivisionCount":8,
		"rowExpirationElapsedTime":-1,
		"rowExpirationTimeUnit":"null"
	},
	"compressionInfoSet":[
	]

</pre>

<p><b> Container Deletion </b><p>
<ul>
<li>
Example:
<pre class="example">gs[public]> dropcontainer　Con001</pre>
</li>
</ul>


<p><b> Container Indication</b></p>
<p>The following command is used to display the container data.</p>
<ul>
<li>
Sub-command
<table  border="0" cellspacing="0" cellpadding="6" rules="none" frame="box" class="command">
<caption></caption>
<colgroup><col align="left" /><col align="left" />
</colgroup>
<tbody>
<tr><td>showcontainer</td><td>Container name</td></tr>
</tbody>
</table>


</li>
<li>
Description of each argument
<table  border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
<caption></caption>
<colgroup><col align="left" /><col align="left" />
</colgroup>
<thead>
<tr><th scope="col">Argument</th><th scope="col">Description</th></tr>
</thead>
<tbody>
<tr><td>Container name</td><td>Specify the container name to be displayed. Display a list of all containers if omitted.</td></tr>
</tbody>
</table>


</li>
<li>
Example:



<pre class="prettyprint linenums">// display container list
gs[userDB]> showcontainer
Database : userDB
Name                  Type         PartitionId
------------------------------------------------
cont001               COLLECTION            10
col00a                COLLECTION             3
time02                TIME_SERIES            5
cont003               COLLECTION            15
cont005               TIME_SERIES           17

// display data of specified container
gs[public]> showcontainer cont003
Database    : userDB
Name : cont003
Type : COLLECTION
Partition ID: 15
DataAffinity: -

Columns:
No  Name                  Type            Index
------------------------------------------------------------
0  col1                  INTEGER         [TREE] (RowKey)
1  col2                  STRING          []
2  col3                  TIMESTAMP       []
</pre>




</li>
</ul>

<p><b>[Memo]</b></p>
<ul>
<li>The data displayed in a container list are the “Container name”, “Container type” and “Partition ID”.</li>
<li>The data displayed in the specified container are the “Container name”, “Container type”, “Partition ID”, “Defined column name”, “Column data type” and “Column index setting”.</li>
<li>Container data of the current DB will be displayed.</li>
</ul>

	
<p><b>Container ROWKEY</b></p>
<p>A ROWKEY is the data set in the row of a container. The uniqueness of a row with a set ROWKEY is guaranteed.
A ROWKEY can be set in the first column of the row. (This is set in Column No. 0 since columns start from 0 in GridDB.)</p>

<ul>
<li>
For a timeseries container
</li>
<ul>
<li>
ROWKEY is a TIMESTAMP    
</li>
<li>
Must be specified.    
</li>
</ul>
</ul>
	
<ul>
<li>
For a collection container
</li>
<ul>    
<li>
A ROWKEY is either a STRING, INTEGER, LONG, or TIMESTAMP column.    
</li>
	
<li>
Need not be specified    
</li>
</ul>
</ul>

<p>
A default index prescribed in advance according to the column data type can be set in a column set in ROWKEY.
In the current version, the default index of all STRING, INTEGER, LONG or TIMESTAMP data that can be specified in a ROWKEY is the TREE index.   
</p>


<h3> Sample of Collection Operations (Java) </h3>

	
<pre class="prettyprint linenums:x">package test;


import java.util.Arrays;
import java.util.Properties;

import com.toshiba.mwcloud.gs.Collection;
import com.toshiba.mwcloud.gs.GSException;
import com.toshiba.mwcloud.gs.GridStore;
import com.toshiba.mwcloud.gs.GridStoreFactory;
import com.toshiba.mwcloud.gs.Query;
import com.toshiba.mwcloud.gs.RowKey;
import com.toshiba.mwcloud.gs.RowSet;


// Operaton on Collection data
public class Sample1 {

	static class Person {
		@RowKey String name;
		boolean status;
		long count;
		byte[] lob;
	}

	public static void main(String[] args) throws GSException {

		// Get a GridStore instance
		Properties props = new Properties();
		props.setProperty("notificationAddress", args[0]);
		props.setProperty("notificationPort", args[1]);
		props.setProperty("clusterName", args[2]);
		props.setProperty("user", "system");
		props.setProperty("password", "manager");
		GridStore store = GridStoreFactory.getInstance().getGridStore(props);

		// Create a Collection (Delete if schema setting is NULL)
		Collection&lt;String, Person&gt; col = store.putCollection("col01", Person.class);

		// Set an index on the Row-key Column
		col.createIndex("name");

		// Set an index on the Column
		col.createIndex("count");

		// Set the autocommit mode to OFF
		col.setAutoCommit(false);

		// Prepare data for a Row
		Person person = new Person();
		person.name = "name01";
		person.status = false;
		person.count = 1;
		person.lob = new byte[] { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };

		// Operate a Row on a K-V basis: RowKey = "name01"
		boolean update = true;
		col.put(person);	// Add a Row
		person = col.get(person.name, update);	// Obtain the Row (acquiring a lock for update)
		col.remove(person.name);	// Delete the Row

		// Operate a Row on a K-V basis: RowKey = "name02"
		col.put("name02", person);	// Add a Row (specifying RowKey)

		// Commit the transaction (Release the lock)
		col.commit();

		// Search the Collection for a Row
		Query&lt;Person&gt; query = col.query("select * where name = 'name02'");

		// Fetch and update the searched Row
		RowSet&lt;Person&gt; rs = query.fetch(update);
		while (rs.hasNext()) {
			// Update the searched Row
			Person person1 = rs.next();
			person1.count += 1;
			rs.update(person1);

			System.out.println("Person: " +
					" name=" + person1.name +
					" status=" + person1.status +
					" count=" + person1.count +
					" lob=" + Arrays.toString(person1.lob));
		}

		// Commit the transaction
		col.commit();

		// Release the resource
		store.close();
	}

}
</pre>




<h3> Sample of TimeSeries Operations 0 Storage and Extraction of Specific Range (Java) </h3>

	
	
<pre class="prettyprint linenums:x">package test;


import java.util.Date;
import java.util.Properties;

import com.toshiba.mwcloud.gs.GSException;
import com.toshiba.mwcloud.gs.GridStore;
import com.toshiba.mwcloud.gs.GridStoreFactory;
import com.toshiba.mwcloud.gs.RowKey;
import com.toshiba.mwcloud.gs.RowSet;
import com.toshiba.mwcloud.gs.TimeSeries;
import com.toshiba.mwcloud.gs.TimestampUtils;
import com.toshiba.mwcloud.gs.TimeUnit;


// Storage and extraction of a specific range of time-series data
public class Sample2 {

	static class Point {
		@RowKey Date timestamp;
		boolean active;
		double voltage;
	}

	public static void main(String[] args) throws GSException {

		// Get a GridStore instance
		Properties props = new Properties();
		props.setProperty("notificationAddress", args[0]);
		props.setProperty("notificationPort", args[1]);
		props.setProperty("clusterName", args[2]);
		props.setProperty("user", "system");
		props.setProperty("password", "manager");
		GridStore store = GridStoreFactory.getInstance().getGridStore(props);

		// Create a TimeSeries (Only obtain the specified TimeSeries if it already exists)
		TimeSeries&lt;Point&gt; ts = store.putTimeSeries("point01", Point.class);

		// Prepare time-series element data
		Point point = new Point();
		point.active = false;
		point.voltage = 100;

		// Store the time-series element (GridStore sets its timestamp)
		ts.append(point);

		// Extract the specified range of time-series elements: last six hours
		Date now = TimestampUtils.current();
		Date before = TimestampUtils.add(now, -6, TimeUnit.HOUR);

		RowSet&lt;Point&gt; rs = ts.query(before, now).fetch();

		while (rs.hasNext()) {
			point = rs.next();

			System.out.println(
					"Time=" + TimestampUtils.format(point.timestamp) +
					" Active=" + point.active +
					" Voltage=" + point.voltage);
		}

		// Release the resource
		store.close();
	}

}
</pre>
</div>
</div>
</div>
</div>
</div>
<!-- / main -->

<?php get_footer(); ?>
