Created
June 5, 2012 16:43
-
-
Save deltheil/2876156 to your computer and use it in GitHub Desktop.
Manipulate lists of records the Redis way via Tokyo Cabinet B+ Tree database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <tcbdb.h> | |
#include <tcutil.h> | |
int main(int argc, char *argv[]) { | |
TCBDB *db = tcbdbnew(); | |
tcbdbopen(db, "list.db", BDBOWRITER | BDBOCREAT | BDBOTRUNC); | |
/* The B+ Tree database features record duplication for a given key | |
(see `tcbdbputdup`) which means we can easily append data for a | |
given key a-la Redis RPUSH. | |
In addition we use (on purpose) integer like primary keys and | |
not directly list names, e.g. FRUITS, etc, to illustrate the | |
key ordering (see below) | |
*/ | |
/* This is equivalent with Redis to: | |
RPUSH FRUITS "orange" | |
RPUSH FRUITS "pear" | |
RPUSH FRUITS "kiwi" | |
*/ | |
tcbdbputdup2(db, "1", "FRUITS"); | |
tcbdbputdup2(db, "1", "orange"); | |
tcbdbputdup2(db, "1", "pear"); | |
tcbdbputdup2(db, "1", "kiwi"); | |
/* This is equivalent with Redis to: | |
RPUSH BRANDS "Coca Cola" | |
RPUSH BRANDS "evian" | |
*/ | |
tcbdbputdup2(db, "2", "BRANDS"); | |
tcbdbputdup2(db, "2", "Coca Cola"); | |
tcbdbputdup2(db, "2", "evian"); | |
BDBCUR *cur = tcbdbcurnew(db); | |
/* The B+ Tree database also features key ordering which allows to retrieve | |
the last (e.g. the most recent) record */ | |
if (tcbdbcurlast(cur)) { | |
TCMAP *uniq = tcmapnew(); | |
for (;;) { | |
int ksiz; | |
const char *kbuf = tcbdbcurkey3(cur, &ksiz); | |
/* WARNING: with record duplication the cursor traverses *all* records | |
Make sure to skip the keys already seen */ | |
if (tcmapputkeep(uniq, kbuf, ksiz, "", 0)) { | |
TCLIST *vals = tcbdbget4(db, kbuf, ksiz); | |
char *head = tclistshift2(vals); | |
char *tail = tcstrjoin(vals, ','); | |
printf("%s -> [%s]\n", head, tail); | |
free(head); | |
free(tail); | |
tclistdel(vals); | |
} | |
if (!tcbdbcurprev(cur)) break; | |
} | |
tcmapdel(uniq); | |
} | |
tcbdbcurdel(cur); | |
tcbdbdel(db); | |
/* Output should be: | |
BRANDS -> [Coca Cola,evian] | |
FRUITS -> [orange,pear,kiwi] | |
*/ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment