Gaelyk tutorial为数据存储和 this Gaelyk google groups article 提供了一些不错的低级包装器描述了一种通过简单地将键存储在实体集合中来建模关系的简单方法。
我的问题是如何查询集合中的值?这是一些示例代码来阐明...
def b1 = new Entity("Book")
b1.title = "Book1"
b1.save()
def b2 = new Entity("Book")
b2.title = "Book2"
b2.save()
def author1 = new Entity("Author")
author1.books = [b1.key, b2.key]
author1.name = "Chris"
author1.save()
// It is easy to simply query the Author entity for a standard string property
def query = new Query("Author")
query.addFilter("name", Query.FilterOperator.EQUAL, "Chris")
PreparedQuery preparedQuery = datastore.prepare(query)
def authors = preparedQuery.asList(withLimit(1))
assert authors[0].name == "Chris"
// But I can't find out how to query a collection property eg books on the Author entity
def query2 = new Query("Author")
// I would like to do something to return the entity if the value is in the collection property
// eg if there could be something like 'CONTAINS' criteria ...
// Unfortunately Query.FilterOperator.CONTAINS doesn't exist...
query2.addFilter("books", Query.FilterOperator.CONTAINS, b2.key)
PreparedQuery preparedQuery2 = datastore.prepare(query2)
def authors2 = preparedQuery2.asList(withLimit(1))
assert authors2[0].name == "Chris"
如何创建查询以在实体的集合属性中搜索匹配项?即如何重新创建上面神话般的“FilterOperator.CONTAINS”查询的功能?
最佳答案
只是为了用户将来登陆此页面而回答:
Query.FilterOperator.EQUAL
也会在键列表中找到(在列表的情况下,它作为 CONTAINS
工作)。所以现在你的第二个案例看起来像:
def query2 = new Query("Author")
query2.addFilter("books", Query.FilterOperator.EQUAL, b2.key)
PreparedQuery preparedQuery2 = datastore.prepare(query2)
def authors2 = preparedQuery2.asList(withLimit(1))
assert authors2[0].name == "Chris"
断言通过:)
乍一看这可能很奇怪,但这确实是 DataStore 的一个很棒的功能。
关于google-app-engine - Gaelyk:如何对集合属性执行数据存储查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4904292/