Struct MochowClient

Source
pub struct MochowClient {
    pub configuration: ClientConfiguration,
    /* private fields */
}

Fields§

§configuration: ClientConfiguration

Implementations§

Source§

impl MochowClient

Source

pub fn new( account: &str, api_key: &str, endpoint: &str, ) -> Result<Self, SdkError>

create a new mochow client with account, api_key and endpoint

use mochow_rust_sdk::mochow::client::MochowClient;
let client = MochowClient::new("account", "api_key", "endpoint").unwrap();
Source

pub fn new_with_configuration( config: &ClientConfiguration, ) -> Result<Self, SdkError>

create a new mochow client with configuration

use mochow_rust_sdk::mochow::{config::ClientConfigurationBuilder, client::MochowClient};
let config = ClientConfigurationBuilder::default()
	.account("account")
	.api_key("api_key")
	.endpoint("endpoint")
	.build().unwrap();
let client = MochowClient::new_with_configuration(&config).unwrap();
Source

pub async fn create_database( &self, data_base: &str, ) -> Result<CommonResponse, SdkError>

create a database

let _ = client.create_database("test").await?;
Source

pub async fn drop_database( &self, data_base: &str, ) -> Result<CommonResponse, SdkError>

drop the database you created, before deleting the database, all tables in the database must be deleted in advance

let _ = client.drop_database("test").await?;
Source

pub async fn list_database(&self) -> Result<ListDatabaseResponse, SdkError>

list current all databases

let ret = client.list_database("test").await?;
println!("{:?}", ret.databases);
Source

pub async fn hash_database(&self, data_base: &str) -> Result<bool, SdkError>

check if the database is exist,

Source

pub async fn create_table( &self, args: &CreateTableArgs, ) -> Result<CommonResponse, SdkError>

create table please check the crate::mochow::api::CreateTableArgs

use mochow_rust_sdk::mochow::api::{CreateTableArgsBuilder, Partition, TableSchema}
let fields = vec![];
let indexes = vec![];
let args = CreateTableArgsBuilder::default()
    .database("test_db")
    .table("test_table")
    .description("basic test".to_string())
    .replication(3 as u32)
    .partition(Partition {
        partition_type: PartitionType::HASH,
        partition_num: 3,
     })
     .schema(TableSchema {
        fields: fields,
        indexes: indexes,
     })
    .build()?;
let create_table_resp = client.create_table(&args).await?;
println!("{:?}", create_table_resp);
Source

pub async fn drop_table( &self, data_base: &str, table: &str, ) -> Result<CommonResponse, SdkError>

drop table

Source

pub async fn list_table( &self, data_base: &str, ) -> Result<ListTableResponse, SdkError>

list table

Source

pub async fn has_table( &self, data_base: &str, table: &str, ) -> Result<bool, SdkError>

has table

Source

pub async fn desc_table( &self, data_base: &str, table: &str, ) -> Result<DescriptTableResponse, SdkError>

descript table

Source

pub async fn add_field( &self, args: &AddFieldArgs, ) -> Result<CommonResponse, SdkError>

add field for table, currently only supports adding scalar fields

use mochow_rust_sdk::mochow::api::{TableSchema, FieldSchemaBuilder, AddFieldArgsBuilder};
let fields = vec![FieldSchemaBuilder::default()
    .field_name("bookAlias")
    .field_type("STRING")
    .build()?];
let args = AddFieldArgsBuilder::default()
    .database("test_db")
    .table("test_table")
    .schema(TableSchema{
        fields: fields,
        indexes: vec![],
    })
    .build()?;
let ret = client.add_field(&args).await?;
Source

pub async fn show_table_stats( &self, data_base: &str, table: &str, ) -> Result<StatsTableResponse, SdkError>

show table stats

Source

pub async fn alias_table( &self, data_base: &str, table: &str, alias: &str, ) -> Result<CommonResponse, SdkError>

alias table

Source

pub async fn unalias_table( &self, data_base: &str, table: &str, alias: &str, ) -> Result<CommonResponse, SdkError>

unalias table

Source

pub async fn create_index( &self, args: &CreateIndexArgs, ) -> Result<CommonResponse, SdkError>

create index, only support for vector index

let indexes = vec![IndexSchemaBuilder::default()
    .index_name("vector_idx")
    .field("vector")
    .index_type(IndexType::HNSW)
    ..metric_type(MetricType::L2)
    .params(VectorIndexParams::HNSW(HNSWIndexParam {
        m: 16,
        ef_construction: 200,
    }))
    .build()?];
let args = CreateIndexArgsBuilder::default()
    .database("test_db")
    .table("test_table")
    .indexes(indexes)
    .build()?;
let ret = client.create_index(&args).await?;
Source

pub async fn desc_index( &self, data_base: &str, table: &str, index_name: &str, ) -> Result<DescriptIndexResponse, SdkError>

descript index

Source

pub async fn modify_index( &self, args: &ModifyIndexArgs, ) -> Result<CommonResponse, SdkError>

modify vector index info, only support ‘autobuild’ attribute

let index = IndexSchemaBuilder::default()
    .index_name("vector_idx")
    .auto_build(true)
    .auto_build_policy(
        AutoBuildPolicyBuilder::default()
            .policy_type(AutoBuildPolicyType::PERIODICAL)
            .period_in_second(5000 as u64)
            .build()?,
    )
    .build()?;
let args = ModifyIndexArgsBuilder::default()
    .database("test_db")
    .table("test_table")
    .index(index)
    .build()?;
let ret = client.modify_index(&args).await?;
Source

pub async fn rebuild_index( &self, data_base: &str, table: &str, index_name: &str, ) -> Result<CommonResponse, SdkError>

rebuild index, only support for vector index

Source

pub async fn delete_index( &self, data_base: &str, table: &str, index_name: &str, ) -> Result<CommonResponse, SdkError>

delete index

Source

pub async fn insert_row<T: Serialize + Clone>( &self, args: &InsertRowArgs<T>, ) -> Result<InsertRowsResponse, SdkError>

insert row, when the primary key of the record already exists, an insertion error occurs, not support insert batch atomicity

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct MyRecord {
    #[serde(default)]
    id: String,
    #[serde(default, rename = "bookName")]
    book_name: String,
    #[serde(default)]
    author: String,
    #[serde(default)]
    page: i32,
    #[serde(default)]
    vector: Vec<f64>,
}
// insert row with a defined struct
let args1 = InsertRowArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .rows(vec![MyRecord {
        id: "0001".to_string(),
        book_name: "西游记".to_string(),
        author: "吴承恩".to_string(),
        page: 21,
        vector: vec![0.2123, 0.24, 0.213],
    }])
    .build()?;
// insert row with a json object
let _ret = client.insert_row(&args1).await?;
let args2 = InsertRowArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .rows(vec![serde_json::json!({
        "id": "0002",
        "bookName": "西游记",
        "author": "吴承恩",
        "page": 22,
        "vector": [0.2123, 0.24, 0.213],
    })])
    .build()?;
let _ret = client.insert_row(&args2).await?;
Source

pub async fn upsert_row<T: Serialize + Clone>( &self, args: &UpsertRowArgs<T>, ) -> Result<UpsertRowsResponse, SdkError>

upsert row, when the primary key of the record already exists, overwrite the old data with the new data as a whole, not support insert batch atomicity

let args = UpsertRowArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .rows(vec![
        serde_json::json!({
            "id":       "0001",
            "bookName": "西游记",
            "author":   "吴承恩",
            "page":     21,
            "vector":   [0.2123, 0.21, 0.213],
        })
    ])
    .build()?;
let _ret = client.upsert_row(&args).await?;
Source

pub async fn update_row( &self, args: &UpdateRowArgs, ) -> Result<CommonResponse, SdkError>

update row, update the value of one or more scalar fields in a specified record

let args = UpdateRowArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .primary_key(serde_json::json!({
        "id": "0001",
    }))
    .update(serde_json::json!({
        "bookName": "红楼梦",
        "author":   "曹雪芹",
        "page":     100,
    }))
    .build()?;
let _ret = client.update_row(&args).await?;
Source

pub async fn delete_rows( &self, args: &DeleteRowArgs, ) -> Result<CommonResponse, SdkError>

delete rows, you can delete multiple records by primary key, or filter the records to be deleted

let args = DeleteRowArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .primary_key(serde_json::json!({
        "id": "0001",
    }))
    .filter("page >= 22")
    .build()?;
let _ret = UTCLIENT.delete_rows(&args).await?;
Source

pub async fn query_row<T>( &self, args: &QueryRowArgs, ) -> Result<QueryRowsResponse<T>, SdkError>
where T: for<'de> Deserialize<'de>,

query row, query single row by primary key

let args = QueryRowArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .primary_key(serde_json::json!({
        "id": "0001",
    }))
    .projections(vec!["id".to_string(), "bookName".to_string()])
    .retrieve_vector(false)
    .build()?;
let query_ret: QueryRowsResponse<MyRecord> = UTCLIENT.query_row(&args).await?;
println!("query_row ret: {:?}", query_ret.row);
let row1 = query_ret.row;
let query_ret: QueryRowsResponse<serde_json::Value> = UTCLIENT.query_row(&args).await?;
println!("query_row ret: {:?}", query_ret.row);
// convert json value to struct
let row2 = serde_json::from_value(query_ret.row)?;
assert_eq!(row1, row2);
Source

pub async fn search_rows<T>( &self, args: &SearchRowsArgs, ) -> Result<SearchRowsResponse<T>, SdkError>
where T: for<'de> Deserialize<'de>,

search rows basing ann search of vector fields, support filter by scalar fields

let search_args = SearchRowsArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .anns(
        AnnsSearchParamsBuilder::default()
            .vector_field("vector")
            .vector_floats(vec![0.3123, 0.43, 0.213])
            .params(VectorSearchParams::HNSW(HNSWSearchParams {
                ef: 200,
                limit: 10,
                distance_far: None,
                distance_near: None,
                pruning: false,
            }))
            .filter("bookName = '三国演义'")
            .build()?,
    )
    .retrieve_vector(true)
    .build()?;
let ret: SearchRowsResponse<serde_json::Value> = client.search_rows(&search_args).await?;
Source

pub async fn select_rows<T>( &self, args: &SelectRowsArgs, ) -> Result<SelectRowsResponse<T>, SdkError>
where T: for<'de> Deserialize<'de>,

select rows filter records by scalar fields

let mut args = SelectRowsArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .projections(vec![
        "id".to_string(),
        "bookName".to_string(),
        "page".to_string(),
    ])
    .filter("page > 21")
    .limit(1 as u32)
    .build()?;
loop {
    let ret: SelectRowsResponse<serde_json::Value> = client.select_rows(&args).await?;
    println!("select_rows ret: {:?}", ret);
    if !ret.is_truncated {
        break;
    } else {
        args.marker = Some(ret.next_marker);
    }
}
Source

pub async fn batch_search_rows<T>( &self, args: &BatchSearchRowsArgs, ) -> Result<BatchSearchRowsResponse<T>, SdkError>
where T: for<'de> Deserialize<'de>,

batch search rows

  1. basing ann search of vector fields, support filter by scalar fields
  2. support batch query
let batch_ann_params = BatchAnnsSearchParamsBuilder::default()
    .vector_field("vector")
    .vector_floats(vec![vec![0.3123, 0.43, 0.213], vec![0.5512, 0.33, 0.43]])
    .params(VectorSearchParams::HNSW(HNSWSearchParams {
        ef: 200,
        limit: 10,
        distance_far: None,
        distance_near: None,
        pruning: false,
    }))
    .filter("bookName = '三国演义'")
    .build()?;
let batch_search_args = BatchSearchRowsArgsBuilder::default()
    .database(&TESTDATABSE.to_string())
    .table(&TESTTABLE.to_string())
    .anns(batch_ann_params)
    .retrieve_vector(true)
    .build()?;
let batch_rets: BatchSearchRowsResponse<serde_json::Value> =
    UTCLIENT.batch_search_rows(&batch_search_args).await?;
for (i, bs) in batch_rets.results.iter().enumerate() {
    println!("batch: {}, {:?}", i, bs.search_vector_floats);
    for (j, ss) in bs.rows.iter().enumerate() {
        println!("{}, {:?}", j, ss);
    }
}

Trait Implementations§

Source§

impl Clone for MochowClient

Source§

fn clone(&self) -> MochowClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MochowClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,