使用查詢 API 擷取資料

您可以使用 QueryRequest 來建構從 NoSQL 表格篩選資料的查詢。

若要執行查詢,請使用 NoSQLHandle.query() API。請參閱 Oracle NoSQL Java SDK API Reference ,瞭解各種類別和方法的詳細資訊。

有兩種方法可以取得查詢的結果:使用重複程式或循環執行部分結果。
  • 迭代器:使用 NoSQLHandle.queryIterable(QueryRequest) 取得包含所有結果的可重複項目。
  • 部分結果:若要計算和擷取查詢的完整結果集,必須多次執行相同的 QueryRequest 執行處理 (透過 NoSQLHandle.query(oracle.nosql.driver.ops.QueryRequest))。每個執行都會傳回 QueryRequest,其中包含結果集的子集。
String sqlstmt_allrows="SELECT * FROM stream_acct";
private static void fetchRows(NoSQLHandle handle,String sqlstmt) 
                                              throws Exception {
   try (
      QueryRequest queryRequest = 
            new QueryRequest().setStatement(sqlstmt_allrows);

      QueryIterableResult results = 
            handle.queryIterable(queryRequest)){

      for (MapValue res : results) {
         System.out.println("\t" + res);
      }
   }
}
您也可以使用查詢中的 WHERE 子句來套用篩選條件。
String sqlstmt_allrows=
"SELECT account_expiry, acct.acct_data.lastName, 
acct.acct_data.contentStreamed[].showName 
FROM stream_acct acct WHERE acct_id=1";
此處的範例下載完整程式碼 QueryData.java

附註:

若要從子項表格擷取資料,請在 SQL 敘述句中指定表格 (parent_tablename.child_tablename) 的完整名稱。從範例下載完整程式碼 TableJoins.java,瞭解如何從此處的父項子項表格擷取資料。

若要執行查詢,請使用 borneo.NoSQLHandle.query() 方法。

有兩種方法可以取得查詢的結果:使用重複程式或循環執行部分結果。
  • 使用 borneo.NoSQLHandle.query_iterable() 取得包含查詢所有結果的可重複項目。
  • 您可以使用 borneo.NoSQLHandle.query() 方法循環執行部分結果。例如,若要執行 SELECT 查詢以從您的表格讀取資料,borneo.QueryResult 會包含結果清單。如果 borneo.QueryRequest.is_done() 傳回 False,則可能會有更多結果,因此查詢通常會以迴圈執行。單一要求可以傳回沒有結果,但查詢仍未完成,表示查詢迴圈應該繼續。
sqlstmt = 'SELECT * FROM stream_acct'

def fetch_data(handle,sqlstmt):
   request = QueryRequest().set_statement(sqlstmt)
   print('Query results for: ' + sqlstmt)

   result = handle.query(request)
   for r in result.get_results():
      print('\t' + str(r))
您也可以使用查詢中的 WHERE 子句來套用篩選條件。
sqlstmt = 'SELECT account_expiry, acct.acct_data.lastName,
acct.acct_data.contentStreamed[].showName 
FROM stream_acct acct WHERE acct_id=1'
Download the full code QueryData.py from the examples here.

附註:

若要從子項表格擷取資料,請在 SQL 敘述句中指定表格 (parent_tablename.child_tablename) 的完整名稱。從範例下載完整程式碼 TableJoins.py ,瞭解如何在此處從父項子項表格擷取資料。

若要執行查詢,請使用 Client.Query 函數。在雲端服務上執行時,單一查詢要求所讀取的資料量會受到系統預設值的限制,而且可以使用 QueryRequest.MaxReadKB 進一步限制。這會限制讀取的資料量,而不是傳回的資料量,這表示查詢可以傳回零結果,但仍有更多資料可供讀取。因此,查詢應該一律以迴圈方式運作,取得更多結果,直到 QueryRequest.IsDone() 傳回 true,表示查詢已完成。

querystmt := "select * FROM stream_acct"

func fetchData(client *nosqldb.Client, err error, 
               tableName string, querystmt string)(){
   prepReq := &nosqldb.PrepareRequest{ Statement: querystmt,}

   prepRes, err := client.Prepare(prepReq)
   if err != nil {
      fmt.Printf("Prepare failed: %v\n", err)
      return
   }

   queryReq := &nosqldb.QueryRequest{
		 PreparedStatement: &prepRes.PreparedStatement,}
   var results []*types.MapValue

   for {
      queryRes, err := client.Query(queryReq)
      if err != nil {
         fmt.Printf("Query failed: %v\n", err)
	  return
      }
      res, err := queryRes.GetResults()

      if err != nil {
         fmt.Printf("GetResults() failed: %v\n", err)
  	return
      }

      results = append(results, res...)
      if queryReq.IsDone() {
         break
      }
   }
   for i, r := range results {
      fmt.Printf("\t%d: %s\n", i+1, 
                  jsonutil.AsJSON(r.Map()))
   }
}
您也可以使用查詢中的 WHERE 子句來套用篩選條件。
querystmt := "SELECT account_expiry, acct.acct_data.lastName, 
acct.acct_data.contentStreamed[].showName 
FROM stream_acct acct where acct_id=1"
Download the full code QueryData.go from the examples here.

附註:

若要從子項表格擷取資料,請在 SQL 敘述句中指定表格 (parent_tablename.child_tablename) 的完整名稱。從範例下載完整程式碼 TableJoins.go,瞭解如何從此處的父項子項表格擷取資料。
您可以使用下列其中一種方法,從 NoSQL 表格查詢資料。如需方法詳細資訊,請參閱 NoSQLClient 類別。
  1. 使用 query 方法來執行查詢。這個方法會傳回 QueryResultPromise ,這是包含結果列陣列與連續鍵值的純 JavaScript 物件。您可以用兩種方式使用 query 方法:
    • 對於最多存取一個資料列的查詢,您只能呼叫 query 方法一次。這些查詢只能包含以主索引鍵為基礎的選取陳述式 (where 子句必須根據完整主索引鍵來指定相等性)。在所有其他情況下,您可以在迴圈或 queryIterable 方法中使用 query
    • 您可以在迴圈中呼叫 query 方法來擷取多個資料列。由於查詢傳回的資料量受系統預設值限制,且可在 queryone 呼叫 query 方法的 QueryOpt 引數中設定 maxReadKB 特性來進一步限制,因此無法傳回所有可用的結果。若要解決此問題,請以迴圈方式執行查詢,直到 QueryResult 中的 continuationKey 變為 null / undefined 為止。
  2. 使用 queryIterable 方法重複查詢結果。這個方法會傳回一個可重複的物件,您可以用 for-await-of 迴圈來重複此物件。您不需要在此方法中管理延續。

    附註:

    您也可以將 queryIterable 方法與 continuationKey 以外的特性搭配使用 QueryOpt 引數。
JavaScript: Download the full code QueryData.js from the examples here.
const querystmt = 'SELECT * FROM stream_acct';

async function fetchData(handle,querystmt) {
    const opt = {};

    try {
        do {
            const result = await handle.query(querystmt, opt);
            for(let row of result.rows) {
                console.log('  %O', row);
            }

            opt.continuationKey = result.continuationKey;
        } while(opt.continuationKey);
    } catch(error) {
        console.error('  Error: ' + error.message);
    }
}
您也可以使用查詢中的 WHERE 子句來套用篩選條件。
const querystmt = 
'SELECT account_expiry, acct.acct_data.lastName, 
acct.acct_data.contentStreamed[].showName 
FROM stream_acct acct WHERE acct_id=1';
TypeScript:您可以使用上述 JavaScript 中 TypeScript 所述的相同方法。您也可以提供選擇性的查詢結果綱要作為 query 方法的類型參數,為 QueryResult 傳回的資料列提供類型提示。這不需要與表格資料列綱要相同 (除非使用 SELECT * 查詢),因為查詢可以包含投影、名稱別名、聚總值等等。Download the full code QueryData.ts from the examples here.
interface StreamInt {
   acct_Id: Integer;
   profile_name: String;
   account_expiry: TIMESTAMP;
   acct_data: JSON;
}
/* fetches data from the table */
async function fetchData(handle: NoSQLClient,querystmt: string) {
   const opt = {};
   try {
      do {
         const result = await handle.query<StreamInt>(querystmt, opt);
         for(let row of result.rows) {
            console.log('  %O', row);
         }
         opt.continuationKey = result.continuationKey;
      } while(opt.continuationKey);
   } catch(error) {
      console.error('  Error: ' + error.message);
   }
}
您也可以使用查詢中的 WHERE 子句來套用篩選條件。
const querystmt = 
'SELECT account_expiry, acct.acct_data.lastName, 
acct.acct_data.contentStreamed[].showName 
FROM stream_acct acct WHERE acct_id=1';

附註:

若要從子項表格擷取資料,請在 SQL 敘述句中指定表格 (parent_tablename.child_tablename) 的完整名稱。Download the full JavaScript code TableJoins.js here and the full TypeScript code TableJoins.ts here to understand how to fetch data from a parent-child table.

若要執行查詢,您可以呼叫 QueryAsync 方法或呼叫 GetQueryAsyncEnumerable 方法,然後重複產生的非同步可列舉。您可以將這些方法的選項傳遞為 QueryOptionsQueryAsync 方法傳回 Task<QueryResult<RecordValue>>QueryResult 包含查詢結果作為 RecordValue 執行處理清單以及其他資訊。當您的查詢指定完整的主索引鍵時,就足以呼叫 QueryAsync 一次。查詢傳回的資料量受系統限制。它也可以透過設定 QueryOptionsMaxReadKB 特性來進一步限制。這表示一個呼叫 QueryAsync 可能不會傳回所有可用的結果。使用連續鍵來處理此情況。QueryResult 中的非空值連續索引鍵表示可能有更多查詢結果。這表示查詢應該在迴圈中執行,迴圈直到連續索引鍵變為空值為止。請參閱 Oracle NoSQL Dotnet SDK API Reference ,瞭解所有類別和方法的詳細資訊。

private const string querystmt ="SELECT * FROM stream_acct";

private static async Task fetchData(NoSQLClient client,String querystmt){
   var queryEnumerable = client.GetQueryAsyncEnumerable(querystmt);
   await DoQuery(queryEnumerable);
 }

//function to display result
private static async Task 
   DoQuery(IAsyncEnumerable<QueryResult<RecordValue>> queryEnumerable){
   Console.WriteLine("  Query results:");

   await foreach (var result in queryEnumerable) {
      foreach (var row in result.Rows)
      {
         Console.WriteLine();
         Console.WriteLine(row.ToJsonString());
      }
   }
}
您也可以使用查詢中的 WHERE 子句來套用篩選條件。
private const string querystmt =
"SELECT account_expiry, acct.acct_data.lastName, 
acct.acct_data.contentStreamed[].showName 
FROM stream_acct acct WHERE acct_id=1";
Download the full code QueryData.cs from the examples here.

附註:

若要從子項表格擷取資料,請在 SQL 敘述句中指定表格 (parent_tablename.child_tablename) 的完整名稱。從範例下載完整程式碼 TableJoins.cs,瞭解如何從此處的父項子項表格擷取資料。