地址、用戶和時間bin都是以空字符(NULL)分割的字符串。地址、用戶和時間是同步的,這樣一個頁面浏覽相關的值在各個bin中是相同的索引位置。
as_operations ops;
as_operations_inita(&ops, 5);
as_operations_add_write_int64(&ops, "last-updated", timestamp);
as_operations_add_incr(&ops, "views", 1);
as_operations_add_append_raw(&ops, "addr", (uint8_t*)addr, strlen(addr) + 1);
as_operations_add_append_raw(&ops, "user", (uint8_t*)user, strlen(user) + 1);
as_operations_add_append_raw(&ops, "time", (uint8_t*)time, strlen(time) + 1);
as_key key;
as_key_init(&key, "app", "pages", url);
if (aerospike_key_operate(&as, &err, NULL, &key, &ops, &rec) != AEROSPIKE_OK) {
fprintf(stderr, "err(%d) %s at [%s:%d]\n", err.code, err.message, err.file, err.line);
}
as_operations_destroy(&ops);
增加與讀取
增加與讀取是常見的操作順序。允許應用使用一個計數器並在每次增加後讀取值。
下面是一個頁面浏覽計數器。記錄的鍵是URL,包含計數器的bin名稱為“views”。
由於要執行讀操作,所以需要提供一個記錄對象用於填充讀取的記錄數值。
as_operations ops;
as_operations_inita(&ops, 2);
as_operations_add_incr(&ops, "views", 1);
as_operations_add_read(&ops, "views");
as_record _rec;
as_record *rec = as_record_inita(&_rec, 1);
as_key key;
as_key_init(&key, "app", "pages", url);
if (aerospike_key_operate(&as, &err, NULL, &key, &ops, &rec) != AEROSPIKE_OK) {
fprintf(stderr, "err(%d) %s at [%s:%d]\n", err.code, err.message, err.file, err.line);
}
else {
printf("views = %ld\n", as_record_get_int64(rec, "views", 0));
}
as_record_destroy(rec);
as_operations_destroy(&ops);
Touching記錄
每條記錄都包含元數據,比如:記錄的分代編號(generation )和生存時間(TTL)。分代編號可被認為是記錄的版本號,記錄每次更新時會增加。生存時間是記錄失效的到期時間。讀取記錄時,這些值都不會被修改。若一條記錄的生存時間是5分鐘,即使是不斷地讀取,5分鐘過後它也不再可用。為了保證記錄不失效,可使用touch操作。
下面的例子,讀取3個bin並touch一條記錄,使其不至失效。我們要從數據庫中讀取這些bin,所以初始化了一個容納3個bin的記錄對象。
as_operations ops;
as_operations_inita(&ops, 4);
as_operations_add_touch(&ops);
as_operations_add_read(&ops, "x");
as_operations_add_read(&ops, "y");
as_operations_add_read(&ops, "z");
as_record _rec;
as_record *rec = as_record_inita(&_rec, 3);
as_key key;
as_key_init(&key, "app", "pages", url);
if (aerospike_key_operate(&as, &err, NULL, &key, &ops, &rec) != AEROSPIKE_OK) {
fprintf(stderr, "err(%d) %s at [%s:%d]\n", err.code, err.message, err.file, err.line);
}
else {
printf("x = %ld\n", as_record_get_int64(rec, "x", 0));
printf("y = %ld\n", as_record_get_int64(rec, "y", 0));
printf("z = %ld\n", as_record_get_int64(rec, "z", 0));
}
as_record_destroy(rec);
as_operations_destroy(&ops);