全部產品
Search
文件中心

Tablestore:多元索引快速入門

更新時間:Apr 28, 2025

本文介紹通過Java SDK快速使用多元索引的操作。

前提條件

使用流程

步驟一:建立多元索引

建立多元索引用於加速資料查詢。建立多元索引時,您需要將要查詢的欄位添加到多元索引中,您還可以按需配置多元索引的資料生命週期、預排序等進階選項。

以下樣本用於為資料表建立一個多元索引,多元索引包含Col_Keyword和Col_Long兩列,類型分別設定為字串(Keyword)和整型(Long)。多元索引按照資料表主鍵進行預排序且資料永不到期。

說明

多元索引支援的資料類型以及多元索引與資料表的資料類型映射請參見多元索引資料類型

private static void createSearchIndex(SyncClient client) {
    CreateSearchIndexRequest request = new CreateSearchIndexRequest();
    //設定資料表名稱。
    request.setTableName("sampletable"); 
    //設定多元索引名稱。
    request.setIndexName("samplesearchindex"); 
    IndexSchema indexSchema = new IndexSchema();
    indexSchema.setFieldSchemas(Arrays.asList(
            //設定欄位名和類型。
            new FieldSchema("Col_Keyword", FieldType.KEYWORD), 
            new FieldSchema("Col_Long", FieldType.LONG)));
    request.setIndexSchema(indexSchema);
    //調用client建立多元索引。
    client.createSearchIndex(request); 
}

步驟二:使用多元索引查詢資料

使用多元索引查詢資料時,請根據實際查詢情境選擇合適的查詢類型。查詢資料時支援配置要返回的列以及返回資料的排序方式。

以下樣本用於查詢表中Col_Keyword列精確匹配"hangzhou"的資料。

/**
 * 查詢表中Col_Keyword列精確匹配"hangzhou"的資料。
 * @param client
 */
private static void termQuery(SyncClient client) {
    SearchQuery searchQuery = new SearchQuery();
    TermQuery termQuery = new TermQuery(); //設定查詢類型為TermQuery。
    termQuery.setFieldName("Col_Keyword"); //設定要匹配的欄位。
    termQuery.setTerm(ColumnValue.fromString("hangzhou")); //設定要匹配的值。
    searchQuery.setQuery(termQuery);
    //searchQuery.setGetTotalCount(true); //設定返回匹配的總行數。

    SearchRequest searchRequest = new SearchRequest("sampletable", "samplesearchindex", searchQuery);
    //通過設定columnsToGet參數可以指定返回的列或返回所有列,如果不設定此參數,則預設只返回主鍵列。
    //SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
    //columnsToGet.setReturnAll(true); //設定為返回所有列。
    //columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); //設定為返回指定列。
    //searchRequest.setColumnsToGet(columnsToGet);

    SearchResponse resp = client.search(searchRequest);
    //System.out.println("TotalCount: " + resp.getTotalCount()); //列印匹配到的總行數,非返回行數。
    System.out.println("Row: " + resp.getRows());
}

相關文檔