2012年3月12日月曜日

読解練習:Python NDB Overview(Experimental版)

NDB APIのドキュメント」の「Python NDB Overview」の章の訳です。

によって訳の正確性は保証しません。
まだ訳の途中ですが、載せてます。


────────────────────────────

Python NDB Overview
Python NDBの概要

Experimental!
実験中です!

NDB is an experimental, innovative, and rapidly changing new feature for App Engine. Unfortunately, being on the bleeding edge means that we may make backwards-incompatible changes to NDB. We will inform the community when this feature is no longer experimental.
NDBは、実験的で、革新的で、急速に変化するAppEngine新機能です。残念ながら、実験段階ですので、NDBには下位互換の無い変更が加えれることがあります。もしも、実験段階ではなくなりましたら、コミュニティに連絡します
The NDB API provides persistent storage in a schemaless object datastore. It supports automatic caching, sophisticated queries, and atomic transactions. NDB is well-suited to storing structured data records.
NDB APIはスキーマレスなオブジェクトであるデータストアによる永続的なストレージを提供します。これは、自動キャッシュ洗練されたクエリ、およびアトミックトなランザクション処理をサポートしています。 NDBは、構造化されたデータレコードを格納するために適しています。

An application creates entities, objects with data values stored as properties of an entity. When the application reads an entity, that entity is automatically cached; this gives fast (and inexpensive) reads for frequently-read entities. The application can perform queries over entities.

アプリケーションは、エンティティのプロパティとして格納されているデータ値を持つエンティティ、オブジェクトを作成します。アプリケーションがエンティティを読み込むとき、そのエンティティは自動的にキャッシュされ、これは(安価な)頻繁に読み取りエンティティの読み取り速くなります。アプリケーションは、エンティティに対する問合せを実行することができます。
────────────────────────────

Introducing NDB
NDBのイントロダクション

NDB saves data objects, known as entities. An entity has one or more properties, named values of one of several supported data types. For example, a property can be a string, an integer, or a reference to another entity.
NDBは、エンティティと呼ばれるデータオブジェクトを保存します。エンティティは一つ以上のプロパティ名前の付けられたサポートされているいくつかのデータ型のいずれかの値を持ちます。たとえば、プロパティは文字列、整数、または別のエンティティへの参照になります。

NDB can group multiple operations in a single transaction. The transaction cannot succeed unless every operation in the transaction succeeds; if any of the operations fail, the transaction is automatically rolled back. This is especially useful for distributed web applications, where multiple users may be accessing or manipulating the same data at the same time.
NDBは、単一のトランザクションで複数の操作をグループ化することができます。トランザクション内のすべての操作が成功しない限り、トランザクションは成功しません操作のいずれかが失敗した場合、トランザクションは自動的にロールバックされます。これは、複数のユーザーがアクセスしたり、同じデータを同時に操作することができる分散Webアプリケーションの場合に特に便利です。

NDB uses Memcache as a cache service for "hot spots" in the data. If the application reads some records often, NDB can read them quickly from cache.
NDBは、データの"ホットスポット"のキャッシュサービスとしてMemcachedの使用します。アプリケーションは、しばしばいくつかのレコードを読み取りますが、NDBはキャッシュからすぐにそれらを読むことができます。

An application uses NDB to define models. A model is a Python class that acts as a sort of database schema: it describes a kind of data in terms of the properties. The underlying Datastore is very flexible in how it stores data objects—two entities of the same kind can have different properties. An application can use NDB models to enforce type-checking but doesn't have to.
モデルを定義するためにNDBを使用できます。モデルは、データベーススキーマの一種として動作するPythonのクラスです:それはプロパティ毎にデータの種類を説明しています。基底のデータストアはデータの格納方法が非常に柔軟で、データの同じ種類の二つのオブジェクトが異なるプロパティを持つことができます。NDBのモデルを使うことで、型チェックを強制させることもできます。

Each entity is identified by a key, an identifier unique within the application's datastore. The key can have a parent, another key. This parent can itself have a parent, and so on; at the top of this "chain" of parents is a key with no parent, called the root.
各エンティティは、キー(=アプリケーションのデータストア内で一意の識別子によって識別されます。キーは、親(別のキー)を持つことができます。この親は自分自身も親を持ち、その親が親を持つ、といったようにすることができます。この親子関係の"チェーン"の頂上にある親を持たないキーを、ルートと呼びます。


Entities whose keys have the same root form an entity group or group. If entities are in different groups, then changes to those entities might sometimes seem to occur "out of order". If the entities are unrelated in your application's semantics, that's fine. But if some entities' changes should be consistent, your application should make them part of the same group when creating them.
キーが同じルートを持つエンティティはエンティティグループまたはグループを形成しています。エンティティが別のグループに属している場合は、これらのエンティティへの変更は、しばしば "順不同"が発生するように見えるかもしれない。エンティティは、アプリケーションのセマンティクスとは無関係である場合、それは問題ありません。しかし、それらを作成するときに、いくつかのエンティティの変更が一貫していなければならない場合、それらを同じグループの一部にする必要があります。

import cgi
import urllib

from google.appengine.ext import ndb
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class Greeting(ndb.Model):
  """Models an individual Guestbook entry with content and date."""
  content = ndb.StringProperty()
  date = ndb.DateTimeProperty(auto_now_add=True)

  @classmethod
  def query_book(cls, ancestor_key):
    return cls.query(ancestor=ancestor_key).order(-cls.date)


class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')
    guestbook_name = self.request.get('guestbook_name')
    ancestor_key = ndb.Key("Book", guestbook_name or "*notitle*")
    greetings = Greeting.query_book(ancestor_key).fetch(20)

    for greeting in greetings:
      self.response.out.write('<blockquote>%s</blockquote>' %
                              cgi.escape(greeting.content))

    self.response.out.write("""
          <form action="/sign?%s" method="post">
            <div><textarea name="content" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="Sign Guestbook"></div>
          </form>
          <hr>
          <form>Guestbook name: <input value="%s" name="guestbook_name">
          <input type="submit" value="switch"></form>
        </body>
      </html>""" % (urllib.urlencode({'guestbook_name': guestbook_name}),
                    cgi.escape(guestbook_name)))

class SubmitForm(webapp.RequestHandler):
  def post(self):
    # We set the parent key on each 'Greeting' to ensure each guestbook's
    # greetings are in the same entity group.
    guestbook_name = self.request.get('guestbook_name')
    greeting = Greeting(parent=ndb.Key("Book", guestbook_name or "*notitle*"),
                        content = self.request.get('content'))
    greeting.put()
    self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))


application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/sign', SubmitForm)
])


def main():
  run_wsgi_app(application)


if __name__ == '__main__':
  main()

────────────────────────────

Storing Data
データの格納

A model is a class that describes a type of entity, including the types and configuration for its properties. It's roughly analogous to a SQL Table. An entity can be created by calling the model's class constructor and then stored by calling the put() method.
モデルは、そのプロパティの型と設定を含むエンティティのタイプを記述するクラスです。これは、SQLのテーブルとほぼ類似しています。put()メソッドを呼び出すことによって、格納されているモデルのクラスのコンストラクタを呼び出し、エンティティを作成することができます。

class Greeting(ndb.Model):
  """Models an individual Guestbook entry with content and date."""
  content = ndb.StringProperty()
  date = ndb.DateTimeProperty(auto_now_add=True)

class SubmitForm(webapp.RequestHandler):
  def post(self):
    # We set the parent key on each 'Greeting' to ensure each guestbook's
    # greetings are in the same entity group.
    guestbook_name = self.request.get('guestbook_name')
    greeting = Greeting(parent=ndb.Key("Book", guestbook_name or "*notitle*"),
                        content = self.request.get('content'))
    greeting.put()

This sample code defines the model class Greeting. Each Greeting entity has two properties: the text content of the greeting and the date the greeeting was created.
このサンプルコードは、モデルクラスのGreeting(挨拶)を定義します。それぞれのGreetingエンティティには、2つのプロパティ(挨拶の内容と、挨拶の作成日付)があります。

To create and store a new greeting, the application creates a new Greeting object and calls its put() method.
新しいメッセージを作成し、保存するには、新しいGreetingオブジェクトを作成して、そのput()メソッドを呼び出します。

To make sure that greetings in a guestbook don't appear "out of order" the application sets a parent key when creating a new Greeting. Thus, the new greeting will be in the same entity group as other greetings in the same guestbook. The application uses this fact when querying: it uses an ancestor query.
ゲストブックの挨拶は、新しいグリーティングメッセージを作成するときに、アプリケーションが親キーを設定する"アウトオブオーダー"が表示されていないことを確認します。したがって、新しい挨拶は、同じブック内の他の挨拶と同じエンティティグループになります。照会するときにアプリケーションはこの事実を使用しています:それは先祖のクエリを使用しています。

────────────────────────────

Queries and Indexes
クエリーとインデックス

An application can query to find entities that match some filters.
いくつかのフィルターにマッチするエンティティをクエリーで検索できます。


class Greeting(ndb.Model):
  ...

  @classmethod
  def query_book(cls, ancestor_key):
    return cls.query(ancestor=ancestor_key).order(-cls.date)

  def get(self):
    guestbook_name = self.request.get('guestbook_name')
    ancestor_key = ndb.Key("Book", guestbook_name or "*notitle*")
    greetings = Greeting.query_book(ancestor_key).fetch(20)

    for greeting in greetings:
      self.response.out.write('<blockquote>%s</blockquote>' %
                              cgi.escape(greeting.content))



A typical NDB query filters entities by kind. In this example, query_book generates a query that returns Greeting entities. A query can also specify filters on entity property values and keys. As in this example, a query can specify an ancestor, finding only entities that "belong to" some ancestor. A query can specify sort order. If a given entity has at least one (possibly null) value for every property in the filters and sort orders and all the filter criteria are met by the property values, then that entity is returned as a result.
一般的なNDBのクエリーは、kindによってエンティティをフィルタします。この例ですと、query_bookは、Greetingエンティティを返すクエリを生成します。クエリは、エンティティのプロパティの値やキーによるフィルタ条件を指定できます。この例にあるように、クエリでは(いくつかの祖先に”属している”だけのエンティティだけでを見つけることで)祖先を特定できます。クエリではソート順を指定できます。クエリーの結果として返されるのは、ソートに指定された各プロパティに値(NullもOK)があり、フィルタの条件で指定された各条件がすべて満たしたエンティティです。

Every query uses an index, a table that contains the results for the query in the desired order. The underlying Datastore automatically maintains simple indexes (indexes that use only one property). It defines its complex indexes in a configuration file, index.yaml. The development web server automatically adds suggestions to this file when it encounters queries that do not yet have indexes configured. You can tune indexes manually by editing the file before uploading the application. You can also update the indexes separately from uploading the application. If your datastore has many records, it takes a long time to create a new index for them; in this case, it's wise to update the index definitions before uploading code that uses the new index.
すべてのクエリは、インデックス(望んだの順序のクエリの結果を含むテーブル)を使用しています。基底のデータストアは、自動的にシンプルなインデックスを(1つのプロパティだけを使用したインデックス)を保持します。複雑なインデックスの定義は、コンフィギュレーションファイル「index.yaml」を用います。SDKの開発Webサーバは、インデックスが設定されていないクエリを検出したときに、自動的にこのファイルに設定を追加します。あなたは、アプリケーションをアップロードする前に、このファイルを編集することで、インデックスを手動で調整することができます。また、アプリケーションのアップロードとは別にインデックスだけを更新することができます。データストアに多くのレコードがある場合、新しい索引を作成するのに長い時間がかかります。こういった場合には、新しいインデックスを使用するコードをアップロードする前に、インデックス定義を更新するのが賢明です。


This index mechanism supports a wide range of queries and is suitable for most applications. However, it does not support some kinds of queries common in other database technologies. In particular, joins aren't supported.
このインデックスメカニズムは幅広いクエリをサポートし、ほとんどのアプリケーションに適しています。しかし、それは他のデータベーステクノロジの一般的なクエリのいくつかの種類をサポートしていません。特に、結合はサポートされません。

────────────────────────────

Understanding NDB Writes: Commit, Invalidate Cache, and Apply
NDBの書き込みを理解する:キャッシュ、コミットの適用、およびデータの可視性について

Note: For a full discussion of writes to the underlying Datastore, see Life of a Datastore Write and Transaction Isolation in App Engine.
基礎となるデータストアへの書き込みの詳細については「データストア書き込みのライフサイクル」と 「App Engine におけるトランザクション分離」を参照して下さい。


NDB Writes data in steps:
NDBは以下のステップで書き込みを行います:

  • In the Commit phase, the underlying Datastore service records the changes.
    コミットフェーズでは、基礎となるDatastoreサービスでは、変更を記録します。
  • NDB invalidates its caches of the affected entity/entities. Thus, future reads will read from (and cache) the underlying Datastore instead of reading stale values from the cache.
    NDBは、影響を受けるエンティティ/エンティティのそのキャッシュを無効にします。したがって、将来の(およびキャッシュ)からではなく、キャッシュから古い値を読んでの基礎となるデータストアを読み込みます読み込みます。
  • Finally, perhaps seconds later, the underlying Datastore applies the change. It makes the change visible to global queries and eventually-consistent reads.
    最後に、おそらく数秒後、基礎となるデータストアは、変更を適用します。それがグローバルクエリには表示され、最終的には一貫性の変化を読み取ることができます。
 The NDB function that writes the data (for example, put()) returns after the cache invalidation; the Apply phase happens asynchronously.
NDBの書き込み関数(例えば、put()とか)は キャッシュを無効化にしてから戻ってきます(ちなみに適用フェーズでは、これは非同期的に発生します)

If there is a failure during the Commit phase, there are automatic retries, but if failures continue, your application receives an exception. If the Commit phase succeeds but the Apply fails, the Apply is rolled forward to completion when one of the following occurs:コミットフェーズ中に障害が発生した場合は自動的にリトライしますが、失敗が続くとアプリケーションは例外が発生します。コミットフェーズが成功したにもかかわらず 適用フェーズで失敗した場合、次のいずれかが発生している時は、適用フェーズが完了するまでロールフォワードされます:
  • Periodic Datastore "sweeps" check for uncompleted Commit jobs and applies them.
    コミットされていないジョブや適用のための 定期的なデータストアの「一掃」チェック
  • The next write, transaction, or strongly-consistent read in the impacted entity group causes the not-yet-applied changes to be applied before the read, write, or transaction.
This behavior affects how and when data is visible to your application. The change may not be completely applied to the underlying Datastore a few hundred milliseconds or so after the NDB function returns. A non-ancestor query performed while a change is being applied may see an inconsistent state (i.e., part but not all of the change). For more information about the timing of writes and queries, see Transaction Isolation in App Engine.
データがアプリケーションに表示されているときにこの動作がどのように影響します。変更は、完全に数百ミリ秒かそこらのNDB関数が戻った後、基礎となるデータストアに適用されない場合があります。変更が適用されている間に行われ、非祖先クエリ(つまり、一部ではなく変化のすべての)矛盾した状態が表示される場合があります。書き込みのタイミングとクエリの詳細については、App Engineのトランザクションのアイソレーションを参照してください。


────────────────────────────

Quotas
クォータ

NDB uses the App Engine Datastore. Each use of the Datastore counts toward the Datastore API Calls limit. Some NDB calls result in multiple calls to the API, and so use more of your resource.
NDBは、App Engineのデータストアを使用しています。データストアAPIに向かってデータストアの数のそれぞれの使用が制限値を呼び出します。いくつかのNDBは、APIへの複数の呼び出しで結果を呼び出して、ので、あなたのリソースの多くを使用しています。

Data sent to the datastore by the app counts toward the Data Sent to (Datastore) API limit. Data received by the app from the datastore counts toward the Data Received from (Datastore) API limit.
データに向かってアプリの数によってデータストアに送信されるデータは、(データストア)APIの制限に送信されます。データ(データストア)APIの制限から受信したデータに向かってデータストアのカウントからアプリケーションによって受信された

The total amount of data currently stored in the datastore for the app cannot exceed the Stored Data (billable) limit. This includes all entity properties and keys and the indexes necessary to support querying these entities. See How Entities and Indexes are Stored for a complete breakdown of the metadata required to store entities and indexes at the Bigtable level.
現在のアプリケーションのデータストアに格納されているデータの総量は保存されたデータ(請求)の制限を超えることはできません。これは、これらのエンティティをクエリをサポートするために必要なすべてのエンティティのプロパティとキーとインデックスが含まれています。エンティティと索引は、Bigtableのレベルでエンティティとインデックスを格納するために必要なメタデータの完全な破壊が格納される方法を参照してください。

For more information on system-wide safety limits, see Limits, and the "Quota Details" section of the Admin Console.
システム全体の安全性の制限を参照してください制限、および管理コンソールの"クォータの詳細"セクションの詳細については、。

In addition to system-wide safety limits, the following limits apply specifically to the use of the datastore:
システム全体の安全性の限界に加えて、次の制限は、データストアの使用に特に適用されます:
Limit
制限項目
Amount
maximum entity sizeエンティティの最大サイズ1 megabyte
1メガバイトまで
maximum number of values in all indexes for an entity (1)
エンティティ1つに対してすべてのインデックスで持てる値の最大数
5,000 values
5,000個の値まで
An entity uses one value in an index for every column × every row that refers to the entity, in all indexes. The number of index values for an entity can grow large if an indexed property has multiple values, requiring multiple rows with repeated values in the table.
エンティティは、すべてのインデックスでは、すべての列×エンティティを参照するすべての行のインデックス内の1つの値を使用します。インデックス付きプロパティは、テーブル内の繰り返しの値を持つ複数の行を必要とする複数の値を持つ場合、エンティティのインデックス値の数が大きくなる可能性があります。

0 件のコメント:

コメントを投稿