如何使用R中的API从Azure DocumentDB中获取数据

时间:2017-04-07 10:04:39

标签: azure azure-cosmosdb

如何在R数据帧中使用documentdb JSON数据。我尝试使用简单的API消耗。

library("JSON")
web_page=getURL("documentdb URI", userpwd = "abc:psswrd") 

我也关注了“DocumentDB web API access with R”链接,但无法弄清楚如何连接。

1 个答案:

答案 0 :(得分: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

以下是使用来自R客户端的REST列出所有数据库的示例代码:

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"))