【问题标题】:Check which ids in id list already exist in NDB (python)检查 id 列表中的哪些 id 已存在于 NDB (python)
【发布时间】:2013-06-26 09:14:41
【问题描述】:

我有一个要加载到前端的实体列表。如果我的 NDB 中还没有这些实体,我会从另一个数据源加载它们。如果我的 NDB 中确实有它们,我显然会从那里加载它们。

我不想单独查询每个键来测试它是否存在,而是查询整个列表(出于效率原因)并找出 NDB 中存在哪些 ID,哪些不存在。

它可以返回一个布尔值列表,但欢迎任何其他实用的解决方案。

已经感谢您的帮助!

【问题讨论】:

    标签: google-app-engine python-2.7 app-engine-ndb


    【解决方案1】:

    如何对您的列表执行ndb.get_multi(),然后将结果与您的原始列表进行比较以查找您需要从其他数据源检索的内容?可能是这样的……

    list_of_ids = [1,2,3 ... ]
    
    # You have to use the keys to query using get_multi() (this is assuming that
    # your list of ids are also the key ids in NDB)
    keys_list = [ndb.key('DB_Kind', x) for x in list_of_ids]
    results = ndb.get_multi(keys_list)
    results = [x for x in results if x is not None] # Get rid of any Nones
    result_keys = [x.key.id() for x in results]
    diff = list(set(list_of_ids) - set(result_keys)) # Get the difference in the lists
    # Diff should now have a list of ids that weren't in NDB, and results should have
    # a list of the entities that were in NDB.
    

    我不能保证它的性能,但它应该比一次查询每个实体更有效。根据我使用ndb.get_multi() 的经验,它可以极大地提高性能,因为它减少了大量的RPC。您可能会调整我在上面发布的代码,但也许它至少会为您指明正确的方向。

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多