### Aggregate Group By: Simple Count and Multi-Aggregate Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Performs GROUP BY aggregations. The first example shows a simple count per device_id. The second demonstrates multiple aggregates (sum, average, count) with sorting options. ```javascript const r1 = await db.aggregate_group_by( "sensor_readings", ["device_id", "count(*)"], 0, GPUdb.END_OF_SET, {} ); console.log(r1.data.column_headers); console.log(r1.data.column_1); console.log(r1.data.column_2); ``` ```javascript const r2 = await db.aggregate_group_by( "sensor_readings", ["device_id", "sum(temperature)", "avg(temperature)", "count(*)"], 0, GPUdb.END_OF_SET, { sort_by: "value", sort_order: "descending" } ); ``` -------------------------------- ### Create Materialized View with Periodic Refresh Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a materialized view named 'hourly_avg_temps' from 'iot_data'. It is configured to refresh periodically every hour, starting immediately. After creation, it populates the view with aggregated hourly average temperatures. ```javascript const result = await db.create_materialized_view( "hourly_avg_temps", { collection_name: "iot_data", refresh_method: "periodic", refresh_period: "3600", // seconds refresh_start_time: "now" } ); const viewTableName = result.table_name; // Now build the view by chaining SQL or filter/aggregation calls against viewTableName await db.execute_sql( `INSERT INTO hourly_avg_temps SELECT DATE_TRUNC('hour', timestamp), device_id, AVG(temperature) FROM sensor_readings GROUP BY 1, 2`, 0, 0, "", [], {} ); ``` -------------------------------- ### Retrieve Paginated Records with Sorting and Filtering Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Fetches a specific page of records (e.g., 100 records starting from offset 100) with optional sorting and filtering based on an expression. ```javascript // Fetch page 2 (records 100–199), sorted const page = await db.get_records("sensor_readings", 100, 100, { sort_by: "timestamp", sort_order: "descending", expression: "temperature > 22" }); console.log(page.total_number_of_records); // total matching rows in DB console.log(page.data.length); // up to 100 ``` -------------------------------- ### Initialize GPUdb Instance Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Create a connection handle to Kinetica servers. Supports single or multiple hosts for HA failover, and various authentication methods like basic auth or OAuth2 tokens. Options like timeout are configurable. ```javascript const GPUdb = require("../nodejs/GPUdb.js"); // Single host, basic auth const db = new GPUdb("http://kinetica-host:9191", { username: "admin", password: "s3cr3t", timeout: 30000 // ms; 0 = infinite }); // Multiple hosts for automatic HA failover const dbHA = new GPUdb( ["http://host1:9191", "http://host2:9191"], { username: "admin", password: "s3cr3t" } ); // OAuth2 token auth const dbOAuth = new GPUdb("http://kinetica-host:9191", { oauth_token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." }); console.log(db.url); // "http://kinetica-host:9191" console.log(db.username); // "admin" console.log(GPUdb.api_version); // "7.2.3.1" console.log(GPUdb.END_OF_SET); // -9999 (retrieve all records) ``` -------------------------------- ### `aggregate_histogram` — Histogram Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Computes a histogram of a numeric column, binning values between `start` and `end` with the specified `interval`. ```APIDOC ## `aggregate_histogram` — Histogram Computes a histogram of a numeric column, binning values between `start` and `end` with the specified `interval`. ### Usage ```javascript const result = await db.aggregate_histogram(table_name, column_name, start, end, interval, options); ``` ### Parameters - **table_name** (string) - The name of the table. - **column_name** (string) - The name of the numeric column. - **start** (number) - The start of the histogram range. - **end** (number) - The end of the histogram range. - **interval** (number) - The width of each bin. - **options** (object) - Optional parameters. ### Response Example ```json { "counts": [3, 7, 5, 2, 1, ...], // one count per bin "start": 18.0, "end": 30.0 } ``` ``` -------------------------------- ### Aggregate Histogram Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Computes a histogram for a numeric column within a specified range and interval. The result provides counts for each bin, along with the start and end of the histogram range. ```javascript const result = await db.aggregate_histogram( "sensor_readings", "temperature", 18.0, 30.0, 2.0, {} ); console.log(result.counts); console.log(result.start); console.log(result.end); ``` -------------------------------- ### User-Defined Procedures: Create and Execute Python Proc Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Shows how to create a Python user-defined procedure named 'normalize_temps' that converts Fahrenheit temperatures to Celsius. It then executes this procedure on the 'sensor_readings_fahrenheit' table and demonstrates how to poll its status. ```javascript // Create a Python proc from source string await db.create_proc( "normalize_temps", "distributed", // execution_mode: nondistributed | distributed { "normalize.py": Buffer.from(` import kinetica_proc proc = kinetica_proc.ProcData() for record in proc.input_data[0]: record["temperature"] = (record["temperature"] - 32) * 5/9 proc.output_data[0].extend(proc.input_data[0]) proc.complete() `).toString("base64") }, "/proc/python", // command [], // args { execution_mode: "distributed" } ); // Execute the proc const run = await db.execute_proc( "normalize_temps", {}, // params {}, // bin_params ["sensor_readings_fahrenheit"], // input_table_names { sensor_readings_fahrenheit: ["device_id","timestamp","temperature"] }, ["sensor_readings_celsius"], // output_table_names {} ); console.log(run.run_id); // Poll status const status = await db.show_proc_status(run.run_id, {}); console.log(status.overall_statuses[run.run_id]); // "running" | "complete" | "error" ``` -------------------------------- ### Constructor - new GPUdb(url, options) Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a connection handle to one or more Kinetica servers. Supports basic authentication, multiple hosts for HA failover, and OAuth2 token authentication. ```APIDOC ## Constructor — `new GPUdb(url, options)` Creates a connection handle to one or more Kinetica servers. All options are immutable after construction; creating a new instance is cheap and does not communicate with the server. ```javascript const GPUdb = require("../nodejs/GPUdb.js"); // Single host, basic auth const db = new GPUdb("http://kinetica-host:9191", { username: "admin", password: "s3cr3t", timeout: 30000 // ms; 0 = infinite }); // Multiple hosts for automatic HA failover const dbHA = new GPUdb( ["http://host1:9191", "http://host2:9191"], { username: "admin", password: "s3cr3t" } ); // OAuth2 token auth const dbOAuth = new GPUdb("http://kinetica-host:9191", { oauth_token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." }); console.log(db.url); // "http://kinetica-host:9191" console.log(db.username); // "admin" console.log(GPUdb.api_version); // "7.2.3.1" console.log(GPUdb.END_OF_SET); // -9999 (retrieve all records) ``` ``` -------------------------------- ### Register S3 Datasource and Kafka Datasink Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Use `create_datasource` to register read-only connections to external storage like S3. Use `create_datasink` to register write connections to external systems like Kafka. Ensure necessary credentials and configuration options are provided. ```javascript await db.create_datasource( "my_s3_source", "s3://my-bucket/data", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", { s3_region: "us-east-1", credential_name: "aws_cred" } ); // Register a Kafka datasink await db.create_datasink( "kafka_output", "kafka://kafka-broker:9092", { kafka_topic_name: "sensor-events", credential_name: "kafka_cred" } ); // Export records to the Kafka sink await db.export_records_to_table( "sensor_readings", "", // remote_query { datasink_name: "kafka_output", kafka_topic_name: "sensor-events" } ); ``` -------------------------------- ### Create Table from External Files (Parquet) Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a table and populates it from Parquet files in S3. Specify type inference mode for performance. ```javascript await db.create_table_external( "sales_2024", // table_name ["s3://my-bucket/sales/*.parquet"], // filepaths {}, { // create_table_options type_inference_mode: "speed" }, { datasource_name: "my_s3_source", file_type: "parquet", bad_record_table_name: "sales_2024_bad_records" } ); ``` -------------------------------- ### Bulk Load from Files Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Loads records into a table from local or remote file paths (CSV, JSON, Parquet, Avro, etc.). Creates the table if it doesn't exist. Configures file type, header presence, delimiter, and error handling. ```javascript await db.insert_records_from_files( "transactions", ["/data/txn_jan.csv", "/data/txn_feb.csv"], {}, // modify_columns { type_inference_mode: "speed" }, // create_table_options (creates if absent) { file_type: "delimited_text", text_has_header: "true", delimiter: ",", error_handling: "skip_record", bad_record_table_name: "transactions_rejected" } ); ``` -------------------------------- ### Upload and Download Files using GPUdb.FileHandler Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt The `FileHandler` class simplifies uploading local files to Kinetica Integrated File Store (KiFS) and downloading files from KiFS. Use `db.create_directory` to ensure the destination exists. The `upload` method accepts local file paths or File objects, and `download` returns base64-encoded file content. ```javascript const fileHandler = new GPUdb.FileHandler(db); // Create a KiFS directory await db.create_directory("my_project/data", { no_error_if_exists: "true" }); // Upload a local file (Node.js path string) await fileHandler.upload( ["/local/path/dataset.csv"], // array of local file paths or File objects "my_project/data", // KiFS destination directory { file_encoding: "base64" } // options ); // List files in the directory const listing = await db.show_files(["my_project/data"], {}); console.log(listing.file_names); // ["my_project/data/dataset.csv"] console.log(listing.sizes); // [204800] // Download files const fileData = await fileHandler.download( ["my_project/data/dataset.csv"], {} ); // fileData is an array of base64-encoded strings (one per file) const csvContent = Buffer.from(fileData[0], "base64").toString("utf8"); console.log(csvContent.slice(0, 100)); ``` -------------------------------- ### Introspect Server Properties and Status Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Retrieves server configuration properties and runtime status information. Use `show_system_properties` for configuration details and `show_system_status` for runtime metrics like uptime and process count. `show_system_timing` provides endpoint performance data. ```javascript // System properties (configuration) const props = await db.show_system_properties({}); console.log(props.property_map["conf.enable_worker_http_server"]); // System runtime status const status = await db.show_system_status({}); console.log(status.system_uptime_secs); console.log(status.num_processes); // System timing breakdown const timing = await db.show_system_timing({}); console.log(timing.endpoint_timings); ``` -------------------------------- ### create_table_external Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a table and populates it in one step from external files (CSV, Parquet, JSON, etc.) using a datasource or direct filepath. ```APIDOC ## `create_table_external` — Create Table from External Files Creates a table and populates it in one step from external files (CSV, Parquet, JSON, etc.) using a datasource or direct filepath. ```javascript await db.create_table_external( "sales_2024", // table_name ["s3://my-bucket/sales/*.parquet"], // filepaths {}, { // create_table_options type_inference_mode: "speed" }, { datasource_name: "my_s3_source", file_type: "parquet", bad_record_table_name: "sales_2024_bad_records" } ); // Alternatively, load CSV with explicit column mapping await db.create_table_external( "events", ["/tmp/events.csv"], { ts: { rename_column: "event_time" } }, { type_inference_mode: "accuracy" }, { file_type: "delimited_text", text_has_header: "true", delimiter: "," } ); ``` ``` -------------------------------- ### Create Table from External Files (CSV with Mapping) Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a table from a local CSV file, allowing explicit column renaming. Use 'accuracy' for type inference. ```javascript await db.create_table_external( "events", ["/tmp/events.csv"], { ts: { rename_column: "event_time" } }, { type_inference_mode: "accuracy" }, { file_type: "delimited_text", text_has_header: "true", delimiter: "," } ); ``` -------------------------------- ### Import Files into KiFS from URL Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Use `upload_files_fromurl` to directly download files from specified URLs into KiFS. This bypasses the need to download files to the client machine first. Ensure the target KiFS paths and source URLs are correctly provided. ```javascript await db.upload_files_fromurl( ["kifs/imported/public_dataset.csv"], // target KiFS paths ["https://example.com/data/public_dataset.csv"], // source URLs {} ); const listing = await db.show_files(["kifs/imported"], {}); console.log(listing.file_names); ``` -------------------------------- ### Server Introspection Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Retrieves server configuration properties and runtime status for monitoring and diagnostics. Includes functions to show system properties, system status, and system timing breakdowns. ```APIDOC ## `show_system_properties` / `show_system_status` — Server Introspection Retrieves server configuration properties and runtime status for monitoring and diagnostics. ```javascript // System properties (configuration) const props = await db.show_system_properties({}); console.log(props.property_map["conf.enable_worker_http_server"]); // System runtime status const status = await db.show_system_status({}); console.log(status.system_uptime_secs); console.log(status.num_processes); // System timing breakdown const timing = await db.show_system_timing({}); console.log(timing.endpoint_timings); ``` ``` -------------------------------- ### KiFS File System Upload / Download Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt The `FileHandler` helper wraps the `/upload/files` and `/download/files` endpoints for the Kinetica Integrated File Store (KiFS). ```APIDOC ## `GPUdb.FileHandler` — KiFS File System Upload / Download The `FileHandler` helper wraps the `/upload/files` and `/download/files` endpoints for the Kinetica Integrated File Store (KiFS). ```javascript const fileHandler = new GPUdb.FileHandler(db); // Create a KiFS directory await db.create_directory("my_project/data", { no_error_if_exists: "true" }); // Upload a local file (Node.js path string) await fileHandler.upload( ["/local/path/dataset.csv"], // array of local file paths or File objects "my_project/data", // KiFS destination directory { file_encoding: "base64" } // options ); // List files in the directory const listing = await db.show_files(["my_project/data"], {}); console.log(listing.file_names); // ["my_project/data/dataset.csv"] console.log(listing.sizes); // [204800] // Download files const fileData = await fileHandler.download( ["my_project/data/dataset.csv"], {} ); // fileData is an array of base64-encoded strings (one per file) const csvContent = Buffer.from(fileData[0], "base64").toString("utf8"); console.log(csvContent.slice(0, 100)); ``` ``` -------------------------------- ### Import Files into KiFS from URL Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Downloads remote files by URL directly into KiFS without going through the client machine. ```APIDOC ## `upload_files_fromurl` — Import Files into KiFS from URL Downloads remote files by URL directly into KiFS without going through the client machine. ```javascript await db.upload_files_fromurl( ["kifs/imported/public_dataset.csv"], // target KiFS paths ["https://example.com/data/public_dataset.csv"], // source URLs {} ); const listing = await db.show_files(["kifs/imported"], {}); console.log(listing.file_names); ``` ``` -------------------------------- ### Create Set Operation Table (UNION, INTERSECT, EXCEPT) Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a table representing the UNION, INTERSECT, or EXCEPT of multiple input tables or views. Column names can be mapped between input and output. ```javascript // UNION ALL of two tables await db.create_union( "all_sensors", // output table_name ["sensors_east", "sensors_west"], [["device_id", "temperature"], ["device_id", "temperature"]], ["device_id", "temperature"], { mode: "union_all" } ); // INTERSECT (common records) await db.create_union("common_sensors", ["sensors_east", "sensors_west"], [["device_id"], ["device_id"]], ["device_id"], { mode: "intersect" } ); ``` -------------------------------- ### Change Data Capture Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a server-sent event (SSE) topic that streams inserts/updates/deletes for a table in real time. ```APIDOC ## `create_table_monitor` / `alter_table_monitor` — Change Data Capture Creates a server-sent event (SSE) topic that streams inserts/updates/deletes for a table in real time. ```javascript // Create monitor on a table const mon = await db.create_table_monitor( "sensor_readings", { event: "insert" } // "insert" | "update" | "delete" ); const topicId = mon.topic_id; console.log("Monitor topic:", topicId); // Modify monitor to also capture updates await db.alter_table_monitor( topicId, { event: "update" }, {} ); // Show active monitors const monitors = await db.show_table_monitors([topicId], {}); console.log(monitors.monitor_ids); // Tear down await db.clear_table_monitor(topicId, {}); ``` ``` -------------------------------- ### Execute SQL Statement: SELECT and DDL Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Executes arbitrary SQL queries, including SELECT statements with aggregation and GROUP BY clauses, and Data Definition Language (DDL) statements like CREATE TABLE AS. Supports pagination and parallel execution. ```javascript const result = await db.execute_sql( "SELECT device_id, AVG(temperature) AS avg_temp FROM sensor_readings GROUP BY device_id", 0, 100, "", [], { parallel_execution: "true" } ); console.log(result.data.column_headers); console.log(result.total_number_of_records); ``` ```javascript await db.execute_sql( "CREATE TABLE archive.sensor_backup AS SELECT * FROM sensor_readings WHERE timestamp < 1700000000000", 0, 0, "", [], {} ); ``` -------------------------------- ### Insert Records (Promise Style) Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Inserts an array of JavaScript objects into a table using async/await. Returns assigned record IDs when the option is set. ```javascript const records = []; for (let i = 0; i < 5; i++) { records.push({ device_id: `sensor_${i}`, timestamp: Date.now() + i * 1000, temperature: 20.5 + i * 0.3, notes: null }); } const result = await db.insert_records("sensor_readings", records, { return_record_ids: "true" } ); // result.count_inserted => 5 // result.record_ids => ["0002...0", "0002...1", ...] ``` -------------------------------- ### Define and Register Table Schema (Type) Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Define a table schema using `GPUdb.Type` and `GPUdb.Type.Column`. The `create()` method registers the schema with Kinetica, returning a type ID. You can also reconstruct types from existing tables or raw type IDs. ```javascript // Define a type with column properties const myType = new GPUdb.Type( "sensor_reading", // label new GPUdb.Type.Column("device_id", "string", ["primary_key", "shard_key"]), new GPUdb.Type.Column("timestamp", "long", ["timestamp"]), new GPUdb.Type.Column("temperature", "double"), new GPUdb.Type.Column("notes", "string", ["nullable", "char256"]) ); console.log(myType.columns[0].is_nullable()); // false console.log(JSON.stringify(myType.generate_schema(), null, 2)); // { // "type": "record", // "name": "type_name", // "fields": [ // { "name": "device_id", "type": "string" }, // { "name": "timestamp", "type": "long" }, // { "name": "temperature", "type": "double" }, // { "name": "notes", "type": ["string", "null"] } // ] // } // Register type with Kinetica (Promise API) const typeId = await myType.create(db); console.log("Registered type ID:", typeId); // Reconstruct a Type from an existing table const tableType = await GPUdb.Type.from_table(db, "sensor_readings"); console.log(tableType.label, tableType.columns.map(c => c.name)); // Reconstruct from a raw type ID const rawType = await GPUdb.Type.from_type(db, typeId); ``` -------------------------------- ### create_graph, solve_graph, query_graph Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt A suite of functions for working with graph data. `create_graph` builds a property graph from table data, `solve_graph` performs graph algorithms like shortest path, and `query_graph` explores graph connectivity. ```APIDOC ## `create_graph` / `solve_graph` / `query_graph` — Graph Analytics Creates a property graph from table data, solves shortest-path or other graph problems, and queries adjacency relationships. ```javascript // Create a directed graph from a road network table await db.create_graph( "road_network", true, // directed_graph ["roads_table.start_node AS NODE_ID"], // nodes ["roads_table.start_node AS EDGE_NODE1_ID", "roads_table.end_node AS EDGE_NODE2_ID", "roads_table.road_id AS EDGE_ID"], // edges ["roads_table.travel_time AS EDGE_WEIGHT_VALUESPECIFIED"], // weights [], // restrictions { graph_table: "road_network_table" } ); // Solve shortest path (SHORTEST_PATH solver) const solution = await db.solve_graph( "road_network", [], // weights_on_edges [], // restrictions "SHORTEST_PATH", // solver_type ["node_12"], // source_nodes ["node_99"], // destination_nodes "path_solution", { output_wkt_path: "true" } ); console.log(solution.result_per_destination_node); // ["LINESTRING(...)"] // Query adjacency (breadth-first, 2 hops) const adj = await db.query_graph( "road_network", ["node_12"], // queries (source nodes) [], // restrictions "adjacency_result", // adjacency_table 2, // rings (BFS depth) {} ); ``` ``` -------------------------------- ### execute_proc, create_proc, show_proc_status Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Manages user-defined procedures (UDFs) implemented in C++, Python, or Java. `create_proc` defines a new procedure, `execute_proc` runs it, and `show_proc_status` monitors its execution status. ```APIDOC ## `execute_proc` / `create_proc` — User-Defined Procedures Creates and runs server-side user-defined functions (UDFs) implemented in C++, Python, or Java. ```javascript // Create a Python proc from source string await db.create_proc( "normalize_temps", "distributed", // execution_mode: nondistributed | distributed { "normalize.py": Buffer.from(` import kinetica_proc proc = kinetica_proc.ProcData() for record in proc.input_data[0]: record["temperature"] = (record["temperature"] - 32) * 5/9 proc.output_data[0].extend(proc.input_data[0]) proc.complete() `).toString("base64") }, "/proc/python", // command [], // args { execution_mode: "distributed" } ); // Execute the proc const run = await db.execute_proc( "normalize_temps", {}, // params {}, // bin_params ["sensor_readings_fahrenheit"], // input_table_names { sensor_readings_fahrenheit: ["device_id","timestamp","temperature"] }, ["sensor_readings_celsius"], // output_table_names {} ); console.log(run.run_id); // Poll status const status = await db.show_proc_status(run.run_id, {}); console.log(status.overall_statuses[run.run_id]); // "running" | "complete" | "error" ``` ``` -------------------------------- ### Filter by String: Equals, Contains, and Full-Text Search Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Demonstrates filtering records using different string matching modes: 'equals' for exact matches, 'contains' for substring matches across multiple columns, and 'search' for full-text indexing. ```javascript await db.filter_by_string("sensor_readings", "exact_match", "sensor_0", "equals", ["device_id"], {}); ``` ```javascript await db.filter_by_string("articles", "keyword_view", "kinetica", "contains", ["title", "body"], {}); ``` ```javascript await db.filter_by_string("articles", "ft_view", "GPU database analytics", "search", ["body"], {}); ``` -------------------------------- ### insert_records_from_files Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Loads records into a table from local or remote file paths (CSV, JSON, Parquet, Avro, etc.). ```APIDOC ## `insert_records_from_files` — Bulk Load from Files Loads records into a table from local or remote file paths (CSV, JSON, Parquet, Avro, etc.). ```javascript await db.insert_records_from_files( "transactions", ["/data/txn_jan.csv", "/data/txn_feb.csv"], {}, { type_inference_mode: "speed" }, // create_table_options (creates if absent) { file_type: "delimited_text", text_has_header: "true", delimiter: ",", error_handling: "skip_record", bad_record_table_name: "transactions_rejected" } ); ``` ``` -------------------------------- ### Graph Analytics: Create, Solve, and Query Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Demonstrates Kinetica's graph analytics capabilities. It includes creating a directed graph from a 'road_network' table, solving the shortest path between two nodes, and querying graph adjacency up to a specified depth. ```javascript // Create a directed graph from a road network table await db.create_graph( "road_network", true, // directed_graph ["roads_table.start_node AS NODE_ID"], // nodes ["roads_table.start_node AS EDGE_NODE1_ID", "roads_table.end_node AS EDGE_NODE2_ID", "roads_table.road_id AS EDGE_ID"], // edges ["roads_table.travel_time AS EDGE_WEIGHT_VALUESPECIFIED"], // weights [], // restrictions { graph_table: "road_network_table" } ); // Solve shortest path (SHORTEST_PATH solver) const solution = await db.solve_graph( "road_network", [], // weights_on_edges [], // restrictions "SHORTEST_PATH", // solver_type ["node_12"], // source_nodes ["node_99"], // destination_nodes "path_solution", { output_wkt_path: "true" } ); console.log(solution.result_per_destination_node); // ["LINESTRING(...)"] // Query adjacency (breadth-first, 2 hops) const adj = await db.query_graph( "road_network", ["node_12"], // queries (source nodes) [], // restrictions "adjacency_result", // adjacency_table 2, // rings (BFS depth) {} ); ``` -------------------------------- ### Retrieve All Records Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Fetches all records from a table. Use `GPUdb.END_OF_SET` for the count parameter to retrieve the maximum allowed number of records. ```javascript // Fetch all records const response = await db.get_records("sensor_readings", 0, GPUdb.END_OF_SET, {}); console.log(response.data); // [ // { device_id: 'sensor_0', timestamp: 1700000000000, temperature: 20.5, notes: null }, // ... // ] ``` -------------------------------- ### Manage Object Permissions with Grant/Revoke Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Use `grant_permission` and `revoke_permission` to manage access control for users or roles on specific objects. `grant_permission_table` allows for row-level security by specifying a `filter_expression`. Use `has_permission` to check existing permissions. ```javascript // Grant table read to a role await db.grant_permission("analyst_role", "sensor_readings", "table", "table_read", {}); // Grant filtered write (row-level security via filter_expression) await db.grant_permission_table( "device_operator", // name (user or role) "table_write", // permission "sensor_readings", // table_name "device_id = CURRENT_USER()", // filter_expression {} ); // Revoke permission await db.revoke_permission("analyst_role", "sensor_readings", "table", "table_read", {}); // Check if a principal has a permission const check = await db.has_permission( "analyst_role", "sensor_readings", "table", "table_read", {} ); console.log(check.has_permission); // true | false ``` -------------------------------- ### `execute_sql` — Execute SQL Statement Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Executes a SQL query (SELECT, INSERT, CREATE TABLE AS, etc.) and returns results with paging support. ```APIDOC ## `execute_sql` — Execute SQL Statement Executes a SQL query (SELECT, INSERT, CREATE TABLE AS, etc.) and returns results with paging support. ### Usage ```javascript // SELECT query const result = await db.execute_sql(sql_query, offset, limit, request_schema_str, data, options); // DDL via SQL await db.execute_sql(sql_query, offset, limit, request_schema_str, data, options); ``` ### Parameters - **sql_query** (string) - The SQL statement to execute. - **offset** (number) - The starting offset for results (for SELECT statements). - **limit** (number) - The maximum number of results to return (for SELECT statements). - **request_schema_str** (string) - Schema string for parameterized queries (usually empty). - **data** (array) - Parameterized query values (usually empty). - **options** (object) - Optional parameters, such as `parallel_execution`. ### Response Example (SELECT) ```json { "data": { "column_headers": ["device_id", "avg_temp"], ... }, "total_number_of_records": 100 } ``` ``` -------------------------------- ### Create and Alter Table Monitor for CDC Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Use `create_table_monitor` to set up real-time change data capture (CDC) for table inserts, updates, or deletes. Use `alter_table_monitor` to modify the events captured by an existing monitor. Ensure the `topicId` is correctly passed for modifications and teardown. ```javascript // Create monitor on a table const mon = await db.create_table_monitor( "sensor_readings", { event: "insert" } // "insert" | "update" | "delete" ); const topicId = mon.topic_id; console.log("Monitor topic:", topicId); // Modify monitor to also capture updates await db.alter_table_monitor( topicId, { event: "update" }, {} ); // Show active monitors const monitors = await db.show_table_monitors([topicId], {}); console.log(monitors.monitor_ids); // Tear down await db.clear_table_monitor(topicId, {}); ``` -------------------------------- ### create_union Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a table that is the UNION, INTERSECT, or EXCEPT of multiple input tables/views. Allows specifying input and output column names and the mode of operation. ```APIDOC ## `create_union` — Set Operations (UNION / INTERSECT / EXCEPT) Creates a table that is the UNION, INTERSECT, or EXCEPT of multiple input tables/views. ```javascript // UNION ALL of two tables await db.create_union( "all_sensors", // output table_name ["sensors_east", "sensors_west"], // table_names [["device_id", "temperature"], ["device_id", "temperature"]], // input_column_names ["device_id", "temperature"], // output_column_names { mode: "union_all" } ); // INTERSECT (common records) await db.create_union("common_sensors", ["sensors_east", "sensors_west"], [["device_id"], ["device_id"]], ["device_id"], { mode: "intersect" } ); ``` ``` -------------------------------- ### Insert Records (Callback Style) Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Inserts an array of JavaScript objects into a table using a callback function for handling the response. Records are generated in a loop. ```javascript const records = []; for (let i = 0; i < 5; i++) { records.push({ device_id: `sensor_${i}`, timestamp: Date.now() + i * 1000, temperature: 20.5 + i * 0.3, notes: null }); } db.insert_records("sensor_readings", records, { return_record_ids: "true" }, (err, response) => { if (err) return console.error(err); console.log("Inserted:", response.count_inserted); console.log("IDs:", response.record_ids); } ); ``` -------------------------------- ### Create Multi-Table Join View Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a materialized or virtual join view over multiple tables using INNER, LEFT OUTER, or CROSS joins. The resulting view can be queried like a regular table. ```javascript await db.create_join_table( "enriched_readings", // join_table_name ["sensor_readings sr", "device_metadata dm"], ["sr.*", "dm.location", "dm.model"], ["sr.device_id = dm.device_id"], { collection_name: "iot_data" } ); // Query the join view like a regular table const records = await db.get_records("enriched_readings", 0, 100, {}); ``` -------------------------------- ### Update Records in a Table Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Applies column-value updates to records matching filter expressions. Use `update_on_existing_pk` to control behavior when primary keys already exist. ```javascript const result = await db.update_records( "sensor_readings", ["device_id = 'sensor_0' and temperature < 20"], // expressions (OR-combined) [{ notes: "below_threshold" }], // new_values_maps [], // data (typed new values) { update_on_existing_pk: "true" } ); console.log(result.count_updated); // number of rows updated console.log(result.count_inserted); // rows upserted (if applicable) ``` -------------------------------- ### SqlIterator: Async Generator for SQL Results Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Streams results from a SQL query using an async generator, processing records in configurable batches. Server-side paging tables are automatically cleaned up upon completion. ```javascript const batchSize = 5000; const sqlOptions = {}; for await (const row of db.SqlIterator( "SELECT * FROM sensor_readings ORDER BY timestamp", batchSize, sqlOptions )) { const [deviceId, ts, temp, notes] = row; console.log(`${deviceId}: ${temp}°C at ${new Date(ts).toISOString()}`); } ``` -------------------------------- ### Aggregate Statistics by Range Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Divides the 'temperature' column in 'sensor_readings' into hourly buckets between two specified timestamps and computes statistics (mean, standard deviation, count) for each bucket. An empty 'select_expression' indicates all records are considered. ```javascript const result = await db.aggregate_statistics_by_range( "sensor_readings", "", // select_expression (filter, empty = all) "timestamp", // column_name (the axis to bin on) "temperature", // value_column_name (values to aggregate) "mean,stddev,count", 1699900000000, // start 1700100000000, // end 3600000, // interval (1 hour in ms) {} ); console.log(result.stats); // { mean: [...], stddev: [...], count: [...] } ``` -------------------------------- ### Create Derived Column Projection View Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a new table (projection) from a source table, allowing selection and transformation of columns. Optional filtering can be applied to the source records. ```javascript await db.create_projection( "sensor_readings", "sensor_readings_celsius", ["device_id", "timestamp", "(temperature - 32) * 5/9 as temp_c"], { expression: "temperature IS NOT NULL", collection_name: "iot_data" } ); ``` -------------------------------- ### create_projection Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a new table (projection) from a source table with selected/transformed columns and an optional filter. Useful for creating derived views. ```APIDOC ## `create_projection` — Derived Column Projection View Creates a new table (projection) from a source table with selected/transformed columns and optional filter. ```javascript await db.create_projection( "sensor_readings", "sensor_readings_celsius", ["device_id", "timestamp", "(temperature - 32) * 5/9 as temp_c"], { expression: "temperature IS NOT NULL", collection_name: "iot_data" } ); ``` ``` -------------------------------- ### `aggregate_k_means` — K-Means Clustering Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Runs the k-means clustering algorithm on one or more numeric columns and returns the cluster centroids. ```APIDOC ## `aggregate_k_means` — K-Means Clustering Runs the k-means clustering algorithm on one or more numeric columns and returns the cluster centroids. ### Usage ```javascript const result = await db.aggregate_k_means(table_name, column_names, k, tolerance, options); ``` ### Parameters - **table_name** (string) - The name of the table. - **column_names** (array of strings) - An array of numeric column names to cluster. - **k** (number) - The desired number of clusters. - **tolerance** (number) - The convergence threshold. - **options** (object) - Optional parameters, such as `max_iters`. ### Response Example ```json { "means": [[22.1, 55.3], [30.5, 40.1], [18.0, 70.2]], "counts": [50, 30, 20], "rms_dists": [0.5, 0.8, 0.3] // root-mean-square distances per cluster } ``` ``` -------------------------------- ### Aggregate K-Means Clustering Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Applies the k-means clustering algorithm to one or more numeric columns. It returns the cluster centroids, the number of points in each cluster, and their root-mean-square distances. ```javascript const result = await db.aggregate_k_means( "sensor_readings", ["temperature", "humidity"], 3, 0.001, { max_iters: "100" } ); console.log(result.means); console.log(result.counts); console.log(result.rms_dists); ``` -------------------------------- ### `SqlIterator` — Async Generator for SQL Results Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Streams all results from a SQL query using an async generator, fetching records in configurable batches and automatically cleaning up server-side paging tables. ```APIDOC ## `SqlIterator` — Async Generator for SQL Results Streams all results from a SQL query using an async generator, fetching records in configurable batches and automatically cleaning up server-side paging tables. ### Usage ```javascript for await (const row of db.SqlIterator(sql_query, batch_size, options)) { // Process each row } ``` ### Parameters - **sql_query** (string) - The SQL query to execute. - **batch_size** (number) - The number of records to fetch per batch. - **options** (object) - Optional parameters for the SQL query. ### Example ```javascript const batchSize = 5000; const sqlOptions = {}; for await (const row of db.SqlIterator("SELECT * FROM sensor_readings ORDER BY timestamp", batchSize, sqlOptions)) { // row is an array: [col1Value, col2Value, ...] const [deviceId, ts, temp, notes] = row; console.log(`${deviceId}: ${temp}°C at ${new Date(ts).toISOString()}`); } // Paging tables are cleaned up automatically when the generator is exhausted ``` ``` -------------------------------- ### create_join_table Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Creates a materialized or virtual join view over two or more tables. Supports INNER, LEFT OUTER, and CROSS joins via the `expressions` parameter. ```APIDOC ## `create_join_table` — Multi-Table Join View Creates a materialized or virtual join view over two or more tables. Supports INNER, LEFT OUTER, and CROSS joins via the `expressions` parameter. ```javascript await db.create_join_table( "enriched_readings", // join_table_name ["sensor_readings sr", "device_metadata dm"], // table_names (aliases) ["sr.*", "dm.location", "dm.model"], // column_names to project ["sr.device_id = dm.device_id"], // join expressions { collection_name: "iot_data" } ); // Query the join view like a regular table const records = await db.get_records("enriched_readings", 0, 100, {}); ``` ``` -------------------------------- ### External Data Connectors Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Registers external data source (read) and sink (write) connections including S3, HDFS, Kafka, Azure Blob, and JDBC. ```APIDOC ## `create_datasource` / `create_datasink` — External Data Connectors Registers external data source (read) and sink (write) connections including S3, HDFS, Kafka, Azure Blob, and JDBC. ```javascript // Register an S3 datasource await db.create_datasource( "my_s3_source", "s3://my-bucket/data", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", { s3_region: "us-east-1", credential_name: "aws_cred" } ); // Register a Kafka datasink await db.create_datasink( "kafka_output", "kafka://kafka-broker:9092", { kafka_topic_name: "sensor-events", credential_name: "kafka_cred" } ); // Export records to the Kafka sink await db.export_records_to_table( "sensor_readings", "", // remote_query { datasink_name: "kafka_output", kafka_topic_name: "sensor-events" } ); ``` ``` -------------------------------- ### get_records Source: https://context7.com/kineticadb/kinetica-api-javascript/llms.txt Fetches records from a table with optional paging. Use `GPUdb.END_OF_SET` (-9999) to retrieve the maximum allowed number of records. ```APIDOC ## `get_records` — Retrieve Records Fetches records from a table with optional paging. Use `GPUdb.END_OF_SET` (-9999) to retrieve the maximum allowed number of records. ```javascript // Fetch all records const response = await db.get_records("sensor_readings", 0, GPUdb.END_OF_SET, {}); console.log(response.data); // [ // { device_id: 'sensor_0', timestamp: 1700000000000, temperature: 20.5, notes: null }, // ... // ] // Fetch page 2 (records 100–199), sorted const page = await db.get_records("sensor_readings", 100, 100, { sort_by: "timestamp", sort_order: "descending", expression: "temperature > 22" }); console.log(page.total_number_of_records); // total matching rows in DB console.log(page.data.length); // up to 100 ``` ```