In an earlier article, I showed how Sicstus Prolog allows us to use Berkeley DB for storage and retrieval of terms using the file system. Interestingly, the latest release of Sicstus Prolog, version 4.7.0, deprecates the Berekely DB library, while recommending an alternative implementation based on Lightning Memory-Mapped Database Manager (LMDB). The library interfaces are quite similar, so it is easy to port from BDB to LMDB.
For this article, I am going to use the same Homeopathic Remedies example that I used in the earlier article. The file “remedies.pl” contains simple facts about a few homeopathic remedies:
Here is the code to create a new database, given an input Prolog file and corresponding Index specification:
As you might notice, one difference from the BDB library is the need to call “lmdb_create” explicitly.
Here is how we can create the actual DB in Sicstus Prolog’s IDE:
What if we wish to add some facts after creating the database? Here is the code that facilitates updates:
Using it is straightforward:
The new fact to insert is passed as the second argument.
A majority of the times, we would want to open the database, perform some operations, and then close the database. The code for opening and closing are given below:
One useful functionality is to retrieve all terms that match a template:
Obviously, this feature is useful only when we are expecting a “manageable” number of terms as result. In general, it is a good idea to be able to perform some “operation” on “matching” facts in the database.
Let us put the above ideas to work.
Since we know that our toy DB contains very few facts, let us retrieve all of them in one go:
This time, let us fetch terms that correspond to “abbrev”:
This also works as expected.
To illustrate the use of “traversal”, let us define a predicate to print any given term:
First, let us visit all the “abbrev” terms and print them:
Great. Now traverse all terms in the database:
Everything seems to work as expected.
One additional useful feature is the ability to export the contents of the database to a text file. Here is the code:
We can now export our toy database thus:
Here is the resulting text file:
This text file can be “imported” into another database if needed. That part is quite easy to implement and I am not detailing the code here.
Finally, we have to close the database:
Well, that is it! Using the new LMDB library poses no surprises.
Here is the ZIP file that contains the source, sample data and the exported text file.
Have a nice weekend!
Recent Comments