2
4

More than 5 years have passed since last update.

Azure documentDBのdocumentをpydocumentdbで抽出してみる

Last updated at Posted at 2017-03-31

Microsoft Azure上のdocumentDB上のデータを手元(local PC)に持ってきて、ドキュメントを配列listに格納するとこまでのメモ

試行前提

  • PC OS: Windows 10
  • Python: Python 2.7
  • Python library: pydocumentdb
  • Azure上のdocumentDB設定
    • server: abc_server.documents.azure.com
    • database: abc_database
    • collection: abc_collection
    • api-key: abc_api
      • それぞれのabc...は、適宜Azure上で設定するときに書き換えてください

Collection?

何はともあれinstall & 初期設定

pip install pydocumentdb

ではPythonで書いていきましょう。

# -*- coding: utf-8 -*-

## library setting
import pydocumentdb.document_client as document_client

## 各種設定
HOST = 'abc_server.documents.azure.com:443/'
DATABASE_ID = 'abc_database'
COLLECTION_ID = 'abc_collection'
MASTER_KEY = 'abc_api'

# documentDb client instance作成
client = document_client.DocumentClient(HOST,  {'masterKey': MASTER_KEY})

# database/collection定義
database_definition = {'id': DATABASE_ID }
collection_definition = { 'id': COLLECTION_ID }

## DB接続を定義
databases = list(client.QueryDatabases({
        'query': 'SELECT * FROM root r WHERE r.id=@id',
        'parameters': [
            { 'name':'@id', 'value': database_definition['id'] }
        ]
    }))

db = databases[0]

## Collectionを定義
collections = list(client.QueryCollections(
    db['_self'],
    {
        'query': 'SELECT * FROM root',
        'parameters': [
            { 'name':'@id', 'value': collection_definition['id'] }
        ]
    }))

collection = collections[0]

## Documentsを格納
### Documentsを入れとく箱
list = []
### 1つずつ入れていきましょー
for doc in client.ReadDocuments(collection['_self']):
    list.append(doc)

格納した結果

  • 各documentはjson形式で入ってくるので、別途parseが必要ですー

備考

  • 今回は全量をもってくる感じでしたが、部分的に抜きたい場合queryを変更する必要がありますが、それはまた別途。
  • 取り敢えず抽出するよー、という用途の場合にご利用ください。
2
4
1

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
2
4