2017-04-07 64 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

相关问题