Skip to content

Instantly share code, notes, and snippets.

@msh5
Created August 5, 2018 13:08
Show Gist options
  • Save msh5/2dc2914fbc901b309511f7c9b95e3a46 to your computer and use it in GitHub Desktop.
Save msh5/2dc2914fbc901b309511f7c9b95e3a46 to your computer and use it in GitHub Desktop.
Groonga Cライブラリ テーブルのレコード参照(https://qiita.com/msh5/items/90dbf582ae2b30ec3f11
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <groonga/groonga.h>
#define TABLE_NAME "table"
int main (int argc, char **argv) {
// ライブラリを初期化
assert(grn_init() == GRN_SUCCESS);
// コンテキストを取得
grn_ctx *ctx = grn_ctx_open(0);
assert(ctx != NULL);
// データベースを作成
grn_obj *db = grn_db_create(ctx, NULL, NULL);
assert(db != NULL);
// テーブルを作成
grn_obj *short_text_type = grn_ctx_at(ctx, GRN_DB_SHORT_TEXT);
assert(short_text_type != NULL);
grn_obj *table = grn_table_create(ctx, TABLE_NAME, strlen(TABLE_NAME), NULL,
GRN_OBJ_TEMPORARY | GRN_OBJ_TABLE_HASH_KEY,
short_text_type, NULL);
assert(table != NULL);
// レコードを作成
grn_id record_id = grn_table_add(ctx, table, "test_record", strlen("test_record"), NULL);
assert(record_id != GRN_ID_NIL);
// 主キー値によるレコードIDの取得
assert(grn_table_get(ctx, table, "test_record", strlen("test_record")) == record_id);
// レコードIDによる主キー値の取得
char keybuf[16];
int keylen = grn_table_get_key(ctx, table, record_id, keybuf, 16);
assert(keylen == strlen("test_record"));
assert(strncmp("test_record", keybuf, keylen) == 0);
// テーブルカーソルによる巡回参照
grn_table_cursor *table_cursor = grn_table_cursor_open(ctx, table, NULL, 0, NULL, 0, 0, -1,
GRN_CURSOR_BY_ID | GRN_CURSOR_ASCENDING);
assert(table_cursor != NULL);
assert(grn_table_cursor_next(ctx, table_cursor) == record_id);
// レコードの巡回が完了した
assert(grn_table_cursor_next(ctx, table_cursor) == GRN_ID_NIL);
assert(grn_table_cursor_close(ctx, table_cursor) == GRN_SUCCESS);
// リソースを破棄
grn_obj_unlink(ctx, table);
grn_obj_unlink(ctx, db);
assert(grn_ctx_close(ctx) == GRN_SUCCESS);
// ライブラリを終了する
assert(grn_fin() == GRN_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment