PageRenderTime 1225ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/doc/GettingStarted.rst

https://github.com/eliantor/sonar-persistit
ReStructuredText | 271 lines | 187 code | 84 blank | 0 comment | 0 complexity | c102aa7c076e68f4ed4a58dfbd121b26 MD5 | raw file
  1. Getting Started with Akiban Persistit
  2. =====================================
  3. Welcome!
  4. We have worked hard to make Akiban Persistit exceptionally fast, reliable, simple and lightweight. We hope you will enjoy learning more about it and using it.
  5. Akiban Persistit is a key/value data storage library written in Java. Key features include:
  6. - support for highly concurrent transaction processing with multi-version concurrency control
  7. - optimized serialization and deserialization mechanism for Java primitives and objects
  8. - multi-segment (compound) keys to enable a natural logical key hierarchy
  9. - support for long records (megabytes)
  10. - implementation of a persistent SortedMap
  11. - extensive management capability including command-line and GUI tools
  12. This chapter briefly and informally introduces and demonstrates various Persistit features through examples. Subsequent chapters and the Javadoc API documentation provides a detailed reference guide to the product.
  13. Download and Install
  14. --------------------
  15. Download |zip_file_name| from the `Launchpad project <https://launchpad.net/akiban-persistit/+download>`_ or directly from `akiban.com <http://www.akiban.com/akiban-persistit>`_.
  16. Unpack the distribution kit into a convenient directory using any unzip utility. For example, use |unpack_zip_cmd| to unpack the distribution kit into the current working directory.
  17. Review the ``LICENSE.txt`` file located in the root of the installation directory. Persistit is licensed under the Eclipse Public License or a free-use community license, see our `licensing options <http://www.akiban.com/akiban-licensing-options>`_ for more details. By installing, copying or otherwise using the Software contained in the distribution kit, you agree to be bound by the terms of the license agreement. If you do not agree to these terms, remove and destroy all copies of the software in your possession immediately.
  18. Working with Persistit
  19. ----------------------
  20. Add the |jar_file_name|, is found in the root directory of the distribution kit, to your project's classpath. For example, copy it to ``jre/lib/ext`` in your Java Runtime Environment, or add it to your classpath environment variable.
  21. That's it. You are ready to work with Persistit.
  22. Examples
  23. ^^^^^^^^
  24. Review the ``examples`` directory. Here you will find functional examples of varying complexity.
  25. ``examples/HelloWorld``
  26. source code for the example illustrating this chapter
  27. ``examples/SimpleDemo``
  28. short, simple program similar to HelloWorld
  29. ``examples/SimpleBench``
  30.   a small micro-benchmark measuring the speed of insert, traversal, random updates, etc.
  31. ``examples/SimpleTransaction``
  32. example demonstrating use of Persisits multi-version currency control (MVCC) transactions
  33. ``examples/FindFile``
  34. a somewhat larger example that uses Persistit as the backing store for file finder utility
  35. ``examples/PersistitMapDemo``
  36. demonstration of the PersistitMap interface
  37. ``examples/SpringFrameworkExample``
  38. configures and initializes a Persistit instance through Spring Framework
  39. HelloWorld
  40. ----------
  41. Before going further let's honor tradition with a small program that stores, fetches and displays the phrase “Hello World.” In this program we will create a record with the key “Hello” and the value “World”.
  42. **HelloWorld.java**
  43. .. code-block:: java
  44. import com.persistit.Exchange;
  45. import com.persistit.Key;
  46. import com.persistit.Persistit;
  47. public class HelloWorld {
  48. public static void main(String[] args) throws Exception {
  49. Persistit db = new Persistit();
  50. try {
  51. // Read configuration from persistit.properties, allocate
  52. // buffers, open Volume, and perform recovery processing
  53. // if necessary.
  54. //
  55. db.initialize();
  56. //
  57. // Create an Exchange, which is a thread-private facade for
  58. // accessing data in a Persistit Tree. This Exchange will
  59. // access a Tree called "greetings" in a Volume called
  60. // "hwdemo". It will create a new Tree by that name
  61. // if one does not already exist.
  62. //
  63. Exchange dbex = db.getExchange("hwdemo", "greetings", true);
  64. //
  65. // Set up the Value field of the Exchange.
  66. //
  67. dbex.getValue().put("World");
  68. //
  69. // Set up the Key field of the Exchange.
  70. //
  71. dbex.getKey().append("Hello");
  72. //
  73. // Ask Persistit to put this key/value pair into the Tree.
  74. // Until this point, the changes to the Exchange are local
  75. // to this thread.
  76. //
  77. dbex.store();
  78. //
  79. // Prepare to traverse all the keys in the Tree (of which there
  80. // is currently only one!) and for each key display its value.
  81. //
  82. dbex.getKey().to(Key.BEFORE);
  83. while (dbex.next()) {
  84. System.out.println(dbex.getKey().indexTo(0).decode() + " "
  85. + dbex.getValue().get());
  86. }
  87. db.releaseExchange(dbex);
  88. } finally {
  89. // Always close Persistit. If the application does not do
  90. // this, Persistit's background threads will keep the JVM from
  91. // terminating.
  92. //
  93. db.close();
  94. }
  95. }
  96. }
  97. Concepts
  98. --------
  99. Although ``HelloWorld.java`` is not very useful, it demonstrates several of the basic building blocks of the Persistit API.
  100. Initialization and Configuration
  101. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  102. Before accessing any data, ``HelloWorld.java`` calls the ``com.persistit.Persistit#initialize()`` method. This sets up the memory configuration for buffers and the path names of Persistit volume and journal files. Alternative methods accept configuration information from a ``com.persistit.Configuration`` object, a ``java.util.Properties`` object, a specified properties file, or by default from the file named ``persistit.properties`` in the current working directory.
  103. In this example, ``persistit.properties`` looks like this::
  104. datapath=.
  105. buffer.count.8192=32
  106. volume.1=${datapath}/hwdemo,create,pageSize:8192,initialPages:5,extensionPages:5,maximumPages:100000
  107. journalpath=${datapath}/hwdemo_journal
  108. See :ref:`Configuration` for additional information about Persistit configuration properties.
  109. Volumes and Trees
  110. ^^^^^^^^^^^^^^^^^
  111. A configuration defines one or more volume files that will contain stored Persistit data. Usually you will specify the ``create`` flag, which allows Persistit to create a new volume if the file does not already exist. Creating a new file also establishes the initial size and growth parameters for that volume.
  112. Each volume may contain an unlimited number of named trees. Each tree within a volume embodies a logically distinct B+Tree index structure. Think of a tree as simply a named key space within a volume.
  113. ``HelloWorld.java`` stores its key/value pair in a tree called greetings in a volume named hwdemo. This is specified by constructing an Exchange.
  114. Exchanges
  115. ---------
  116. The ``com.persistit.Exchange`` class is the primary facade for interacting with Persistit data. It is so-named because it allows an application to exchange information with the database. An Exchange provides methods for storing, deleting, fetching and traversing key/value pairs.
  117. The method
  118. .. code-block:: java
  119. Exchange dbex = db.getExchange("hwdemo", "greetings", true);
  120. in ``HelloWorld.java`` finds a volume named "hwdemo" and attempts to find a tree in it named "greetings". If there is no such tree, ``getExchange`` creates it.
  121. Methods ``com.persistit.Persistit#getExchange`` and ``com.persistit.Persistit#releaseExchange`` maintain a pool of reusable Exchange objects designed for use by multi-threaded applications such as web applications. If a suitable exchange already exists, ``getExchange`` returns it; otherwise it constructs a new one.
  122. The Exchange looks up the volume name hwdemo by matching it against the volumes specified in the configuration. The match is based on the simple file name of the volume after removing its final dotted suffix. For example, the volume name hwdemo matches the volume specification ``${datapath}/hwdemo.v00``.
  123. Each Exchange is implicitly associated with a ``com.persistit.Key`` and a ``com.persistit.Value``. Typically you work with an Exchange in one of the following patterns:
  124. - Modify the Key, modify the Value and then perform a ``com.persistit.Exchange#store`` operation.
  125. - Modify the Key, perform a ``com.persistit.Exchange#fetch`` operation and then read the Value.
  126. - Modify the Key and then perform a ``com.persistit.Exchange#remove`` operation.
  127. - Optionally modify the Key, perform a ``com.persistit.Exchange#next``, ``com.persistit.Exchange#previous`` or ``com.persistit.Exchange#traverse`` operation, then read the resulting Key and/or Value.
  128. These methods and their variants provide the foundation for using Persistit.
  129. Records
  130. ^^^^^^^
  131. In Persistit, a database record consists of a Key and a Value. The terms record and key/value pair are used interchangeably.
  132. When you store a record, Persistit searches for a previously stored record having the same key. If there is such a record, Persistit replaces its value. If there is no such record, Persistit inserts a new one. Like a Java Map, Persistit stores at most one value per key, and every record in a Tree has a unique key value.
  133. Keys
  134. ^^^^
  135. A Key contains a unique identifier for key/value pair - or record - in a tree. The identifier consists of a sequence of one or more Java values encoded into an array of bytes stored in the volume file.
  136. Key instances are mutable. Your application typically changes an Exchange's Key in preparation for fetching or retrieving data. In particular, you can append, remove or replace one or more values in a Key. Each value you append is called a *key segment*. You append multiple key segments to implement concatenated keys. See ``com.persistit.Key`` for additional information on constructing keys and the ordering of key traversal within a tree.
  137. The ``HelloWorld.java`` example appends Hello to the Exchanges Key object in this line:
  138. .. code-block:: java
  139. dbex.getKey().append("Hello");
  140. The result is a key with a single key segment.
  141. Values
  142. ^^^^^^
  143. A Value object represents the serialized state of a Java object or a primitive value. It is a staging area for data being transferred from or to the database by ``fetch``, ``traverse`` and ``store`` operations.
  144. Value instances are mutable. The ``fetch`` and ``traverse`` operations modify the state of an Exchange's Value instance to represent the value associated with some Key. Your application executes methods to modify the state of the Value instance in preparation for storing new data values into the database.
  145. Numerous methods allow you to serialize and deserialize primitives values and objects into and from a Value object. For example, in ``HelloWorld.java``, the statement
  146. .. code-block:: java
  147. dbex.getValue().put("World");
  148. serializes the string World into the backing byte array of the Exchanges Value object and
  149. .. code-block:: java
  150. System.out.println(
  151. dbex.getKey().indexTo(0).decode() + " " +
  152. dbex.getValue().get());
  153. deserializes and prints an object value from the Key and another object value from the Value. Value also has methods such as ``getInt``, ``getLong``, ``getByteArray`` to decode primitive and array values directly.
  154. Storing and Fetching Data
  155. ^^^^^^^^^^^^^^^^^^^^^^^^^
  156. Finally, it is these two methods in ``HelloWorld.java`` that cause the Exchange object to share data with the B+Tree, making it persistent and potentially available to other threads:
  157. .. code-block:: java
  158. dbex.store();
  159. ...
  160. while (dbex.next()) { ... }
  161. Closing Persistit
  162. ^^^^^^^^^^^^^^^^^
  163. Persistit creates one or more background threads that lazily write data to the Volume files and perform other maintenance activities. Be sure to invoke the ``com.persistit.Persistit#close`` method to allow these threads to finish their work and exit properly. The pattern illustrated in ``HelloWorld.java``, using a *try/finally* block to invoke ``close``, is strongly recommended.
  164. The ``com.persistit.Persistit#close(boolean)`` method optionally flushes all data to disk from the buffer pool before shutting down. Specifying the ``false`` option will close Persistit more quickly will lose recent updates if they were not performed inside of transactions, or will potentially require a longer recovery process during the next startup to reapply committed transactions.
  165. Additional Topics
  166. -----------------
  167. PersistitMap
  168. ^^^^^^^^^^^^
  169. A particularly easy way to get started with Persistit is to use its built-in ``com.persistit.PersistitMap`` implementation. PersistitMap implements the ``java.util.SortedMap`` interface, so it can directly replace ``java.util.TreeMap`` or other kinds of Map in existing Java code.
  170. See :ref:`PersistitMap`.
  171. KeyFilters
  172. ^^^^^^^^^^
  173. A ``com.persistit.KeyFilter`` can be supplied to restrict the results returned by the ``com.persistit.Exchange#traverse`` methods. You can specify discrete values or ranges for values of individual key segments and apply other simple predicates.
  174. See :ref:`Basic-API`.
  175. Transactions
  176. ^^^^^^^^^^^^
  177. Persistit provides ACID Transaction support with multi-version concurrency control (MVCC) and adjustable durability policy.
  178. See :ref:`Transactions`.
  179. Managing Persistit
  180. ^^^^^^^^^^^^^^^^^^
  181. Persistit provides several mechanisms for managing Persistit operation within an application. These include
  182. - JMX MXBeans
  183. - The ``com.persistit.Management`` object which provides programmatic access to many management operations
  184. - The ``com.persistit.CLI`` object which provides a command-line interface for various management operations
  185. - The AdminUI tool which provides a graphical client interface for examining records and other resources
  186. - Logging interface design for easy embedding in host applications
  187. See :ref:`Management`.