Cassandra is a NoSQL database (a.k.a key-value storage). One individual data entry in cassandra constructed by 3 parts:
- row_key. (a.k.a hash_key, partition key or sharding_key.)
- column_key.
- 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:
insert(row_key, column_key, value)
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")]
Ideas: a row_key may correspond to a plurality of the Column; and a row_key column_key uniquely determined and a value corresponds.
You can use a hash table sets hash table to achieve: map<row_key, map<column_key, value>>
Every time insert
directly update the value can be.
And query
the need to remove a corresponding row_key all <column_key, value> pair, if column_key when within a given range, the answer in the sequence can be placed.
/**
* 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;
}
}