Aerospike C用戶端手冊———使用者定義函數—應用UDF到記錄,aerospikeudf

來源:互聯網
上載者:User

Aerospike C用戶端手冊———使用者定義函數—應用UDF到記錄,aerospikeudf
應用UDF到記錄

Aerospike C用戶端API提供aerospike_key_apply()來應用一個使用者定義函數到資料庫中某記錄。

在使用aerospike_key_apply()操作前,包含被應用函數的UDF模組,必須首先註冊到Aerospike伺服器。請參見【註冊使用者定義函數】章節來學習如何使用C API註冊,或閱讀【aql手冊】學習如何使用外部工具註冊。

下面的代碼引用自樣本目錄【examples/basic_examples/get】,由Aerospike C用戶端安裝包內建。

請先閱讀【建立串連】章節內容,理解如何建立與叢集的串連。

定義UDF

函數bin_transform定義在名稱為“basice_udf“的模組中。

function bin_transform(record, bin_name, x, y)    record[bin_name] = (record[bin_name] * x) + y    aerospike:update(record)    return record[bin_name]end

此函數是個有三個參數的簡單演算法,三 個參數名稱分別為”bin_name“、”x“、”y“。它在由“bin_name”指定的bin上執行運算並更新記錄資料,然後返回這個bin的運算結果值。

初始化記錄鍵(KEY)

當在記錄上應用使用者定義函數時,需要通過鍵(key)在資料庫中標識這條記錄。下面我們為範例程式碼建立一個鍵。用來做鍵的是字串(string)”test-key",資料所在的namespace名稱為“test”、set名稱為“test-set”。其它資料類型也可用作鍵,比如:整型(integer)或二進位大對象塊(blob)。

as_key key;as_key_init_str(&key, "test", "test-set", "test-key");
傳遞參數給UDF

使用者定義函數”bin_transform“,要求一個字串型(string)參數和兩個整型(integer)參數,因此需要填充一個參數列表。

as_arraylist args;as_arraylist_inita(&args, 3);as_arraylist_append_str(&args, "test-bin-2");as_arraylist_append_int64(&args, 4);as_arraylist_append_int64(&args, 400);
在記錄上應用UDF

使用記錄鍵,現在可在資料庫的指定記錄上調用使用者定義函數:

as_val * result = NULL;if (aerospike_key_apply(&as, &err, NULL, &key, "mymodule", "add",     (as_list *) &args, &result) != AEROSPIKE_OK) {    fprintf(stderr, "err(%d) %s at [%s:%d]\n", err.code, err.message, err.file, err.line);}

UDF函數bin_trransform()的返回值將在參數對象result中返回。

若記錄鍵對應的記錄不存在,當UDF函數被發現則返回AEROSPIKE_ERR_RECORD_NOT_FOUND,否則返回UDF執行階段錯誤,錯誤細節在as_error的成員域中返回。

清理資源

當不再需要返回的結果時,應釋放它及其相關資源:

as_val_destroy(&result);

同時,也就清理參數列表:

as_arraylist_destroy(&args);

在這裡記錄鍵不需要顯式銷毀,因為它及其成員均建立於棧。


原文連結: http://www.aerospike.com/docs/client/c/usage/udf/apply.html譯       者: 歪脖大肚子Q  

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.