Mini Cassandra

Cassandra is a NoSQL database (a.k.a key-value storage). One individual data entry in cassandra constructed by 3 parts:

  1. row_key. (a.k.a hash_key, partition key or sharding_key.)
  2. column_key.
  3. value

row_key is used to hash and can not support range query. Let's simplify this to a string.
column_key is sorted and support range query. Let's simplify this to integer.
value is a string. You can serialize any data into a string and store it in value.

Implement the following methods:

  1. insert(row_key, column_key, value)
  2. query(row_key, column_start, column_end) return a list of entries

Example

Example 1:

Input:
  insert("google", 1, "haha")
  query("google", 0, 1)
Output: [(1, "haha")]

思路:一个 row_key 可以对应多个 Column; 而一个 row_key 和一个 column_key 是唯一确定对应的 value 的.

可以使用哈希表套哈希表实现: map<row_key, map<column_key, value>>

每次 insert 直接更新 value 即可.

而 query 则需要取出一个 row_key 对应的所有的 <column_key, value> 对, 如果 column_key 在给定范围内时, 放入答案序列中即可.

/**
 * 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 HashMap<String, HashMap<Integer, String>> hashmap;
    public MiniCassandra() {
        hashmap = new HashMap<String, HashMap<Integer, String>>();
    }

    /*
     * @param raw_key: a string
     * @param column_key: An integer
     * @param column_value: a string
     * @return: nothing
     */
    public void insert(String row_key, int column_key, String value) {
        hashmap.putIfAbsent(row_key, new HashMap<Integer, String>());
        hashmap.get(row_key).put(column_key, value);
    }

    /*
     * @param row_key: a string
     * @param column_start: An integer
     * @param column_end: An integer
     * @return: a list of Columns
     */
    public List<Column> query(String row_key, int column_start, int column_end) {
        List<Column> list = new ArrayList<Column>();
        if(hashmap.containsKey(row_key)) {
            HashMap<Integer, String> columnMap = hashmap.get(row_key);
            for(int i = column_start; i <= column_end; i++) {
                if(columnMap.containsKey(i)){
                    list.add(new Column(i, columnMap.get(i)));
                }
            }
        }
        return list;
    }
}
发布了569 篇原创文章 · 获赞 13 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104047329