2017-04-07 78 views

回答

1

要使用REST API查詢DocumentDB資源,首先需要爲REST API調用生成Azure documentDB auth標頭。有關更多詳細信息,請參閱official documentation和我的earlier post。其次,您可以通過使用包httr進行HTTP請求來與DocumentDB進行交互。

有關如何使用REST查詢DocumentDB資源的更多信息,請參閱https://docs.microsoft.com/en-us/rest/api/documentdb/querying-documentdb-resources-using-the-rest-api

下面是一個示例代碼通過使用REST來自R客戶列出的所有數據庫:

library(digest) 
library(base64enc) 
library(httr) 

Sys.setlocale("LC_TIME", "English") 

endpoint = "https://{your-database-account}.documents.azure.com"; 
masterKey = "aTPETGJNV3u7ht9Ip2mo..."; # replace with your master key     

currentDate <- tolower(format(Sys.time(), "%a, %d %b %Y %T", tz = "GMT", usetz = TRUE)) 

generateMasterKeyAuthorizationSignature <- function(verb, resourceId, resourceType) { 

    key <- base64decode(masterKey) 
    text <- sprintf("%s\n", paste(tolower(verb), tolower(resourceType), resourceId, currentDate, "", sep="\n")) 
    body <- enc2utf8(text) 
    signature <- base64encode(hmac(key, body, algo = "sha256", raw = T)) 
    token <- sprintf("type=master&ver=1.0&sig=%s", signature) 

    return(URLencode(token, reserved = TRUE)) 

} 


# LIST all databases 

verb <- "GET" 
resourceType <- "dbs" 
resourceLink <- "dbs" 
resourceId = "" 

authHeader = generateMasterKeyAuthorizationSignature(verb, resourceId, resourceType) 

headers <- c("x-ms-documentdb-isquery" = "True", 
      "x-ms-date" = currentDate, 
      "x-ms-version" = "2015-08-06", 
      "authorization" = authHeader) 

r <- GET(paste(endpoint, resourceLink, sep = "/"), add_headers(headers)) 
print(content(r, "text")) 

執行查詢

# EXECUTE a query 

databaseId <- "FamilyDB"  # replace with your database ID  
collectionId <- "FamilyColl" # replace with your collection ID 
verb <- "POST" 
resourceType <- "docs" 
resourceLink <- sprintf("dbs/%s/colls/%s/docs", databaseId, collectionId) 
resourceId = sprintf("dbs/%s/colls/%s", databaseId, collectionId) 

authHeader = generateMasterKeyAuthorizationSignature(verb, resourceId, resourceType) 

headers <- c("x-ms-documentdb-isquery" = "True", 
      "x-ms-date" = currentDate, 
      "x-ms-version" = "2015-08-06", 
      "authorization" = authHeader, 
      "Content-Type" = "application/query+json") 

body = list("query" = "SELECT * FROM c")    

r <- POST(paste(endpoint, resourceLink, sep = "/"), add_headers(headers), body = body, encode = "json") 
print(content(r, "text")) 
+0

感謝您的幫助,我跟隨您的早期博客,我現在能夠得到生成的密鑰「f2jgWXb2BAQUK4eVk8RSNwDu7eT/Yeq + uNFgmR4fRoNY =」,之後,不能得到如何使用此密鑰。 - @Aaron Chen - MSFT – Tappy

+0

好吧,我看了一下,今天晚些時候我會分享一些細節。 –

+0

非常感謝 - @Aaron Chen - MSFT,它解決了。 :) – Tappy

相關問題