0

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;
}
Pete Darrow
  • 455
  • 5
  • 20

2 Answers2

0

I think you cannot define an order for values.

I recommend to have a second tokyocabinet db, mapping from values to keys. I expect that with this one indirection you still get nice performance.

Sven
  • 496
  • 4
  • 9
0

The tokyo cabinet have not the embed sort mechanism. You can like to use the list and it self custom ordering

Alexandre Kalendarev
  • 681
  • 2
  • 10
  • 24