OBKV-Table provides general distributed storage capabilities, and simple key-value storage is a special case of OBKV-Table. This topic uses examples to describe how to simulate simple KV operations with OBKV-Table.
Schema
The underlying storage engine of OBKV-Table is based on a table model, so all data must be stored in tables. In a simple KV scenario, you only need to create one table. The reference schema is as follows:
CREATE TABLE IF NOT EXISTS `kv_table` (
`key` varchar(1024) NOT NULL,
`value` varbinary(1048576) DEFAULT NULL,
PRIMARY KEY (`key`)
);
The schema is described as follows:
- In the sample schema, the key can be up to 1 KB and the value can be up to 1 MB. This schema meets the requirements of most use cases.
- In practice, you can define the key and value types and constraints for your business scenario by referring to the table creation specifications of OceanBase AI Database. If a typical business scenario involves storing very large values, you can use a large object type of OceanBase AI Database for the value.
Configure and connect to the database
The following example uses the direct connection mode.
ObTableClient obkvHandle = new ObTableClient();
obkvHandle.setFullUserName("");
obkvHandle.setParamURL("");
obkvHandle.setPassword("");
obkvHandle.setSysUserName("");
obkvHandle.setSysPassword("");
obkvHandle.init();
Data access
put
public void put(Object key, Object value) throws Exception {
MutationResult result = obkvHandle.insert("kv_table")
.setRowKey(colVal("key", key))
.addMutateColVal(colVal("value", value))
.execute();
}
get
public Object get(Object key) throws Exception {
QueryResultSet result = obkvHandle.query("kv_table")
.select("value")
.setScanRangeColumns("key")
.addScanRange(key,key)
.execute();
}
del
public void del(Object key) throws Exception {
MutationResult result = obkvHandle.delete("kv_table")
.setRowKey(colVal("key", key))
.execute();
}
batch
public class writeBatch {
BatchOperation batch = null;
ObTableClient kvHandle = null;
public writeBatch(ObTableClient handle) {
kvHandle = handle;
batch = handle.batchOperation("kv_table");
}
public void put(Object key, Object value) throws Exception {
Insert insert = insert().setRowKey(colVal("key", key))
.addMutateColVal(colVal("value", value));
batch.addOperation(insert);
}
public void del(Object key) throws Exception {
Delete del = delete().setRowKey(colVal("key", key));
batch.addOperation(del);
}
public BatchOperationResult execute() throws Exception {
return batch.execute();
}
}