0

我正在使用 tokyo cabinet 实现一个 btree,但我想知道是否可以对值进行排序。我知道我可以使用 atcbdbsetcmpfunc为键设置自定义比较功能,但不确定值?

我问这个是因为大多数时候我只需要前 1000 条记录,假设我的值已排序。否则我将不得不对数百万条记录进行循环排序并获得前 1000 条记录,这可能会很慢。

例如:

#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;
}
4

2 回答 2

0

我认为您无法定义值的顺序。

我建议有第二个 tokyocabinet db,从值映射到键。我希望通过这种间接方式,您仍然可以获得不错的性能。

于 2014-04-10T07:34:01.627 回答
0

东京内阁没有嵌入排序机制。您可以喜欢使用列表和自定义排序

于 2015-12-21T14:35:53.553 回答