表
一个表就是一组有序排列的向量。本小节介绍表的创建、读取和添加的方式及使用示例。
创建表
表的创建可通过结构体 TableBuilder 实现,方法如下:
- 通过 new 方法创建 builder
,方法签名如下:
pub fn new() -> Self
- 通过 with_name 和 with_contents 方法指定表的信息:
with_name 指定该表的表名信息,方法签名如下:
pub fn with_name(&mut self, name: String) -> &mut Self
with_contents 指定该表的列名和表中的数据,方法签名如下:
pub fn with_contents(&mut self, columns: Vec<VectorImpl>, column_names: Vec<String>) -> &mut Self
- 通过 build
方法创建该表,方法签名如下:
pub fn build(self) -> Result<Table>
示例如下:
use dolphindb::types::{DoubleArrayVector, IntVector, TableBuilder, VectorImpl};
// 准备表中数据
async fn main() {
let mut prices = DoubleArrayVector::new();
let price1 = vec![1.1, 2.2, 3.3];
prices.push(price1);
let price2 = vec![4.4, 5.5];
prices.push(price2);
let v_int = IntVector::from_raw(&[2, 3]).into();
let v_double_array_vector = VectorImpl::from(prices);
// 创建表
let mut builder = TableBuilder::new();
builder.with_name("my_table".to_string());
builder.with_contents(
vec![v_int, v_double_array_vector],
vec!["volume".to_string(), "price".to_string()],
);
let table = builder.build().unwrap();
println!("{table}");
}
/*
+--------+---------------+
| volume | price |
+--------+---------------+
| 2 | [1.1,2.2,3.3] |
+--------+---------------+
| 3 | [4.4,5.5] |
+--------+---------------+
*/
访问表
方法 column_names 用于查看表的列名,签名如下:
pub fn column_names(&self) -> &Vec<String>
方法 columns 用于查看表中每列的数据,签名如下:
pub fn columns(&self) -> &Vec<VectorImpl>
示例如下:
// 获取列名
table.column_names()
// 获取每列数据
table.columns()