Mini Cassandra

Mini Cassandra

Cassandra is a NoSQL storage. The structure has two-level keys.

Level 1: rawkey. The same as hashkey or shardkey.
Level 2: column
key.
Level 3: columnvalue
raw
key is used to hash and can not support range query. let's simplify this to a string.
columnkey is sorted and support range query. let's simplify this to integer.
column
value is a string. you can serialize any data into a string and store it in column value.

implement the following methods:

  1. insert(rawkey, columnkey, column_value)
  2. query(rawkey, columnstart, column_end) // return a list of entries

Example

insert("google", 1, "haha")  
query("google", 0, 1)  
>> [(1, "haha")]
/**
 * Definition of Column:
 * public class Column {
 *     public int key;
 *     public String value;
 *     public Column(int key, String value) {
 *         this.key = key;
 *         this.value = value;
 *    }
 * }
 */
public class MiniCassandra {  
    private Map<String, NavigableMap<Integer, String>> map;

    public MiniCassandra() {
        map = new HashMap<>();
    }

    /**
     * @param raw_key a string
     * @param column_start an integer
     * @param column_end an integer
     * @return void
     */
    public void insert(String raw_key, int column_key, String column_value) {
        if (!map.containsKey(raw_key)) {
            map.put(raw_key, new TreeMap<Integer, String>());
        }
        map.get(raw_key).put(column_key, column_value);
    }

    /**
     * @param raw_key a string
     * @param column_start an integer
     * @param column_end an integer
     * @return a list of Columns
     */
    public List<Column> query(String raw_key, int column_start, int column_end) {
        List<Column> result = new ArrayList<>();

        if (map.containsKey(raw_key)) {
           NavigableMap<Integer, String> nm = map.get(raw_key).subMap(column_start, true,
           column_end, true);        
           for (Map.Entry<Integer, String> entry : nm.entrySet()) {
               result.add(new Column(entry.getKey(), entry.getValue()));
           } 
        }

        return result;
    }
}

Hope this helps,
Michael