Writing and Reading

Accumulo Tour: Writing and Reading

Tour page 2 of 11

Accumulo is a big key/value store. Writing data to Accumulo is flexible and fast. Like any database, Accumulo stores data in tables and rows. Each row in an Accumulo table can hold many key/value pairs. Our next exercise shows how to write and read from a table.

static void exercise(MiniAccumuloCluster mac) {
    // Connect to Mini Accumulo as the root user and create a table called "GothamPD".
    Connector conn = mac.getConnector("root", "tourguide");
    conn.tableOperations().create("GothamPD");

    // Create a Mutation object to hold all changes to a row in a table.  Each row has a unique row ID.
    Mutation mutation = new Mutation("id0001");

    // Create key/value pairs for Batman.  Put them in the "hero" family.
    mutation.put("hero","alias", "Batman");
    mutation.put("hero","name", "Bruce Wayne");
    mutation.put("hero","wearsCape?", "true");

    // Create a BatchWriter to the GothamPD table and add your mutation to it. Try w/ resources will close for us.
    try (BatchWriter writer = conn.createBatchWriter("GothamPD", new BatchWriterConfig())) {
        writer.addMutation(mutation);
    }

    // Read and print all rows of the "GothamPD" table. Try w/ resources will close for us.
    try (Scanner scan = conn.createScanner("GothamPD", Authorizations.EMPTY)) {
        System.out.println("Gotham Police Department Persons of Interest:");
        // A Scanner is an extension of java.lang.Iterable so behaves just like one.
        for (Map.Entry<Key, Value> entry : scan) {
            System.out.printf("Key : %-50s  Value : %s\n", entry.getKey(), entry.getValue());
        }
    }
}

Copy this code into your exercise method and run it using the command below.

mvn -q clean compile exec:java

Good job! That is all it takes to write and read from Accumulo.

Notice a lot of other information was printed from the Keys we created. Accumulo is flexible because hidden within its Key is a rich data model that can be broken up into different parts. We will cover the Data Model in the next lesson.

But wait… I thought Accumulo was all about Security?

Spoiler Alert: it is! Did you notice the Authorizations.EMPTY we passed in when creating a Scanner? The data we created in this first lesson was not secured with Authorizations so the Scanner didn’t require any Authorizations to read it. More to come later in the Authorizations lesson!

< 2 / 11 >