天天看點

表格存儲 Java SDK 開發入門

準備工作

在您開始Tablestore SDK開發前,需確定已開通表格存儲服務并且已建立表格存儲執行個體。

您需要提前擷取到以下幾個參數

開發簡介

開發示例中将以訂單場景為例,使用Tablestore SDK實作如下幾個功能。

  • 訂單表建立。
  • 訂單插入。
  • 訂單号查詢。
  • 訂單搜尋。
字段名 字段類型 字段描述
order_id String 主鍵 訂單号
customer_name 屬性列 消費者姓名
product_name 産品名
product_type 産品類型
order_time 下單時間
pay_time 支付時間

訂單表

開發步驟

初始化連接配接

Tablestore支援Http/Https協定通路服務端,使用Java SDK發起請求前,您需要初始化一個OTSClinet執行個體,初始化需要擷取到服務位址(endpoint)、執行個體名(instanceName)、密鑰(accessKeyId、accessSecret)等資訊。代碼如下

public static void main(String[] args) {
 SyncClient syncClient = new SyncClient(
        "https://order-instance.cn-beijing.ots.aliyuncs.com",//your endpoint,此處可選擇公網位址
        "",//your accessKeyId
        "",//your accessSecret
        "order-instance");//your instance name
    //operation_method(syncClinet);//operation method
}      

建立資料表

示例代碼中建立了一張訂單資料表order。

public static void createOrderTable(SyncClient syncClient){
        TableOptions tableOptions = new TableOptions();
        tableOptions.setMaxVersions(1);
        tableOptions.setTimeToLive(-1);
        TableMeta tableMeta = new TableMeta("order");//設定表名
        tableMeta.addPrimaryKeyColumn("order_id",PrimaryKeyType.STRING);//設定主鍵
        CreateTableRequest createTableRequest = new CreateTableRequest(tableMeta,tableOptions);
        syncClient.createTable(createTableRequest);//發送建立表請求
        System.out.println("create order table succeed");
    }      

寫入資料

示例代碼中寫入了一條訂單資料,訂單号order_id為“o1”。樣例中模拟了一萬條訂單資料,這裡不作展示。

public static void putOrder(SyncClient syncClient){
        RowPutChange rowPutChange = new RowPutChange("order");//設定表名
        rowPutChange.setPrimaryKey(PrimaryKeyBuilder.createPrimaryKeyBuilder()
                .addPrimaryKeyColumn("order_id",PrimaryKeyValue.fromString("o1"))//設定主鍵
                .build());
        rowPutChange.addColumns(Arrays.asList(
             new Column("customer_name",ColumnValue.fromString("消十一")),//設定屬性列資訊
             new Column("product_name",ColumnValue.fromString("iphone 6")),
             new Column("product_type",ColumnValue.fromString("手機")),
             new Column("order_time",ColumnValue.fromString("2021-10-25 09:20:01")),
             new Column("pay_time",ColumnValue.fromString("2017-10-25 10:00:01"))
        ));
        syncClient.putRow(new PutRowRequest(rowPutChange));//發送插入資料請求
        System.out.println("put order succeed");
    }      

查詢資料

示例代碼中查詢訂單号order_id為“o1”的記錄

public static void getOrder(SyncClient syncClient){
        SingleRowQueryCriteria criteria = new SingleRowQueryCriteria("order");//設定表名
        criteria.setPrimaryKey(PrimaryKeyBuilder.createPrimaryKeyBuilder()
                .addPrimaryKeyColumn("order_id",PrimaryKeyValue.fromString("o1"))//設定主鍵
                .build());
        criteria.setMaxVersions(1);
        GetRowResponse response = syncClient.getRow(new GetRowRequest(criteria));//發送讀取資料請求
        System.out.println(response.getRow());
    }      

建立多元索引

示例代碼中建立了一個多元索引order_index。分别設定customer_name字元串類型、order_time字元串類型、pay_time字元串類型、product_name分詞類型、product_type字元串類型。關于索引字段類型的介紹請參考

多元索引概述

public static void createSearchIndex(SyncClient syncClient){
        CreateSearchIndexRequest createSearchIndexRequest =
                new CreateSearchIndexRequest("order","order_index");//設定表名和索引名
        IndexSchema indexSchema = new IndexSchema();
        indexSchema.setFieldSchemas(Arrays.asList(//設定索引結構
                new FieldSchema("customer_name",FieldType.KEYWORD),
                new FieldSchema("order_time",FieldType.KEYWORD),
                new FieldSchema("pay_time",FieldType.KEYWORD),
                new FieldSchema("product_name",FieldType.TEXT),
                new FieldSchema("product_type",FieldType.KEYWORD)
        ));
        createSearchIndexRequest.setIndexSchema(indexSchema);
        syncClient.createSearchIndex(createSearchIndexRequest);//發送建立索引請求
        System.out.println("create search index succeed");
    }      

搜尋資料

示例代碼中查詢産品類型為“手機”的訂單,并統計了符合條件的行數。

public static void searchQuery1(SyncClient syncClient){
        SearchRequest searchRequest = SearchRequest.newBuilder()
                .tableName("order").indexName("order_index")//設定表名、索引名
                .searchQuery(SearchQuery.newBuilder()
                        .query(QueryBuilders.term("product_type","手機"))//查詢類型為手機的記錄
                        .getTotalCount(true)//擷取查詢命中的行數
                        .build())
                .returnAllColumns(true)
                .build();
        SearchResponse response = syncClient.search(searchRequest);
        System.out.println("total rows:" + response.getTotalCount());
        for(Row row : response.getRows()){
            System.out.println(row);
        }
    }      

示例代碼中搜尋産品名包含“iphone”的訂單,并統計了符合條件的行數。

public static void searchQuery2(SyncClient syncClient){
        SearchRequest searchRequest = SearchRequest.newBuilder()
                .tableName("order").indexName("order_index")//設定表名、索引名
                .searchQuery(SearchQuery.newBuilder()
                        .query(QueryBuilders.match("product_name","iphone"))//搜尋産品名中包含iphone的行
                        .getTotalCount(true)//擷取查詢命中的行數
                        .build())
                .returnAllColumns(true)
                .build();
        SearchResponse response = syncClient.search(searchRequest);
        System.out.println("total rows:" + response.getTotalCount());
        for(Row row : response.getRows()){
            System.out.println(row);
        }
    }      

示例代碼中查詢了消費者姓名為“消十一”并且下單時間在“2021-10-24 00:00:00”之間的訂單。并統計了行數。

public static void searchQuery3(SyncClient syncClient){
        SearchRequest searchRequest = SearchRequest.newBuilder()
                .tableName("order").indexName("order_index")//設定表名、索引名
                .searchQuery(SearchQuery.newBuilder()
                        .query(QueryBuilders.bool()
                                .must(QueryBuilders.term("customer_name","消十一"))
                                .must(QueryBuilders.range("order_time").lessThan("2021-10-24 00:00:00")))
                        .getTotalCount(true)//擷取查詢命中的行數
                        .build())
                .returnAllColumns(true)
                .build();
        SearchResponse response = syncClient.search(searchRequest);
        System.out.println("total rows:" + response.getTotalCount());
        for(Row row : response.getRows()){
            System.out.println(row);
        }
    }      

删除多元索引

示例代碼中展示了删除訂單表order中的order_index多元索引。

public static void deleteSearchIndex(SyncClient syncClient){
        DeleteSearchIndexRequest deleteSearchIndexRequest = 
                new DeleteSearchIndexRequest();
        deleteSearchIndexRequest.setTableName("order");
        deleteSearchIndexRequest.setIndexName("order_index");
        syncClient.deleteSearchIndex(deleteSearchIndexRequest);
        System.out.println("delete search index succeed");
    }      

删除資料表

示例代碼中展示了删除訂單表order。删除表之前需確定先删除表中的多元索引。

public static void deleteTable(SyncClient syncClient){
        syncClient.deleteTable(new DeleteTableRequest("order"));//發送删除資料表請求
        System.out.println("delete table succeed");
    }      

更多關于Tablestore JAVA SDK的介紹請參考

Tablestore JAVA SDK