Kraeze has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

It is my first time asking a question here.

Background: I have used the perl api for Kyoto Cabinet, given here: http://fallabs.com/kyotocabinet/. I opted to use the B Tree implementation and would like to write my own comparator. As the keys are sorted lexicographically by default, it does not suit my keys.

My keys are stored as intervals e.g. "1-50", representing the start and end positions of bases in a biological sequence. Hence to order them I would compare only the first integer.

The only information I have found in the API is the following paragraph:

"The default record comparator is the lexical ordering function. That is, records in the B+ tree database are placed in the lexical order of each key. If you want to use another ordering, call `tune_comparator' to set a functor which implements the ordering function." Ref: Tuning the File Tree Database @ http://fallabs.com/kyotocabinet/spex.html

Question:How do I write my own comparator in perl? Thank you in advance.

  • Comment on Howto: Comparator for B-Tree in Kyoto Cabinet

Replies are listed 'Best First'.
Re: Howto: Comparator for B-Tree in Kyoto Cabinet
by Corion (Patriarch) on Jul 03, 2015 at 06:21 UTC

    The easiest approach would be to make your keys lexically sortable by padding them:

    my $key = sprintf "%010d-%010d", $low, $high;

    This only works if you want to sort by start position and then by end position (or length).

      Hi Corion,

      Thank you for your reply. I see what your saying. I spent a few hours trying to determine how to write a comparator and yours seems to be the simpliest solution.

      Just to ensure that there is no method provided by the API, I emailed the author. I will post back here should I get a reply. I just thought the Perl Monks would be much faster and provide me with a clean, honest approach. Thanks again!

Re: Howto: Comparator for B-Tree in Kyoto Cabinet
by QM (Parson) on Jul 03, 2015 at 08:16 UTC
    Skimming the docs, it seems that there are only predefined comparators. That is, it's not obvious to me how to write your own. You have a few to choose from, which don't seem to be clearly documented.

    So it seems Corion's idea is spot on: make your keys sort lexicographically.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      Hi QM,

      Thanks for looking through the docs for me. I feel more confident that I didn't miss anything. Thank you!