LoginSignup
0
0

More than 5 years have passed since last update.

Azure SDK for go で Storage Table のデータを作成する

Last updated at Posted at 2018-09-20

Azure Storage Table のデータの書き出しを実施したかったので、どのように実施したかを記録しておきたい。

Storage Table の操作に関しては、Storage Account 名前とキーがあれば可能になる。こちらにリファレンスが存在するのでどうやって使うかは想像がつきやすい。

使用例と解説

使い方は簡単です。Storage Table のライブラリには、他のライブラリのように service/storage/mgmt の下に日付付きのライブラリが普通はあるのですが、なぜか Storage Table だけありません。

ルート直下にある /storage を読み込みます。その後は簡単で

  1. Storage Account clinet をインスタンス化。NewBasicClient 今回の目的に適していた。
  2. Storage Table Service のリファレンスを取得 client.GetTableService()
  3. 具体的なテーブルのリファレンスを取得 tableService.GetTableReference(YOUR_TABLE_NAME)
  4. Entity 構造体をセット
  5. インサートまたはアップデートの実施

テーブルのレコードを作るためには、Entity 構造体を自分で New してインサートするか、Batch で複数のレコードを一括で更新するか?という方法がある。下記のサンプルはバッチ型で実施している。

import (
  "github.com/Azure/azure-sdk-for-go/storage"
)
: 
client, err := storage.NewBasicClient(YOUR_ACCOUNT_NAME, YOUR_ACCOUNT_KEY)
    :
tableService := client.GetTableService()
table := tableService.GetTableReference(YOUR_TABLE_NAME)
tableBatch := table.NewBatch()
entity := &storage.Entity {}
entity.PartitionKey = "1"
entity.RowKey = "0"
entity.TimeStamp = time.Now()
m := make(map[string]interface{})
m["Foo"] = "foo"
m["Bar"] = "bar"
m["CustomTime"] = time.Now()
tableBatchInsertOrReplaceEntityByForce(entity)
:
err := tableBatch.ExecuteBatch()

Odata のコンフィグレーションは必要か?

結論から言うと必要ない。

一つ疑問だったのが、Entity の定義にあった Odata の提議。

type Entity struct {
    Table         *Table
    PartitionKey  string
    RowKey        string
    TimeStamp     time.Time
    OdataMetadata string
    OdataType     string
    OdataID       string
    OdataEtag     string
    OdataEditLink string
    Properties    map[string]interface{}
}

どれが必須のなのかわからないけど、これは、Azure REST API のリファレンスを見ろとのこと。

このリファレンスを見ると、OData のレベルに対応して、設定する必要のある項目が異なってくる。本ライブラリの場合は、各カラムの型などは自動で設定してくれて、medatada も勝手に設定してくれるので、実用上は、私の上記のサンプルで構わない。自分でコントロールしたい場合は、

func (e *Entity) Insert(ml MetadataLevel, options *EntityOptions) error

の MetadataLevelを参照すれば良い。こちらだが、一瞬定義が見つかりにくいが、Constantのところに書かれている。

    EmptyPayload    MetadataLevel = ""
    NoMetadata      MetadataLevel = "application/json;odata=nometadata"
    MinimalMetadata MetadataLevel = "application/json;odata=minimalmetadata"
    FullMetadata    MetadataLevel = "application/json;odata=fullmetadata"

デフォルトでは、MinimalMetadata になっている様子で、私のユースケースでは、特に設定しなくても十分だと思われる。InsertOrReplace を使うと、一行で書ける。

entity.InsertOrReplace(&storage.EntityOptions{Timeout: 10}) 

タイムアウトの単位は、秒で最大 30 秒。わざわざオプションを指定しないといけないのが面倒だが、REST API のx-ms-client-request-id(Optional)   と timeout(Optional) パラメータに相当するので、タイムアウトも指定しなくても良い。空のインスタンスで良い。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0