|
| 1 | +use clickhouse_derive::Row; |
| 2 | +use serde::{Deserialize, Serialize}; |
| 3 | + |
| 4 | +use clickhouse::sql::Identifier; |
| 5 | +use clickhouse::{error::Result, Client}; |
| 6 | + |
| 7 | +// Requires ClickHouse 24.10+, as the `input_format_binary_read_json_as_string` and `output_format_binary_write_json_as_string` settings were added in that version. |
| 8 | +// Inserting and selecting a row with a JSON column as a string. |
| 9 | +// See also: https://clickhouse.com/docs/en/sql-reference/data-types/newjson |
| 10 | + |
| 11 | +#[tokio::main] |
| 12 | +async fn main() -> Result<()> { |
| 13 | + let table_name = "chrs_data_types_new_json"; |
| 14 | + let client = Client::default() |
| 15 | + .with_url("http://localhost:8123") |
| 16 | + // All these settings can instead be applied on the query or insert level with the same `with_option` method. |
| 17 | + // Enable new JSON type usage |
| 18 | + .with_option("allow_experimental_json_type", "1") |
| 19 | + // Enable inserting JSON columns as a string |
| 20 | + .with_option("input_format_binary_read_json_as_string", "1") |
| 21 | + // Enable selecting JSON columns as a string |
| 22 | + .with_option("output_format_binary_write_json_as_string", "1"); |
| 23 | + |
| 24 | + client |
| 25 | + .query( |
| 26 | + " |
| 27 | + CREATE OR REPLACE TABLE ? |
| 28 | + ( |
| 29 | + id UInt64, |
| 30 | + data JSON |
| 31 | + ) ENGINE MergeTree ORDER BY id; |
| 32 | + ", |
| 33 | + ) |
| 34 | + .bind(Identifier(table_name)) |
| 35 | + .execute() |
| 36 | + .await?; |
| 37 | + |
| 38 | + let row = Row { |
| 39 | + id: 1, |
| 40 | + data: r#" |
| 41 | + { |
| 42 | + "name": "John Doe", |
| 43 | + "age": 42, |
| 44 | + "phones": [ |
| 45 | + "+123 456 789", |
| 46 | + "+987 654 321" |
| 47 | + ] |
| 48 | + }"# |
| 49 | + .to_string(), |
| 50 | + }; |
| 51 | + |
| 52 | + let mut insert = client.insert(table_name)?; |
| 53 | + insert.write(&row).await?; |
| 54 | + insert.end().await?; |
| 55 | + |
| 56 | + let db_row = client |
| 57 | + .query("SELECT ?fields FROM ? LIMIT 1") |
| 58 | + .bind(Identifier(table_name)) |
| 59 | + .fetch_one::<Row>() |
| 60 | + .await?; |
| 61 | + |
| 62 | + println!("{db_row:#?}"); |
| 63 | + |
| 64 | + // You can then use any JSON library to parse the JSON string, e.g., serde_json. |
| 65 | + let json_value: serde_json::Value = serde_json::from_str(&db_row.data).expect("Invalid JSON"); |
| 66 | + println!("Extracted name from JSON: {}", json_value["name"]); |
| 67 | + |
| 68 | + Ok(()) |
| 69 | +} |
| 70 | + |
| 71 | +#[derive(Debug, Row, Serialize, Deserialize)] |
| 72 | +pub struct Row { |
| 73 | + id: u64, |
| 74 | + data: String, |
| 75 | +} |
0 commit comments