> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kinetica.com/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript Developer Guide

> Step-by-step instructions on writing JavaScript applications with Kinetica

The following guide provides step-by-step instructions to get started writing
*JavaScript* applications using *Kinetica*. This guide demonstrates only a small
set of the available API.  A detailed description of the complete interface is
available under [JavaScript API Reference](/content/api/javascript).

<a id="js-api-install" />

## API Download

The source code for the *JavaScript* API is available for download from the
*GitHub* repository [kineticadb/kinetica-api-javascript](https://github.com/kineticadb/kinetica-api-javascript).
Follow the instructions in the included README file to use the API library.

## Connecting to the Database

To connect to the database, instantiate an object of the
[GPUdb](/content/api/javascript/GPUdb) class, providing the connection URL,
including host & port of the database server as well as an optional username &
password for secure connections:

```javascript theme={null}
var db = new GPUdb([url], {"username": user, "password": pass});
```

## Loading Data

Before any data can be loaded into the system, a
[Type](/content/concepts/types#gpudb-type-desc-label) needs to be defined in the system.  The type
definition is a JSON string describing the fields (i.e. columns) of the type
along with a name for the type. Each field consists of a name and a data type:

```javascript theme={null}
// Declare the data type for the table
var my_type = {
	"type": "record",
	"name": "my_type",
	"fields": [
		{"name":"col1","type":"double"},
		{"name":"col2","type":"string"},
		{"name":"group_id","type":"string"}
	]
};

// Register the data type with GPUdb and get the type's ID
var create_type_rsp = db.create_type( JSON.stringify( my_type ), "my_type" );
var type_id = create_type_rsp.type_id;
```

The returned object from the `create_type()` call contains a unique type
identifier allocated by the system.  This identifier can then be used in the
request to create a new table as follows:

```javascript theme={null}
var create_table_rsp = db.create_table( table_name, type_id );
```

Once the table is created, data can be inserted as follows:

```javascript theme={null}
// Generate records to be inserted
var records = [];
for (var i = 0; i < 10; i++) {
	var record = {
		col1 : (i + 0.1),
		col2 : ("string " + i),
		group_id : "Group 1"
	};
	records.push( record );
}

// This option will return IDs per record with which we can refer
// to particular records later as needed
var insert_options = { "return_record_ids" : "true" }
var insert_records_rsp = db.insert_records( table_name, records, insert_options );
console.log( "Record IDs for newly inserted records: " + insert_records_rsp["record_ids"] );
```

## Retrieving Data

Once the table is populated with data, the data can be retrieved from the system
by a call to `get_records()` as shown below:

```javascript theme={null}
var get_records_rsp = db.get_records( table_name );
console.log( "Retrieved records: " );
console.log( JSON.stringify( get_records_rsp["data"] ) );
```

For large tables, the data can be easily be retrieved in smaller blocks by using
the `offset` and `limit` parameters.  The returned response also contains
the schema (or data type) of the results.

## Running Queries

To filter a subset of the records, use the `filter()` method with an
expression as follows:

```javascript theme={null}
var filter_rsp = db.filter( table_name, view1_name, "col1 = 1.1" );
console.log( "Number of filtered records: " + filter_rsp["count"] );
```

To filter all the records matching a known list of values:

```javascript theme={null}
var column_values_map = {
		col1 : [ "1.1", "2.1", "5.1" ]
};

var filter_by_list_rsp = db.filter_by_list( table_name, view2_name, column_values_map );
console.log( "Number of records filtered by list: " + filter_by_list_rsp["count"] );
```

To retrieve a list of all the unique values for a column or a set of columns or
expression:

```javascript theme={null}
var unique_rsp = db.aggregate_unique( table_name, "group_id", 0 )
console.log( "Unique of values in 'group_id': " );
console.log( JSON.stringify( unique_rsp['data'] ) );
```

*Kinetica* supports various group-by queries.  To group by one or more columns
and return the count of the unique values, use the `aggregate_group_by()`
method as shown below.  The next query shows how to get the count of records,
as well as the sum and average of the values of column `col1`, within each
group:

```javascript theme={null}
var column_names = [ "col2" ];
var group_by_rsp = db.aggregate_group_by( table_name, column_names, 0 )
console.log( "Group by results: " );
console.log( JSON.stringify( group_by_rsp['data'] ) );
```

```javascript theme={null}
var column_names = [ "group_id", "count(*)", "sum(col1)", "avg(col1)" ];
group_by_rsp = db.aggregate_group_by( table_name, column_names, 0 )
console.log( "Second group by results: " );
console.log( JSON.stringify( group_by_rsp['data'] ) );
```

*Kinetica* supports grouping numerical data into a histogram.  The input range
is divided into equal sized bins and the count of objects in each bin are
returned:

```javascript theme={null}
var start = 1.1;
var end = 2;
var interval = 1;

var histogram_rsp = db.aggregate_histogram(table_name, "col1", start, end, interval)
console.log( "Histogram results: " );
console.log( JSON.stringify( histogram_rsp ) );
```

## Download & Run

Included below is a complete example containing all the above requests, the data
file, and output.

* [Tutorial Script Launch Page](https://raw.githubusercontent.com/kineticadb/kinetica-docs/master/content/examples/javascript/tutorial.html)
* [Tutorial Script](https://raw.githubusercontent.com/kineticadb/kinetica-docs/master/content/examples/javascript/tutorial.js)
* [Tutorial Output](https://raw.githubusercontent.com/kineticadb/kinetica-docs/master/content/examples/javascript/tutorial.out)

To run the complete sample, ensure the <Badge color="gray">GPUdb.js</Badge> & <Badge color="gray">tutorial.js</Badge>
references in the <Badge color="gray">tutorial.html</Badge> file point to the correct location of
the Kinetica Javascript API library & tutorial script files, respectively--(the
default assumes all three files are co-located in a browser-accessible
location).  Then, open the <Badge color="gray">tutorial.html</Badge> file in a browser, passing the
Kinetica URL, as well as optional username/password credentials for the
server as URL parameters:

```text theme={null}
file:///path/to/tutorial/tutorial.html?url=<url>[&user=<user>&pass=<pass>]
```

<Info>
  As this script creates a schema and several database objects within
  it, [system admin permission](/content/security/sec_concepts#security-concepts-permissions-system) is
  required to run it.
</Info>
