简体   繁体   English

使用C中的东京橱柜按值自定义排序

[英]Custom sort by value using tokyo cabinet in C

I'm implementing a btree using tokyo cabinet, but I'd like to know if it's possible to keep the values sorted. 我正在使用东京内阁实现btree,但我想知道是否可以对值进行排序。 I know I can use a tcbdbsetcmpfunc to set the custom comparison function for the keys, but not sure about the values? 我知道我可以使用tcbdbsetcmpfunc设置键的自定义比较功能,但是不确定值吗?

I ask this because most of the time I only need the first 1000 records assuming my values are sorted. 我之所以这样问,是因为在大多数情况下,我只需要对前1000条记录进行排序即可。 Otherwise I will have to loop over millions of records sort them and get the first 1000, which can be slow. 否则,我将不得不遍历数百万条记录,对它们进行排序并获得前1000条,这可能会很慢。

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

I think you cannot define an order for values. 我认为您无法定义值的顺序。

I recommend to have a second tokyocabinet db, mapping from values to keys. 我建议再创建一个tokyocabinet数据库,从值到键的映射。 I expect that with this one indirection you still get nice performance. 我希望通过这种间接方式仍然可以获得不错的性能。

The tokyo cabinet have not the embed sort mechanism. 东京内阁没有嵌入分类机制。 You can like to use the list and it self custom ordering 您可以使用列表及其自定义排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM