Question

I'm trying to write a simple C++ program that uses Berkeley DB for storage. The key of the database is of type time_t and the data is an integer.

I need to take the difference between two adjacent data in a between two key. I open a cursor with the flag DB_SET_RANGE and then i use DB_NEXT to iterate.

My problem is that the cursor returns unsorted data. Is there a way to specify a custom sorter function for the cursor?

Was it helpful?

Solution

Some of the reasons why you may want to provide a custom sorting function are:

You are using a little-endian system (such as x86) and you are using integers as your database's keys. Berkeley DB stores keys as byte strings and little-endian integers do not sort well when viewed as byte strings. There are several solutions to this problem, one being to provide a custom comparison function. See http://www.oracle.com/technology/documentation/berkeley-db/db/ref/am_misc/faq.html for more information.

You set a BTree's key comparison function using DB->set_bt_compare().

For example, an example routine that is used to sort integer keys in the database is:

int
compare_int(DB *dbp, const DBT *a, const DBT *b)
{
    int ai, bi;

    /* 
     * Returns: 
     * < 0 if a < b 
     * = 0 if a = b 
     * > 0 if a > b 
     */ 
    memcpy(&ai, a->data, sizeof(int)); 
    memcpy(&bi, b->data, sizeof(int)); 
    return (ai - bi); 
} 

OTHER TIPS

I think you have to create a secondary index for your data.

I had tried Sleeping Cat Berkeley Database (due to code maintenance) but I did not try secondary indices.
If perfomance isn't so critical and you can switch database engine, I recommend SQLite :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top