1923

都内と業界の隅っこで生活しているエンジニアのノート

Cosmos DB はじめました

Cosmos DB をちょっと使い始めてみたので書き付け。 最初にCosmos DBはAzureのNoSQLデータベースサービスという程度の知識しかないので、以下のサイトでお勉強。

Azure Cosmos DB Documentation

Azure Cosmos DB入門 - ryuichi111stdの技術日記

Azure Cosmos DB がやってきた

ざっくり概要や特徴などがわかったところで、手を動かして実際に試してみます。
たくさんデータモデルがあるようですが、今回はドキュメント データモデルでDocumentDB APIを使います。最初なので、まずはAzure上にリソースを作成。作ったり・消したりするのでPowerShellでさくっと準備。

データベース アカウントの作成

# ログイン
Login-AzureRmAccount 

# サブスクリプション選択
Select-AzureRmSubscription -SubscriptionId "00000000-0000-0000-0000-000000000000"

# リソースグループの作成
New-AzureRmResourceGroup -Name "RG01" -Location "Japan West" 

# データベース アカウントの作成
$locations = @(@{"locationName"="Japan West"; "failoverPriority"=0})
$ipRangeFilter = ""
$consistencyPolicy = @{"defaultConsistencyLevel"="Session";
                       "maxIntervalInSeconds"= "5";
                       "maxStalenessPrefix"= "100"}
$dbProperties = @{
                  "databaseAccountOfferType"="Standard";
                  "locations"=$locations; 
                  "consistencyPolicy"=$consistencyPolicy; 
                  "ipRangeFilter"=$ipRangeFilter
}

New-AzureRmResource -ResourceType "Microsoft.DocumentDb/databaseAccounts" -ApiVersion "2016-03-31" -ResourceGroupName "RG01" -Location "Japan West" -Name "cosmosdbtest" -PropertyObject $dbProperties

ちなみにApiVersionは以下で確認。

((Get-AzureRmResourceProvider -ProviderNamespace Microsoft.DocumentDb).ResourceTypes | Where-Object ResourceTypeName -eq databaseAccounts).ApiVersions

ということでリソースの準備完了。ついでなので、PowerShellからデータベース、コレクション、ドキュメントもREST APIを使って作成してみます。Authorizationを生成するコードなどは、How to query Azure Cosmos DB resources using the REST API by PowerShellから拝借。ApiVersionはSupported REST API Versionsで確認。

Add-Type -AssemblyName System.Web

# generate authorization key 
Function Generate-MasterKeyAuthorizationSignature 
{ 
    [CmdletBinding()] 
    Param 
    ( 
        [Parameter(Mandatory=$true)][String]$verb, 
        [Parameter(Mandatory=$false)][String]$resourceLink, 
        [Parameter(Mandatory=$true)][String]$resourceType, 
        [Parameter(Mandatory=$true)][String]$dateTime, 
        [Parameter(Mandatory=$true)][String]$key, 
        [Parameter(Mandatory=$true)][String]$keyType, 
        [Parameter(Mandatory=$true)][String]$tokenVersion 
    ) 
 
    $hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256 
    $hmacSha256.Key = [System.Convert]::FromBase64String($key) 
 
    $payLoad = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n" 
    $hashPayLoad = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad)) 
    $signature = [System.Convert]::ToBase64String($hashPayLoad); 
 
    [System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature") 
} 

# いろいろCreate 
Function Create 
{ 
    [CmdletBinding()] 
    Param 
    ( 
        [Parameter(Mandatory=$true)][String]$EndPoint, 
        [Parameter(Mandatory=$true)][String]$DataBaseId, 
        [Parameter(Mandatory=$true)][String]$MasterKey, 
        [Parameter(Mandatory=$true)][String]$ResourceType, 
        [Parameter(Mandatory=$false)][String]$ResourceLink,
        [Parameter(Mandatory=$true)][String]$BodyJson 
    ) 

    $verb = "POST" 
    $dateTime = [DateTime]::UtcNow.ToString("r") 
    $authHeader = Generate-MasterKeyAuthorizationSignature -verb $verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime 
    $header = @{authorization=$authHeader;"x-ms-version"="2017-02-22";"x-ms-date"=$dateTime} 
    $contentType"application/json" 
    $queryUri = "$EndPoint$ResourceLink/$ResourceType" 
 
    $result = Invoke-RestMethod -Method $verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $bodyJson -Debug
    $result | ConvertTo-Json -Depth 10 
} 

# キーを取得
$Keys = Invoke-AzureRmResourceAction -Action listKeys -ResourceType "Microsoft.DocumentDb/databaseAccounts" -ApiVersion "2016-03-31" -ResourceGroupName "RG01" -Name "cosmosdbtest"

# 作るモノの設定
$EndPoint = "https://cosmosdbtest.documents.azure.com/"
$DataBaseId = "hogedb1"
$CollectionId = "hogecoll1"
$DocumentId = "doc01"

# データベース作成
$json = @{"id"="$DataBaseId"} | ConvertTo-Json 
Create -EndPoint $EndPoint -DataBaseId $DataBaseId -MasterKey $Keys.primaryMasterKey -ResourceType "dbs" -ResourceLink "" -BodyJson $json

# コレクション作成
$json = @{"id"="$CollectionId"} | ConvertTo-Json 
Create -EndPoint $EndPoint -DataBaseId $DataBaseId -MasterKey $Keys.primaryMasterKey -ResourceType "colls" -ResourceLink "dbs/$DatabaseId" -BodyJson $json

# ドキュメント作成
$json = @{ "id"="$DocumentId"; "name"="hogehoge"; "age" = 24; } | ConvertTo-Json 
Create -EndPoint $EndPoint -DataBaseId $DataBaseId -MasterKey $Keys.primaryMasterKey -ResourceType "docs" -ResourceLink "dbs/$DatabaseId/colls/$CollectionId" -BodyJson $json

という感じで基本的な環境の作成は完了。疲れたのでまるっと削除して本日は終了。

Remove-AzureRmResourceGroup -ResourceGroupName "RG01"