### Start AgentGuard Service Source: https://docs.timeplus.com/agentguard-installation Starts the AgentGuard service after installation. Access the setup wizard via http://localhost:8080. ```shell agentguard ``` -------------------------------- ### Configuration File Example Source: https://docs.timeplus.com/nats-jetstream-source Example of a configuration file for NATS connection settings, including username, password, and data format. ```INI username=my_username password=my_password data_format=JSONEachRow one_message_per_row=true ``` -------------------------------- ### Install Python Packages via SQL (3.0+) Source: https://docs.timeplus.com/py-udf Demonstrates how to install Python packages for UDFs using SQL commands. Supports installing the latest version, specific versions, or versions with range specifiers. ```sql -- Install latest SYSTEM INSTALL PYTHON PACKAGE 'requests'; -- Install with version specifier (PEP 440) SYSTEM INSTALL PYTHON PACKAGE 'requests>2.0'; SYSTEM INSTALL PYTHON PACKAGE 'requests==2.32.3'; -- Alternative form with separate version literal SYSTEM INSTALL PYTHON PACKAGE 'requests' '2.32.3'; ``` -------------------------------- ### Install Grafana, Prometheus, and Alloy Source: https://docs.timeplus.com/prometheus Installs Grafana, Prometheus, and Grafana Alloy using Homebrew. Ensure Homebrew is installed and configured before running these commands. ```bash brew install grafana prometheus brew install grafana/grafana/alloy ``` -------------------------------- ### MySQL Configuration File Example Source: https://docs.timeplus.com/mysql-external-table Example content for a configuration file used to set MySQL connection parameters like address, user, and password. ```text address=localhost:3306 user=root password=secret123 database=production ``` -------------------------------- ### Start Timeplus Enterprise Server Source: https://docs.timeplus.com/bare-metal-install Navigate to the 'bin' directory after uncompressing the package and run this command to start the Timeplus Enterprise server with preconfigured settings. ```bash ./timeplus start ``` -------------------------------- ### Start Services on Lead Node Source: https://docs.timeplus.com/bare-metal-install Start all Timeplus services on the lead node after configuring environment variables. ```bash timeplus start ``` -------------------------------- ### Example Mutable Stream Creation Source: https://docs.timeplus.com/mutable-stream This example demonstrates how to create a simple Mutable Stream named 'products' with specified columns and a primary key. ```sql CREATE MUTABLE STREAM products( id string, name string, price float32, description string ) PRIAMRY KEY id; ``` -------------------------------- ### Install AgentGuard with Shell Script Source: https://docs.timeplus.com/agentguard-installation Installs the latest AgentGuard binary or a specific version using a provided shell script. Installs to /usr/local/bin and creates a basic config file. ```shell # Install latest curl -fsSL https://agentguard.s3.us-west-1.amazonaws.com/install.sh | sh ``` ```shell # Install a specific version curl -fsSL https://agentguard.s3.us-west-1.amazonaws.com/install.sh | sh -s -- --version v1.2.3 ``` -------------------------------- ### MinMax Skip Index Example Source: https://docs.timeplus.com/append-stream-indexes An example of creating a skip index using the 'minmax' type with a specified granularity. ```sql INDEX idx2 u64 TYPE minmax GRANULARITY 3 ``` -------------------------------- ### Example: Control Fan-Out with Substreams Setting Source: https://docs.timeplus.com/shuffle-data This example shows how to control the number of target substreams after shuffling by using the `substreams` setting. The input stream is created with 3 shards. ```sql CREATE STREAM device_utils( location string, device string, cpu float32 ) SETTINGS shards=3; SELECT location, device, min(cpu), max(cpu), avg(cpu) FROM device_utils SHUFFLE BY location GROUP BY location, device EMIT ON UPDATE WITH BATCH 1s SETTINGS substreams=8; ``` -------------------------------- ### Install and Run AutoMQ Community Edition Source: https://docs.timeplus.com/automq-kafka-source Installs and runs the standalone deployment of AutoMQ Community Edition on Linux or Mac. ```bash curl https://download.automq.com/community_edition/standalone_deployment/install_run.sh | bash ``` -------------------------------- ### Install Timeplus Enterprise Source: https://docs.timeplus.com/automq-kafka-source Installs Timeplus Enterprise on Linux or Mac. ```bash curl https://install.timeplus.com | sh ``` -------------------------------- ### Example Local Executable Script Source: https://docs.timeplus.com/dictionary An example bash script that outputs tab-separated data for use with the EXECUTABLE source. ```bash #!/bin/bash echo -e "1\tp111" echo -e "2\tp222" echo -e "3\tp333" ``` -------------------------------- ### Install OpenClaw Plugin for AgentGuard Source: https://docs.timeplus.com/agentguard-installation Use npm to install the OpenClaw plugin for AgentGuard. ```bash npm install @timeplus/agentguard-openclaw-plugin ``` -------------------------------- ### List Installed Python Packages via SQL (3.0+) Source: https://docs.timeplus.com/py-udf Shows how to list all installed Python packages and their versions using the `SYSTEM LIST PYTHON PACKAGES` command. ```sql -- List installed packages SYSTEM LIST PYTHON PACKAGES; ``` -------------------------------- ### Example Materialized View for Aggregation Source: https://docs.timeplus.com/materialized-view This example demonstrates creating a source stream, a target stream for results, and a Materialized View that calculates a sum within a tumbling window. It then shows how to query the results from the target stream. ```sql -- Create a source stream CREATE RANDOM STREAM random_source(i int, s string); -- Create a target stream to hold the Materialized View results CREATE STREAM aggr_results(win_start datetime64(3), s string, total int64); -- Create a Materialized View which calculates the sum for each key `s` in a 2 seconds (tumble) window -- When the query results are available (when window closes), it materializes the results to -- target `aggr_results` stream CREATE MATERIALIZED VIEW tumble_aggr_mv INTO aggr_results AS SELECT window_start AS win_start, s, sum(i) AS total FROM tumble(random_source, 2s) GROUP BY window_start, s; -- Streaming query to continously monitor the results in target stream `aggr_results` SELECT * FROM aggr_results; ``` -------------------------------- ### Example PostgreSQL External Table Configuration File Source: https://docs.timeplus.com/pg-external-table This is an example of a configuration file used with the 'config_file' setting for external tables. It specifies connection parameters like address, user, password, and database. ```text address=localhost:5432 user=postgres password=secret123 database=production ``` -------------------------------- ### NATS Configuration File Example Source: https://docs.timeplus.com/nats-jetstream-sink Example of a configuration file for NATS JetStream sink, useful for managing credentials and settings, especially in Kubernetes. ```properties username=my_username password=my_password data_format=JSONEachRow one_message_per_row=true ``` -------------------------------- ### Example: Skip Shuffle with Pre-Partitioned Data Source: https://docs.timeplus.com/shuffle-data This example demonstrates skipping shuffle when data is already partitioned by using `allow_independent_shard_processing=true`. The stream is created with 3 shards and a custom sharding expression. ```sql CREATE STREAM device_utils( location string, device string, cpu float32 ) SETTINGS shards=3, sharding_expr='weak_hash32((location, device))'; SELECT location, device, min(cpu), max(cpu), avg(cpu) FROM device_utils GROUP BY location, device EMIT ON UPDATE WITH BATCH 1s SETTINGS allow_independent_shard_processing=true; ``` -------------------------------- ### Start Docker Compose Services Source: https://docs.timeplus.com/agentguard-installation Command to start the services defined in the Docker Compose file in detached mode. ```bash docker compose up -d ``` -------------------------------- ### Install Proton using Helm Source: https://docs.timeplus.com/proton Install the Timeplus Proton chart on Kubernetes using Helm, specifying the namespace, release name, and desired version. ```bash export NS=timeplus export RELEASE=proton export VERSION=v1.0.0 # or the latest version you want to install kubectl create ns $NS helm -n $NS install -f values.yaml $RELEASE timeplus/timeplus-proton --version $VERSION ``` -------------------------------- ### Example: Shuffle Data by Location Source: https://docs.timeplus.com/shuffle-data This example demonstrates shuffling data by the 'location' column to compute CPU utilization aggregations independently per substream. The input stream has a single source shard. ```sql CREATE STREAM device_utils( location string, device string, cpu float32 ); SELECT location, device, min(cpu), max(cpu), avg(cpu) FROM device_utils SHUFFLE BY location GROUP BY location, device EMIT ON UPDATE WITH BATCH 1s; ``` -------------------------------- ### Start Timeplus Container Source: https://docs.timeplus.com/tutorial-testcontainers-java Start a Timeplus container, attaching it to the same network as Kafka and providing an initialization script. This container will process the data pipeline. ```java // Step 4: start Timeplus container and run init.sql to create ETL pipelines TimeplusContainer timeplus = new TimeplusContainer( "timeplus/timeplusd:2.3.31" ) .withNetwork(network) .withInitScript("init.sql"); // inside src/test/resources timeplus.start(); ``` -------------------------------- ### Start Local PostgreSQL with Docker Source: https://docs.timeplus.com/pg-external-table Use this command to run a local PostgreSQL instance using Docker. Ensure the POSTGRES_PASSWORD environment variable is set. ```bash docker run --name=postgres --rm --env=POSTGRES_PASSWORD=foo -p 5432:5432 postgres:latest -c log_statement=all ``` -------------------------------- ### Set Skip Index Example Source: https://docs.timeplus.com/append-stream-indexes An example of creating a skip index using the 'set' type with a maximum of 1000 unique values and a granularity of 4. ```sql INDEX idx3 u64 TYPE set(1000) GRANULARITY 4 ``` -------------------------------- ### Start Kafka Container with Network Source: https://docs.timeplus.com/tutorial-testcontainers-java Initialize and start a Kafka container within a try-with-resources block for automatic cleanup. Create a network and set a listener for inter-container communication. ```java @Test public void testPrimalityRouter() { try ( Network network = Network.newNetwork(); KafkaContainer kafka = new KafkaContainer( "apache/kafka-native:3.8.0" ) .withListener("kafka:19092") .withNetwork(network); ) { // Step 1: start Apache Kafka (we will start Timeplus container when data is ready) kafka.start(); ``` -------------------------------- ### NATS User JWT and NKey Seed Example Source: https://docs.timeplus.com/nats-jetstream-sink Example content of a NATS credentials file, showing the structure of a User JWT and NKey Seed. ```text -----BEGIN NATS USER JWT----- eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJUVlNNTEtTWkJBN01VWDNYQUxNUVQzTjRISUw1UkZGQU9YNUtaUFhEU0oyWlAzNkVMNVJBIiwiaWF0IjoxNTU4MDQ1NTYyLCJpc3MiOiJBQlZTQk0zVTQ1REdZRVVFQ0tYUVM3QkVOSFdHN0tGUVVEUlRFSEFKQVNPUlBWV0JaNEhPSUtDSCIsIm5hbWUiOiJvbWVnYSIsInN1YiI6IlVEWEIyVk1MWFBBU0FKN1pEVEtZTlE3UU9DRldTR0I0Rk9NWVFRMjVIUVdTQUY3WlFKRUJTUVNXIiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.6TQ2ilCDb6m2ZDiJuj_D_OePGXFyN3Ap2DEm3ipcU5AhrWrNvneJryWrpgi_yuVWKo1UoD5s8bxlmwypWVGFAA ------END NATS USER JWT------ ************************* IMPORTANT ************************* NKEY Seed printed below can be used to sign and prove identity. NKEYs are sensitive and should be treated as secrets. -----BEGIN USER NKEY SEED----- SUAOY5JZ2WJKVR4UO2KJ2P3SW6FZFNWEOIMAXF4WZEUNVQXXUOKGM55CYE ------END USER NKEY SEED------ ************************************************************* ``` -------------------------------- ### Create Iceberg Stream Example Source: https://docs.timeplus.com/iceberg-source An example demonstrating the creation of an Iceberg stream named 'transformed' within the 'demo' database, including specific column definitions. ```sql CREATE STREAM demo.transformed ( timestamp datetime64, org_id string, float_value float, array_length int, max_num int, min_num int ); ``` -------------------------------- ### Create Changelog Stream Source: https://docs.timeplus.com/changelog-stream Example of creating a stream named 'dim_products' in 'changelog_kv' mode. This mode allows for data updates and deletions. ```SQL CREATE STREAM dim_products ( _tp_time DATETIME64(3, UTC), _tp_delta INT, product_id STRING, price FLOAT ) WITH ( mode = 'changelog_kv' ); ``` -------------------------------- ### Install NumPy via REST API (Enterprise 2.7+) Source: https://docs.timeplus.com/py-udf Installs the numpy library by making a POST request to the Timeplus REST API. Requires administrator credentials and is applicable to Enterprise v2.7 and v2.8. ```bash curl -H "x-timeplus-user: theUser" -H "x-timeplus-key:thePwd" -X POST http://localhost:8123/timeplusd/v1/python_packages -d '{"packages": [{"name": "numpy"}]}' ``` -------------------------------- ### Primary Index Example Visualization Source: https://docs.timeplus.com/append-stream-indexes Illustrates how a primary index on (counter_id, date) orders data and how queries can leverage this for efficient data retrieval. ```text Whole data: [---------------------------------------------] CounterID: [aaaaaaaaaaaaaaaaaabbbbcdeeeeeeeeeeeeefgggggggghhhhhhhhhiiiiiiiiikllllllll] Date: [1111111222222233331233211111222222333211111112122222223111112223311122333] Marks: | | | | | | | | | | | a,1 a,2 a,3 b,3 e,2 e,3 g,1 h,2 i,1 i,3 l,3 Marks numbers: 0 1 2 3 4 5 6 7 8 9 10 ``` -------------------------------- ### NATS JetStream External Stream Settings Example Source: https://docs.timeplus.com/nats-jetstream-sink Example configuration for NATS JetStream external stream settings, including NKey authentication with seed text. ```sql settings ... nats_nkey='UARHTANQIPCXFXYR3QZWHF4JWGRHPSOI4ZUEWWAHZ6CHZQVPC74J5CBU', nats_nkey_seed='SUAKUHMJTCRVKGUFUVIPE4MJA7WX64QEPS427GEGAZ477L4EDLZAOL66LQ', ... ``` -------------------------------- ### Protobuf Package Definition Source: https://docs.timeplus.com/data-formats Example of defining a package in a Protobuf schema. ```protobuf package demo; message StockRecord { .. } ``` -------------------------------- ### Querying with Skipping Indexes Source: https://docs.timeplus.com/append-stream-indexes Shows example queries that can benefit from the previously defined skipping indexes to reduce data read from disk. ```sql SELECT count() FROM table(test) WHERE u64 == 10; SELECT count() FROM table(test) WHERE u64 * i32 >= 1234; SELECT count() FROM table(test) WHERE u64 * length(s) == 1234; ``` -------------------------------- ### CSV Data Example Source: https://docs.timeplus.com/data-formats Sample data in CSV format, with values separated by commas. ```csv 123,click,2024-01-15T10:30:00Z 124,view,2024-01-15T10:31:00Z ``` -------------------------------- ### List Installed Python Libraries via REST API (Enterprise 2.x) Source: https://docs.timeplus.com/py-udf Retrieves a list of all extra Python libraries installed in Timeplus Enterprise 2.x environments using a GET request to the REST API. This is applicable for v2.7 and v2.8. ```bash curl -H "x-timeplus-user: theUser" -H "x-timeplus-key:thePwd" http://localhost:8123/timeplusd/v1/python_packages ``` -------------------------------- ### Create Mutable Stream with Auto-Increment Column Source: https://docs.timeplus.com/mutable-stream Example of creating a mutable stream with an auto-increment column. The 'id' column will automatically generate unique uint64 values starting from 1 for each shard. ```sql CREATE MUTABLE STREAM auto_incr ( id uint64 AUTO_INCREMENT, p string ) PRIMARY KEY (p); ``` -------------------------------- ### Create BigQuery Table Source: https://docs.timeplus.com/bigquery-external Example SQL statement to create a table in BigQuery with integer and string columns. ```sql create table `PROJECT.DATASET.http_sink_t1`( num int, str string); ``` -------------------------------- ### Example Query Result Source: https://docs.timeplus.com/proton Sample output from a streaming SQL query on the 'devices' stream, showing aggregated counts and temperature ranges per device. ```text ┌─device──┬─count()─┬─min(temperature)─┬─max(temperature)─┐ │ device0 │ 2256 │ 0 │ 99.6 │ │ device1 │ 2260 │ 0.1 │ 99.7 │ │ device3 │ 2259 │ 0.3 │ 99.9 │ │ device2 │ 2225 │ 0.2 │ 99.8 │ └─────────┴─────────┴──────────────────┴──────────────────┘ ``` -------------------------------- ### Sample Bar Chart Output Source: https://docs.timeplus.com/tutorial-sql-kafka Example output of the streaming SQL query for visualizing HTTP method counts with an ASCII bar chart. ```text ┌─raw:method─┬─cnt─┬─bar───┐ │ DELETE │ 35 │ ████▍ │ │ POST │ 29 │ ███▋ │ │ GET │ 27 │ ███▍ │ │ HEAD │ 25 │ ███ │ │ PUT │ 22 │ ██▋ │ └────────────┴─────┴───────┘ ``` -------------------------------- ### Check AgentGuard Startup Status (Binary/Local) Source: https://docs.timeplus.com/agentguard-installation Check the logs for the AgentGuard binary to confirm it started cleanly and is configured correctly. Look for Timeplus endpoint and webhook URL information. ```bash ./agentguard 2>&1 | grep -E "timeplus|AgentGuard" ``` -------------------------------- ### Kafka Configuration File Example Source: https://docs.timeplus.com/kafka-sink Use a configuration file to securely pass credentials and settings for the Kafka external stream. Settings in the DDL will override those in the config file. ```text username=my_username password=my_password data_format='Avro' one_message_per_row=true ``` -------------------------------- ### Sample Data Insertion for Partitioning Example Source: https://docs.timeplus.com/partition-data Inserts sample event data for two trucks (lic1 and lic2) with unaligned timestamps to demonstrate the effect of partitioning. ```sql -- Truck lic1 in San Francisco insert into trucks(lpn, lat, lon, spd, mil, state, city, _tp_time) values ('lic1', 37.7749, 37.7749, 23.5, 12462, 'CA', 'San Francisco', '2015-10-01 13:00:44'); -- Truck lic2 in Manhattan insert into trucks(lpn, lat, lon, spd, mil, state, city, _tp_time) values ('lic2', 40.7128, 74.0060, 32.3, 32567, 'NY', 'Manhattan', '2015-10-01 20:10:22'); -- Truck lic1 in San Francisco insert into trucks(lpn, lat, lon, spd, mil, state, city, _tp_time) values ('lic1', 37.7341, 37.7258, 13.5, 12472, 'CA', 'San Francisco', '2015-10-01 13:00:45'); -- Truck lic2 in Manhattan insert into trucks(lpn, lat, lon, spd, mil, state, city, _tp_time) values ('lic2', 40.7325, 74.0213, 32.4, 32570, 'NY', 'Manhattan', '2015-10-01 20:10:23'); -- Truck lic1 in San Francisco insert into trucks(lpn, lat, lon, spd, mil, state, city, _tp_time) values ('lic1', 37.7719, 37.7730, 33.5, 12473, 'CA', 'San Francisco', '2015-10-01 13:00:46'); -- Truck lic2 in Manhattan insert into trucks(lpn, lat, lon, spd, mil, state, city, _tp_time) values ('lic2', 40.7335, 74.0223, 12.3, 32581, 'NY', 'Manhattan', '2015-10-01 20:10:24'); ``` -------------------------------- ### Download and Run Timeplus Demo Kit with Docker Compose Source: https://docs.timeplus.com/bare-metal-install For Linux or Mac users, this command downloads and executes the demo kit using Docker Compose, which includes Timeplus Enterprise, Redpanda, ClickHouse, and a data generator. ```bash curl https://install.timeplus.com/sp-demo | sh ``` -------------------------------- ### Create and Query a Parameterized View Source: https://docs.timeplus.com/view Demonstrates creating a parameterized view with placeholders for query parameters and then querying it by providing values for those placeholders. ```sql -- Create a test stream CREATE STREAM test(i int); -- Create a parameterized view with one int8 parameter CREATE VIEW test_param_view AS SELECT * FROM test WHERE i > {range_start:int} AND i < {range_end:int}; -- Query the parameterized view by populating the placeholds SELECT * FROM test_param_view(range_start=100, range_end=200); ``` -------------------------------- ### JSONEachRow Example Data Source: https://docs.timeplus.com/data-formats Example of a single JSON object per line, suitable for the JSONEachRow data format. ```json {"user_id": 123, "action": "click", "timestamp": "2024-01-15T10:30:00Z"} ``` -------------------------------- ### Complete Alert Example with Python UDF Source: https://docs.timeplus.com/alert Demonstrates creating an alert that monitors GitHub events, calls a Python UDF to send notifications to Slack, and includes batching and suppression rules. ```python CREATE FUNCTION send_star_events_to_slack(actor string) RETURNS string LANGUAGE PYTHON AS $$ import json import requests def send_star_events_to_slack(value): for github_id in value: requests.post( "https://hooks.slack.com/services/T123/B456/other_id", data=json.dumps({ "text": f"New 🌟 for Timeplus Proton from https://github.com/{github_id}" }) ) return value $$ ``` ```sql CREATE ALERT default.watch_event_alert BATCH 10 EVENTS WITH TIMEOUT 5s LIMIT 1 ALERTS PER 15s CALL send_star_events_to_slack AS SELECT actor FROM github_events WHERE repo = 'timeplus-io/proton' AND type = 'WatchEvent'; ``` -------------------------------- ### Install Timeplus Proton using Homebrew Source: https://docs.timeplus.com/proton Installs or upgrades Timeplus Proton on macOS using the Homebrew package manager. ```bash brew tap timeplus-io/timeplus brew install proton ``` -------------------------------- ### Install Timeplus Proton on Linux/Mac Source: https://docs.timeplus.com/proton Installs Timeplus Proton as a single binary on Linux or Mac systems using curl. ```bash curl https://install.timeplus.com/oss | sh ``` -------------------------------- ### Create Stream with Storage Policy Source: https://docs.timeplus.com/append-stream-tiered-storage Create a new stream and apply a storage policy to manage data retention and location. This example sets a TTL of 7 days for historical data to move to the 'cold' volume. ```sql CREATE STREAM my_stream ( id uint32, name string, age uint8 ) TTL to_start_of_day(_tp_time) + interval 7 day to volume 'cold' SETTINGS storage_policy = 'hcs'; ``` -------------------------------- ### Example: Alter TTL by One Day Source: https://docs.timeplus.com/append-stream-ttl An example of altering a stream's TTL to expire data after one day. ```sql ALTER STREAM test MODIFY TTL d + INTERVAL 1 DAY; ``` -------------------------------- ### Install AgentGuard Claude Code Plugin Globally Source: https://docs.timeplus.com/agentguard-installation Installs the `agentguard-hook` command globally, making it available on your system's PATH. ```bash npm install -g @timeplus/agentguard-claudecode-plugin ``` -------------------------------- ### Docker-based OpenClaw Setup Commands Source: https://docs.timeplus.com/agentguard-installation Commands to set up OpenClaw via Docker using the Makefile in the `agents/openclaw/` directory. Includes workspace creation, initialization, configuration, and plugin deployment. ```bash cd agents/openclaw make workspace # one-time: create .openclaw/ with correct permissions make init # one-time: run the OpenClaw onboarding wizard make configure # inject AgentGuard plugin config into openclaw.json make deploy-plugin # build plugin + start container make url # print the dashboard URL with auth token ``` -------------------------------- ### Start Timeplus Container Source: https://docs.timeplus.com/tutorial-testcontainers-java Instantiate and start a Timeplus container using the TimeplusContainer class. Ensure you are using Testcontainers version 1.2.0.2 or newer. ```java TimeplusContainer timeplus = new TimeplusContainer("timeplus/timeplusd:2.3.31";) timeplus.start(); ``` -------------------------------- ### HashiCorp Vault Injection Example for Kafka Credentials Source: https://docs.timeplus.com/kafka-sink Example of using HashiCorp Vault annotations to inject Kafka credentials into a Kubernetes environment. ```yaml annotations: vault.hashicorp.com/agent-inject: "true" vault.hashicorp.com/agent-inject-status: "update" vault.hashicorp.com/agent-inject-secret-kafka-secret: "secret/kafka-secret" vault.hashicorp.com/agent-inject-template-kafka-secret: | {{- with secret "secret/kafka-secret" -}} username={{ .Data.data.username }} password={{ .Data.data.password }} {{- end }} vault.hashicorp.com/role: "vault-role" ``` -------------------------------- ### Create Stream with Mixed TTL Actions (DELETE, TO VOLUME, TO DISK) Source: https://docs.timeplus.com/append-stream-ttl Example of creating a stream with mixed TTL actions: deleting after one month, moving to a volume after one week, and moving to a disk after two weeks. ```sql CREATE STREAM stream_for_move ( d datetime, a int ) PARTITION BY to_YYYYMM(d) ORDER BY d TTL d + INTERVAL 1 MONTH DELETE, d + INTERVAL 1 WEEK TO VOLUME 'aaa', d + INTERVAL 2 WEEK TO DISK 'bbb'; ``` -------------------------------- ### Create Stream with Default Values Source: https://docs.timeplus.com/append-stream Example demonstrating how to create a stream with columns that have default values computed using DEFAULT and ALIAS expressions. It also shows inserting data and selecting from the stream. ```sql CREATE STRAM test ( id uint64, updated_at datetime DEFAULT now(), updated_at_date date DEFAULT to_date(updated_at) ) ORDER BY id; INSERT INTO test (id) VALUES (1); SELECT * FROM table(test); ``` -------------------------------- ### General Input Creation Syntax Source: https://docs.timeplus.com/inputs Use this syntax to create a target stream and then create an input that directs data to that stream. The target stream can be configured for streaming storage to reduce overhead. ```sql CREATE STREAM (...) SETTINGS ...; CREATE INPUT SETTINGS type=, target_stream=, tcp_port=, listen_host=, ...other input-type-specific settings... COMMENT '' ``` ```sql CREATE STREAM (...) SETTINGS storage_type = 'streaming'; ``` -------------------------------- ### Push Multiple Events (Java) Source: https://docs.timeplus.com/ingest-api Ingest multiple events in a batch using Java with OkHttp. This example demonstrates setting up the request with headers and a JSON body. ```java import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import java.io.IOException; public class Example { public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); String url = "https://host/ws123456/api/v1beta2/streams/foo/ingest"; MediaType mediaType = MediaType.parse("text/plain"); String data = """ { "columns": ["key1","key2"], "data": [ ["value11","value12"], ["value21","value22"], ] } """; RequestBody body = RequestBody.create(mediaType, data); Request request = new Request.Builder() .url(url) .header("X-Api-Key", "your_api_key") .header("Content-Type", "application/json") .post(body) .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.code()); System.out.println(response.body().string()); } } } ``` -------------------------------- ### Navigate and List Directory Contents Source: https://docs.timeplus.com/byoc Navigate into the generated Timeplus stack directory and list its contents to review configuration files. ```bash cd timeplus-stack-{cluster-name}/ ls -la ``` -------------------------------- ### Initialize Timeplus BYOC Configuration Source: https://docs.timeplus.com/byoc Run this command to start the interactive configuration wizard for your Timeplus BYOC cluster. Follow the prompts to generate the cluster configuration file. ```bash timeplus_byoc init ``` -------------------------------- ### Query NATS Stream from Specific Timestamp Source: https://docs.timeplus.com/nats-jetstream-source Starts consuming messages from a NATS JetStream stream from a given timestamp. Timeplus converts this to the nearest starting point. ```sql SELECT raw FROM ext_stream SETTINGS seek_to='2025-01-01T00:00:00.000' ``` -------------------------------- ### Deploy Timeplus with Configuration Source: https://docs.timeplus.com/byoc Initiate the Timeplus BYOC deployment using the cluster configuration file or directory. ```bash timeplus_byoc --config timeplus-stack-{cluster-name}/cluster.yaml ``` ```bash timeplus_byoc --config timeplus-stack-{cluster-name} ``` -------------------------------- ### Query NATS Stream Starting from Latest Messages Source: https://docs.timeplus.com/nats-jetstream-source Retrieves only new messages arriving after the query starts from a NATS JetStream stream. This is the default for streaming queries. ```sql SELECT raw FROM ext_stream SETTINGS seek_to='latest' ``` -------------------------------- ### Query NATS Stream Starting from Earliest Messages Source: https://docs.timeplus.com/nats-jetstream-source Retrieves all messages from a NATS JetStream stream, starting from the oldest available message. This is the default for non-streaming queries. ```sql SELECT raw FROM ext_stream SETTINGS seek_to='earliest' ``` -------------------------------- ### Named Collection Definition Example Source: https://docs.timeplus.com/mysql-external-table Example of defining a named collection in Timeplus to store MySQL connection configurations, including address, user, password, and database. ```sql CREATE NAMED COLLECTION mysql_config AS address='localhost:3306', user='root', password='secret123', database='production'; ``` -------------------------------- ### Connect to Local PostgreSQL Source: https://docs.timeplus.com/pg-external-table Connect to the running PostgreSQL instance using the psql command-line tool. Specify the port, user, and host. ```bash psql -p 5432 -U postgres -h localhost ``` -------------------------------- ### Create Skipping Indexes Example Source: https://docs.timeplus.com/append-stream-indexes Demonstrates the creation of various skipping indexes (bloom_filter, minmax, set) on different column types and expressions within a stream definition. ```sql CREATE STREAM test ( u64 uint64, i32 int32, s string, ... INDEX idx1 u64 TYPE bloom_filter GRANULARITY 3, INDEX idx2 u64 * i32 TYPE minmax GRANULARITY 3, INDEX idx3 u64 * length(s) TYPE set(1000) GRANULARITY 4 ) ... ``` -------------------------------- ### Start a Specific Timeplus Enterprise Process Source: https://docs.timeplus.com/bare-metal-install To start only a specific Timeplus Enterprise process, such as the core SQL engine ('timeplusd'), use the '-s' flag followed by the service name. ```bash timeplus start -s timeplusd ``` -------------------------------- ### Show Create Statement for a Format Schema Source: https://docs.timeplus.com/data-formats Displays the SQL command used to create a specific format schema. ```sql SHOW CREATE FORMAT SCHEMA schema_name ``` -------------------------------- ### Example SQL Expression for JIT Compilation Source: https://docs.timeplus.com/jit Demonstrates a SQL expression that can benefit from JIT compilation by fusing operations into single machine instructions for faster execution. ```sql SELECT ts, key, value AS v, (a + (b * c)) + 5 AS calc FROM stream; ``` -------------------------------- ### Create a Stream with Random Data Source: https://docs.timeplus.com/proton SQL commands to create a streaming data source with random device and temperature values, and set the event rate. ```sql -- Create a stream with random data CREATE RANDOM STREAM devices( device string default 'device'||to_string(rand()%4), temperature float default rand()%1000/10 ) SETTINGS eps=10000 -- 10,000 events per second. Default to 1000 ; -- Run the streaming SQL SELECT device, count(*), min(temperature), max(temperature) FROM devices GROUP BY device; ``` -------------------------------- ### Install NumPy via timeplusd CLI (Enterprise 2.8) Source: https://docs.timeplus.com/py-udf Installs the numpy library using the `timeplusd python -m pip` command for Enterprise v2.8. Ensure you are using a compatible version. ```bash timeplusd python --config-file ../conf/timeplusd.yaml -m pip install --user numpy ``` -------------------------------- ### Local File Source Syntax Source: https://docs.timeplus.com/dictionary Syntax for creating a dictionary from a local file. The file must be in the 'user_files' directory, and all cluster nodes must have the same file in the same location. ```sql SOURCE(FILE(path '/var/lib/timeplusd/user_files/dict.tsv' format 'CSV')) ``` -------------------------------- ### Local Executable Source Syntax Source: https://docs.timeplus.com/dictionary Syntax for creating a dictionary from a local executable. The executable must be in the 'user_files' directory and output data in the specified format. ```sql SOURCE(EXECUTABLE(command '/var/lib/timeplusd/user_files/dict.sh' format 'TabSeparated')) ``` -------------------------------- ### Example: Create Task to Collect Node Statuses Source: https://docs.timeplus.com/task Demonstrates creating a target stream and a scheduled task to periodically collect and store Timeplus node statuses. The task runs every 5 seconds and persists results to the 'node_states' stream. ```sql -- Create a target stream to hold the task results CREATE STREAM node_states (cluster_id string, node_id string, node_state string); -- Create a task to collect the node statuses CREATE TASK refresh_node_states SCHEDULE 5s TIMEOUT 2s INTO node_states AS SELECT cluster_id, node_id, node_state FROM system.cluster; ``` -------------------------------- ### Example Query Result Table Source: https://docs.timeplus.com/tutorial-sql-kafka This is an example of the tabular output you might receive when querying the 'mv_broken_links' materialized view, showing the count of events per HTTP method and a visual bar representation of those counts. ```text ┌─method─┬─cnt─┬─bar─┐ │ GET │ 25 │ ███ │ │ DELETE │ 20 │ ██▌ │ │ HEAD │ 17 │ ██ │ │ POST │ 17 │ ██ │ │ PUT │ 17 │ ██ │ │ PATCH │ 17 │ ██ │ └────────┴─────┴─────┘ ``` -------------------------------- ### Install Specific NumPy Version via REST API (Enterprise 2.7+) Source: https://docs.timeplus.com/py-udf Installs a specific version of the numpy library (e.g., 2.2.3) using the Timeplus REST API. This method is for Enterprise v2.7 and v2.8. ```bash curl -H "x-timeplus-user: theUser" -H "x-timeplus-key:thePwd" -X POST http://localhost:8123/timeplusd/v1/python_packages -d '{"packages": [{"name": "numpy", "version": "2.2.3"}]}' ``` -------------------------------- ### Install Pandas via Docker Exec (Enterprise 2.8) Source: https://docs.timeplus.com/py-udf Installs the pandas library within a running Timeplus Docker container using `docker exec` and `timeplusd python -m pip`. This is for Enterprise v2.8. ```bash docker exec -it container_name timeplusd python --config-file /etc/timeplusd-server/config.yaml -m pip install --user pandas ``` -------------------------------- ### Python External Stream with Init and Deinit Functions Source: https://docs.timeplus.com/python-external-stream-source Manage resources like client connections using init and deinit functions. These functions are executed per query. Configuration is passed as a string to the init function. ```sql CREATE EXTERNAL STREAM py_cookie_counter ( previous_cleanup_count int32, secret_flavor string ) AS $$ import builtins, json def open_bakery(config): builtins._tp_cookie_secret_flavor = json.loads(config)["flavor"] def close_bakery(): if hasattr(builtins, "_tp_cookie_secret_flavor"): del builtins._tp_cookie_secret_flavor def serve_cookie_report(): return [(0, getattr(builtins, "_tp_cookie_secret_flavor", ""))] $$ SETTINGS type = 'python', read_function_name = 'serve_cookie_report', init_function_name = 'open_bakery', init_function_parameters = '{"flavor":"double-chocolate"}', deinit_function_name = 'close_bakery'; ```