【问题标题】:gcp - get all entities from the datastoregcp - 从数据存储中获取所有实体
【发布时间】:2019-03-01 21:17:47
【问题描述】:

我正在尝试从数据存储中获取所有数据实体。当我遇到谷歌文档时,我发现了类似于 Query Projection (Link to the Docs) 的内容。这是我用来从数据存储区获取所有实体的代码。

def do_the_query_projection(self, kind_name):

        query = self.client.query(kind=kind_name)
        query.projection = ['attr_1', 'attr_2', 'attr_3']

        #create a list to store
        f, m, r = [], [], []

        for task in query.fetch():
            f.append(task['attr_1'])
            m.append(task['attr_2'])
            r.append(task['attr_3'])

        return f, m, r

这是我现在面临的错误

> google.api_core.exceptions.FailedPrecondition: 400 no matching index
> found. recommended index is:
> - kind: <kind_name>  properties:
>   - name: attr_1
>   - name: attr_2
>   - name: attr_3

还有其他方法可以从 Cloud Datastore 中检索所有数据实体吗?我们是否需要创建复合索引来检索数据?我是 GCP 的新手。

【问题讨论】:

    标签: python-3.x google-cloud-platform google-cloud-datastore


    【解决方案1】:

    尝试在没有投影的情况下进行查询。

    当您已经在要检索的列上具有复合索引时,投影查询很有用,因为它允许您从索引中检索这些列,而无需从数据表中检索任何内容。但是,如果您没有索引,则 Datastore 必须以任何一种方式检索完整数据,因此在这种情况下它不允许您指定投影。

    【讨论】:

    • 不幸的是,我无法提供任何示例代码,因为我没有使用过这个 Python API(只有old Datastore API on App Engine Standard。可能删除query.projection = [...] 的行应该可以解决问题
    • 我想出了另一种方法来完成这项工作。感谢您的帮助!
    【解决方案2】:

    检索数据存储区中的所有实体

    def retrieve_all_entities(self):
        query = self.client.query(kind=self.kind_name)
        all_keys = query.fetch() #fetches all the entities from the datastore
    
        kinds, r, m, f = [] , [], [], []
    
        for keys in all_keys:
            kinds.append(keys.key.id_or_name)
            r.append(keys['attr_1'])
            m.append(keys['attr_2'])
            f.append(keys['attr_3'])
    
        return kinds, r, m, f
    

    【讨论】:

    • 这非常低效,因为此代码往返数据存储区需要 4 次以获取 3 个实体,而这可以在一次往返中完成。为什么首先需要仅键查询?
    • 对于性能过程,我们可以使用key_all(kind) 之类的东西来获取所有实体吗?而不是首先获取关键实体并遍历所有键以获取剩余属性!
    猜你喜欢
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多