UpdateJSON.updateTableWithIndex()

The UpdateJSON.updateTableWithIndex() method performs the update using an index.

This read operation is considerably easier to implement than the previous method because we do not need to perform all the error checking. This method is also more efficient because only the table rows identified by the index are returned, resulting in less network traffic and fewer rows for our code to examine. However, if the required index does not exist, then this method will fail.

    // Update the zip code found on all Boston home addresses
    // to "02102-1000"
    //
    // Because we have an index available to us, we only have to look
    // at those rows which have person.address.home.city = Boston. 
    // All other rows are skipped during the read operation.
    private void updateTableWithIndex(KVStore kvstore) {
        TableAPI tableH = kvstore.getTableAPI();
        Table myTable = tableH.getTable("personContacts");

        // Construct the IndexKey.
        Index homeCityIdx = myTable.getIndex("idx_home_city");
        IndexKey homeCityIdxKey = null;

        // If NullPointerException is thrown by createIndexKey(),
        // it means that the required index has not been created.
        // Run the createIndex() method before running this method.
        homeCityIdxKey = homeCityIdx.createIndexKey();

        // Return only those entries with a home city of "Boston"
        homeCityIdxKey.put("person.address.home.city", "Boston");

        // Iterate over the returned table rows. Because we're
        // using an index, we're guaranteed that 
        // person.address.home.city exists and equals Boston
        // for every table row seen here.
        TableIterator<Row> iter =
            tableH.tableIterator(homeCityIdxKey, null, null);
        try {
            while (iter.hasNext()) {
                Row row = iter.next();
                updateZipCode(tableH, row, "home", "02102-1000");
            }
        } finally {
            if (iter != null) {
            iter.close();
            }
        }
        System.out.println("Updated a table using an index.");
    }