GoogleAppEngine再入門(3) -Datastore API 2-
前回:GoogleAppEngine再入門(2) -Datastore API 1- - souta-bot log
DatastoreAPIの続き
動的なproperty作成
- db.Modelを継承したdb.Expandoを使えばpropertyとして定義していない形式のデータも格納できる
早速日経ソフトウェア2009/1月号リスト5のコードを写経
# -*- coding: utf-8 -*- from google.appengine.ext import db import datetime class Song(db.Expando): title = db.StringProperty() songs = Song.all() if songs.count() == 0: dragonfly = Song(title='Dragonfly', author='Takashi Matsuo', publish_date='yesterday', rating=5.0) masterpiece = Song(title='The Sound of Silence', author='Simon Garfunkel', publish_date=datetime.datetime(1968, 6, 15)) dragonfly.last_minute_note=db.Text( 'This song could be another masterpiece!') db.put([dragonfly, masterpiece]) songs = Song.all() print "Content-Type: text/html\n" print "<html>" for song in songs: print song.title print "<br />" print "<ul>" #dynamic_propertiesメソッドでプロパティのリストを取得 for prop_name in song.dynamic_properties(): #getattr関数でアトリビュートの値を取得 print "<li>%s: %s</li>" % (prop_name, getattr(song, prop_name)) print "</ul>" print "</html>"
実行結果
動的に設定したpropertyの削除
del song.author
song.put()
Datastoreの編集
作成したentityを削除するのに、いちいちdb.delete()とかをやるのは面倒なのでSDK Consoleを使う
- GoogleAppEngineLauncherからCmd-KでSDK Consoleを開く
- Entity Kindから編集したいデータモデル(ここではSong)を選択しList Entitiesボタン
- 削除したいentityをチェックし、Deleteボタン
それぞれのentityの編集も可能
参考:http://d.hatena.ne.jp/CortYuming/20081129/p2
トランザクション処理
RDBとは異なるので注意
用語
- entityには親となるentity、子となるentityを指定できる
- 一連の親子群を「entity group」と呼ぶ
- entity groupの頂点を「root」と呼ぶ
- あるentityの全ての親entityを「ancestors」と呼ぶ
- rootから末端entityの一連の連なりを「path」と呼ぶ
トランザクション処理実行の際の注意点
- Googleは安価なマシンを大量に用意して並列処理を行うサーバー構造を持つ(Googleを支える技術 ?巨大システムの内側の世界 (WEB+DB PRESSプラスシリーズ))
- そのためentityがあちこちのサーバに散らばってしまう可能性がある
- あるトランザクションで遠くにあるentityが関係すると大量のネットワーク通信が発生し性能が落ちてしまう
- だがentity groupを作成すると、そのentity groupに属するenttyは全て同じ場所に保存される
- トランザクション実行の際は対象データを同じentity groupに所属させる
- トランザクションが必要ないときはentity groupを作成しない
- コツはGoogle曰く小さなentity groupを複数持つこと
なんか実例が無いとモヤモヤしたままだが、それはおいおい