python - 如何更快地从azure documentdb获取数据

标签 python sql azure azure-cosmosdb

我正在尝试实现这个示例:

https://github.com/Azure/azure-documentdb-python/blob/master/samples/DatabaseManagement/Program.py

从 azure documentdb 获取数据并进行一些可视化。但是,我想在此处使用#error 所在的行进行查询。

def read_database(client, id):
    print('3. Read a database by id')

    try:

       db = next((data for data in client.ReadDatabases() if data['id'] == database_id))
       coll = next((coll for coll in client.ReadCollections(db['_self']) if coll['id'] == database_collection))
       return list(itertools.islice(client.ReadDocuments(coll['_self']), 0, 100, 1))

    except errors.DocumentDBError as e:
        if e.status_code == 404:
            print('A Database with id \'{0}\' does not exist'.format(id))
        else:
            raise errors.HTTPFailure(e.status_code)

当我想要获取 >10k 项时,获取速度非常慢,我该如何改进?

谢谢!

最佳答案

不能直接通过数据库实体查询文档。

代码中使用的 ReadDocuments() 方法的参数应该是集合链接和查询选项。

def ReadDocuments(self, collection_link, feed_options=None):
    """Reads all documents in a collection.

    :Parameters:
        - `collection_link`: str, the link to the document collection.
        - `feed_options`: dict

    :Returns:
        query_iterable.QueryIterable

    """
    if feed_options is None:
        feed_options = {}

    return self.QueryDocuments(collection_link, None, feed_options)

因此,您可以按如下方式修改代码:

# Initialize the Python DocumentDB client
client = document_client.DocumentClient(config['ENDPOINT'], {'masterKey': config['MASTERKEY']})

db = "db"
coll = "coll"

try:
    database_link = 'dbs/' + db
    database = client.ReadDatabase(database_link)

    collection_link = 'dbs/' + db + "/colls/" + coll
    collection = client.ReadCollection(collection_link)

    # options = {}
    # options['enableCrossPartitionQuery'] = True
    # options['partitionKey'] = 'jay'
    docs = client.ReadDocuments(collection_link)
    print(list(docs))

except errors.DocumentDBError as e:
    if e.status_code == 404:
        print('A Database with id \'{0}\' does not exist'.format(id))
    else:
        raise errors.HTTPFailure(e.status_code)

如果您想查询集合的分区,请添加上面代码中注释的代码片段。

   options = {}
   options['enableCrossPartitionQuery'] = True
   options['partitionKey'] = 'jay'
<小时/>

您的问题似乎主要集中在 Azure Cosmos DB 查询性能上。

您可以引用以下几点来提高查询性能。

分区

您可以在数据库中设置分区键,并在单个分区键上使用过滤子句进行查询,这样它需要更低的延迟并消耗更低的 RU。

吞吐量

您可以将吞吐量设置得大一些,这样单位时间的 Azure Cosmos DB 性能将会大大提高。当然,这会导致成本更高。

索引政策

使用索引路径可以提高性能并降低延迟。

更多详情,建议您引用 official performance documentation .

希望对您有帮助。

关于python - 如何更快地从azure documentdb获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47098204/

相关文章:

python - python如何比较字符串和整数

python - 无法建立连接,因为目标机器主动拒绝

python - 使用 python 搜索文本中的字符串

python - Django 删除 OneToOneField

mysql - 根据最大订单从 2 个不同的表中选择数据

mysql - 使用 SQL 从第二个 P 标记 <p> 之后的数据库获取文本

具有多个共享列的 MySql 索引策略

azure - 如何使用包含资源组和资源的链接模板部署 Arm 模板

azure - 如何删除 Azure 上 URL 的 .html 部分?

azure - 使用图形 API 从 Multi-Tenancy AD 应用程序获取所有用户