在查詢中使用 String 函數

字串上有各種內建函數。在任何字串中,位置會從 0 開始,且以長度 - 1 結束。

如果您想要跟隨範例,請參閱 以檢視範例資料,並使用指令碼載入測試的範例資料。命令檔會建立範例中使用的表格,並將資料載入表格中。

如果您想要跟隨範例,請參閱執行查詢的範例資料以檢視範例資料,並瞭解如何使用 OCI 主控台建立範例表格,並使用 JSON 檔案載入資料。

子串函數

substring 函數會根據指定的數值開始位置和指定的數值子字串長度,從指定的字串擷取字串。
returnvalue substring (source, position [, substring_length] )

source ::= any*
position ::= integer*
substring_length ::= integer*
returnvalue ::= string
範例:從車票號碼為 1762376407826 的乘客路由詳細資訊擷取前三個字元。
SELECT substring(bag.baginfo.routing,0,3) AS Source 
FROM baggageInfo bag 
WHERE ticketNo=1762376407826
輸出:
{"Source":"JFK"}

串接函數

concat 函數會串連其所有引數,並將串連字串顯示為輸出。
returnvalue concat (source,[source*])
source ::= any*
returnvalue ::= string
範例:顯示特定標牌號碼為「passenger_name 的路由為 ...」之客戶的路由。
SELECT concat("The route for passenger ",fullName , " is ", bag.baginfo[0].routing)
FROM baggageInfo bag 
WHERE ticketNo=1762376407826
輸出:
{"Column_1":"The route for passenger Dierdre Amador is JFK/MAD"}

上下函數

upperlower 是簡單函數,可分別轉換為大寫或小寫。upper 函數會將字串中的所有字元轉換成大寫。lower 函數會將字串中的所有字元轉換為小寫。
returnvalue upper (source)
returnvalue lower (source) 

source ::= any* 
returnvalue ::= string
範例 1:以大寫字母擷取乘客的完整名稱,其機票號碼為 1762376407826
SELECT upper(fullname) AS FULLNAME_CAPITALS 
FROM BaggageInfo 
WHERE ticketNo=1762376407826
輸出:
{"FULLNAME_CAPITALS":"DIERDRE AMADOR"}
範例 2:以小寫字母擷取乘客的完整名稱,其機票號碼為 1762376407826
SELECT lower(fullname) AS fullname_lowercase
FROM BaggageInfo WHERE ticketNo=1762376407826
輸出:
{"fullname_lowercase":"dierdre amador"}

修剪函數

trim 函數可讓您移除字串的前端或尾端字元 (或都移除)。ltrim 函數可讓您從字串中刪減前置字元。rtrim 函數可讓您從字串中刪減尾端字元。
returnvalue trim(source [, position [, trim_character]])

source ::= any*
position ::= "leading"|"trailing"|"both"
trim_character ::= string*
returnvalue ::= string
returnvalue ltrim(source)

returnvalue rtrim(source)
source ::= any*
returnvalue ::= string
範例:從車票號碼為 1762350390409 之乘客的路線詳細資料中移除前置空格與尾端空格。
SELECT trim(bag.baginfo[0].routing,"trailing"," ")
FROM BaggageInfo bag 
WHERE ticketNo=1762376407826
輸出:
{"Column_1":"JFK/MAD"}
使用 ltrim 函數移除前置空格:
SELECT ltrim(bag.baginfo[0].routing)
FROM BaggageInfo bag 
WHERE ticketNo=1762376407826
輸出:
{"Column_1":"JFK/MAD"}
使用 rtrim 函數移除尾端空格:
SELECT rtrim(bag.baginfo[0].routing)
FROM BaggageInfo bag 
WHERE ticketNo=1762376407826
輸出:
{"Column_1":"JFK/MAD"}

長度函數

length 函數會傳回字元字串的長度。長度函數會使用 UTF 字元集來計算長度。
returnvalue length(source)

source ::= any*
returnvalue ::= integer
範例:尋找機票號碼為 1762350390409 的乘客全名長度。
SELECT fullname, length(fullname) AS fullname_length 
FROM BaggageInfo
WHERE ticketNo=1762350390409
輸出:
{"fullname":"Fallon Clements","fullname_length":15}

包含函數

contains 函數會指出來源字串中是否有搜尋字串。
returnvalue contains(source, search_string)

source ::= any*
search_string ::= any*
returnvalue ::= boolean
範例:擷取路線中具有 "SFO" 的乘客全名。
SELECT fullname FROM baggageInfo bag 
WHERE EXISTS bag.bagInfo[contains($element.routing,"SFO")]
輸出:
{"fullname":"Michelle Payne"}
{"fullname":"Lucinda Beckman"}
{"fullname":"Henry Jenkins"}
{"fullname":"Lorenzo Phil"}
{"fullname":"Gerard Greene"}

starts_with 和 ends_with 函數

starts_with 函數會指出來源字串是否以搜尋字串開頭。
returnvalue starts_with(source, search_string)

source ::= any*
search_string ::= any*
returnvalue ::= boolean
ends_with 函數會指出來源字串是否以搜尋字串結尾。
returnvalue ends_with(source, search_string)

source ::= any*
search_string ::= any*
returnvalue ::= boolean
範例:從辦理登機手續到機票號碼為 176234463813 之乘客登機時掃描行李的時間,需要多久時間?
SELECT $flightLeg.flightNo,
$flightLeg.actions[contains($element.actionCode, "Checkin")].actionTime AS checkinTime,
$flightLeg.actions[contains($element.actionCode, "BagTag Scan")].actionTime AS bagScanTime,
timestamp_diff(
   $flightLeg.actions[contains($element.actionCode, "Checkin")].actionTime,
   $flightLeg.actions[contains($element.actionCode, "BagTag Scan")].actionTime
) AS diff
FROM baggageinfo $s, $s.bagInfo[].flightLegs[] AS $flightLeg
WHERE ticketNo=176234463813 
AND starts_with($s.bagInfo[].routing, $flightLeg.fltRouteSrc)

說明:在行李資料中,每個 flightLeg 都有一個動作陣列。動作陣列中有三個不同的動作。陣列中第一個元素的動作代碼為「存回 / 卸載」。針對第一個航段,作業代碼為「存回」,而針對其他航段,作業代碼為跳躍點的「卸載」。陣列之第二個元素的動作代碼為 BagTag 掃描。在上面的查詢中,您可以決定行李箱標籤掃描與入住時間之間的動作時間差異。只有在動作代碼為「存入」或 BagScan 時,才能使用 contains 函數來篩選動作時間。由於只有第一個航班航段具有辦理登機手續和行李掃描的詳細資料,因此您使用 starts_with 函數額外篩選資料,僅擷取原始碼 fltRouteSrc

輸出:
{"flightNo":"BM572","checkinTime":"2019-03-02T03:28:00Z",
"bagScanTime":"2019-03-02T04:52:00Z","diff":-5040000}
範例 2:尋找目的地為 JTR 的乘客清單。
SELECT fullname FROM baggageInfo $bagInfo 
WHERE ends_with($bagInfo.bagInfo[].routing, "JTR")
輸出:
{"fullname":"Lucinda Beckman"}
{"fullname":"Gerard Greene"}
{"fullname":"Michelle Payne"}

index_of 函數

index_of 函數會決定搜尋字串第一個出現位置 (如果有的話) 的第一個字元位置。
returnvalue index_of(source, search_string [, start_position])

source ::= any*
search_string ::= any*
start_position ::= integer*
returnvalue ::= integer
各種傳回值:
  • 傳回第一次出現時搜尋字串第一個字元的位置。此位置相對於字串的開始位置 (為零)。
  • 如果來源中沒有 search_string,則傳回 -1。
  • 如果 search_string 的長度為 0,則為來源的任何值傳回 0。
  • 如果任何引數為 NULL,則傳回 NULL。
  • 如果任一引數是空的序列或含有多個項目的序列,則傳回 NULL。
  • 如果 start_position 引數不是整數,則傳回錯誤。
範例 1:決定在票號為 1762320569757 之乘客第一段的預估抵達時間中找到哪個位置 "-"。
SELECT index_of(bag.baginfo.flightLegs[0].estimatedArrival,"-")
FROM BaggageInfo bag 
WHERE ticketNo=1762320569757
輸出:
{"Column_1":4}
範例 2:決定票號碼為 1762320569757 的乘客第一段路程中找到的位置 "/"。這將協助您判斷機票號碼為 1762320569757 的乘客來源點有多少字元。
SELECT index_of(bag.baginfo.routing,"/") 
FROM BaggageInfo bag 
WHERE ticketNo=1762320569757
輸出:
"Column_1":3}

取代功能

replace 函數會傳回來源,其中每個出現的搜尋字串都會以取代字串取代。
returnvalue replace(source, search_string [, replacement_string])

source ::= any*
search_string ::= any*
replacement_string ::= any*
returnvalue ::= string
範例:將乘客的來源地點取代為 SFO 至 SOF 的機票號碼 1762320569757
SELECT replace(bag.bagInfo[0].routing,"SFO","SOF") 
FROM baggageInfo bag
WHERE ticketNo=1762320569757
輸出:
{"Column_1":"SOF/IST/ATH/JTR"}

範例 2:以單引號取代乘客名稱中的雙引號。

如果您的資料在乘客姓名中可能包含雙引號,您可以使用取代函數將雙引號變更為單引號。
SELECT fullname, 
replace(fullname, "\"", "'") as new_fullname
FROM BaggageInfo bag

逆函數

reverse 函數會以相反順序傳回來源字串的字元,其中字串是以最後一個字元為開頭。
returnvalue reverse(source)

source ::= any*
returnvalue ::= string
範例:顯示全名並回轉票號為 1762330498104 的乘客全名。
SELECT fullname, reverse(fullname) 
FROM baggageInfo
WHERE ticketNo=1762330498104
輸出:
{"fullname":"Michelle Payne","Column_2":"enyaP ellehciM"}

使用 QueryRequest API 的範例

您可以使用 QueryRequest API 並套用 SQL 函數,從 NoSQL 表格擷取資料。

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

Download the full code SQLFunctions.java from the examples here.
 //Fetch rows from the table
private static void fetchRows(NoSQLHandle handle,String sqlstmt) throws Exception {
   try (
      QueryRequest queryRequest = new QueryRequest().setStatement(sqlstmt);
      QueryIterableResult results = handle.queryIterable(queryRequest)){
      for (MapValue res : results) {
         System.out.println("\t" + res);
      }
   }
} 
String string_func1="SELECT substring(bag.baginfo.routing,0,3) AS Source FROM baggageInfo bag WHERE ticketNo=1762376407826";
System.out.println("Using substring function ");
fetchRows(handle,string_func1);
String string_func2="SELECT fullname, length(fullname) AS fullname_length FROM BaggageInfo WHERE ticketNo=1762320369957";
System.out.println("Using length function ");
fetchRows(handle,string_func2);
String string_func3="SELECT fullname FROM baggageInfo bag WHERE EXISTS bag.bagInfo[contains($element.routing,\"SFO\")]";
System.out.println("Using contains function ");
fetchRows(handle,string_func3);

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

Download the full code SQLFunctions.py from the examples here.
# Fetch data from the table
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))  

 string_func1 = '''SELECT substring(bag.baginfo.routing,0,3) AS Source FROM baggageInfo bag
                     WHERE ticketNo=1762376407826'''
 print('Using substring function:')
 fetch_data(handle,string_func1)

 string_func2 = '''SELECT fullname, length(fullname) AS fullname_length FROM BaggageInfo
                     WHERE ticketNo=1762320369957'''
 print('Using length function:')
 fetch_data(handle,string_func2)

 string_func3 = '''SELECT fullname FROM baggageInfo bag WHERE
                     EXISTS bag.bagInfo[contains($element.routing,"SFO")]'''
 print('Using contains function:')
 fetch_data(handle,string_func3)

若要執行查詢,請使用 Client.Query 函數。

Download the full code SQLFunctions.go from the examples here.
 //fetch data from the table
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()))
   }
} 
string_func1 := `SELECT substring(bag.baginfo.routing,0,3) AS Source FROM baggageInfo bag
                    WHERE ticketNo=1762376407826`
fmt.Printf("Using substring function:\n")
fetchData(client, err,tableName,string_func1)

string_func2 := `SELECT fullname, length(fullname) AS fullname_length FROM BaggageInfo
                    WHERE ticketNo=1762320369957`
fmt.Printf("Using length function:\n")
fetchData(client, err,tableName,string_func2)

string_func3 := `SELECT fullname FROM baggageInfo bag WHERE
                    EXISTS bag.bagInfo[contains($element.routing,"SFO")]`
fmt.Printf("Using contains function:\n")
fetchData(client, err,tableName,string_func3)

若要執行查詢,請使用 query 方法。

JavaScript: Download the full code SQLFunctions.js from the examples here.
  //fetches data from the table
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);
   }
}
TypeScript: Download the full code SQLFunctions.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: any) {
   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);
   }
}
const string_func1 = `SELECT substring(bag.baginfo.routing,0,3) AS Source FROM baggageInfo bag
                      WHERE ticketNo=1762376407826`
console.log("Using substring function:");
await fetchData(handle,string_func1);

const string_func2 = `SELECT fullname, length(fullname) AS fullname_length FROM BaggageInfo
                      WHERE ticketNo=1762320369957`
console.log("Using length function");
await fetchData(handle,string_func2);

const string_func3 = `SELECT fullname FROM baggageInfo bag WHERE
                      EXISTS bag.bagInfo[contains($element.routing,"SFO")]`
console.log("Using contains function");
await fetchData(handle,string_func3);

若要執行查詢,您可以呼叫 QueryAsync 方法或呼叫 GetQueryAsyncEnumerable 方法,然後重複產生的非同步可列舉。

Download the full code SQLFunctions.cs from the examples here.
private static async Task fetchData(NoSQLClient client,String querystmt){
   var queryEnumerable = client.GetQueryAsyncEnumerable(querystmt);
   await DoQuery(queryEnumerable);
}

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());
      }
   }
} 
private const string string_func1 =@"SELECT substring(bag.baginfo.routing,0,3) AS Source FROM baggageInfo bag
                                           WHERE ticketNo=1762376407826" ;
Console.WriteLine("\nUsing substring function!");
await fetchData(client,string_func1);

private const string string_func2 =@"SELECT fullname, length(fullname) AS fullname_length FROM BaggageInfo
                                           WHERE ticketNo=1762320369957";
Console.WriteLine("\nUsing length function!");
await fetchData(client,string_func2);


private const string string_func3 =@"SELECT fullname FROM baggageInfo bag WHERE
                                           EXISTS bag.bagInfo[contains($element.routing,""SFO"")]";
Console.WriteLine("\nUsing contains function!");
await fetchData(client,string_func3);