如何使用R數據框中的documentdb JSON數據。我嘗試使用簡單的API消耗。如何使用R中的API從Azure DocumentDB中使用數據
library("JSON")
web_page=getURL("documentdb URI", userpwd = "abc:psswrd")
我也跟着鏈接「DocumentDB web API access with R」但無法弄清楚如何進行連接。
如何使用R數據框中的documentdb JSON數據。我嘗試使用簡單的API消耗。如何使用R中的API從Azure DocumentDB中使用數據
library("JSON")
web_page=getURL("documentdb URI", userpwd = "abc:psswrd")
我也跟着鏈接「DocumentDB web API access with R」但無法弄清楚如何進行連接。
要使用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"))
與樣本代碼更新。 –