I'm implementing a btree using tokyo cabinet, but I'd like to know if it's possible to keep the values sorted. I know I can use a tcbdbsetcmpfunc
to set the custom comparison function for the keys, but not sure about the values?
I ask this because most of the time I only need the first 1000 records assuming my values are sorted. Otherwise I will have to loop over millions of records sort them and get the first 1000, which can be slow.
For instance:
#include <tcutil.h>
#include <tcbdb.h>
#include <stdbool.h>
#include <stdint.h>
struct foo {
int one;
double two;
char *three;
};
// sort by three field
static int val_cmp(const char *aptr, int asiz, const char *bptr, int bsiz, void *op) {
return 1;
}
int main() {
int ecode;
TCBDB *db;
db = tcbdbnew();
struct foo *f;
tcbdbsetcmpfunc(db, val_cmp, f); // sort by struct->three?
// open the database
if(!tcbdbopen(db, "struct.tcb", BDBOWRITER | BDBOCREAT)){
ecode = tcbdbecode(db);
fprintf(stderr, "open error: %s\n", tcbdberrmsg(ecode));
}
f = malloc(sizeof(struct foo));
f->one = 100;
f->two = 1.1111;
f->three = "Hello World";
printf("put: %d\n", tcbdbput(db, "foo", 3, f, sizeof(struct foo)));
f = malloc(sizeof(struct foo));
f->one = 100;
f->two = 1.1111;
f->three = "Hello Planet";
printf("put: %d\n", tcbdbput(db, "bar", 3, f, sizeof(struct foo)));
char *key;
BDBCUR *cursor;
cursor = tcbdbcurnew(db);
tcbdbcurfirst(cursor);
while ((key = tcbdbcurkey2(cursor)) != NULL) {
struct foo *val;
int size;
val = tcbdbcurval(cursor, &size);
printf("%s: one=%d\n", key, val->one);
printf("%s: two=%f\n", key, val->two);
tcbdbcurnext(cursor);
}
tcbdbdel(db);
return 0;
}