如何在查询GAE数据存储时修复索引错误?

8
当我尝试按日期对数据存储运行查询时,我会收到以下错误提示:
NeedIndexError: no matching index found.
The suggested index for this query is:

- kind: Message
  properties:
  - name: author
  - name: ref
  - name: date

如果不尝试按日期排序,则查询会无错误运行。在数据存储索引下,应用程序引擎控制台显示:
author ▲ , ref ▲ , date ▼   
Serving

我做错了什么?如何按日期排序运行我的查询?谢谢!

以下是我的实体定义:

from google.appengine.ext import ndb

class Message(ndb.Model):
    subject = ndb.StringProperty()
    body = ndb.TextProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)
    ref = ndb.StringProperty( required=True )
    author = ndb.KeyProperty(required=True)

这是失败的查询语句:

def readMessages( ref, user = None ):
    query = Message.query()
    query = query.filter(Message.ref == ref )
    if user:
        query = query.filter(Message.author == user.key )
    query = query.order(Message.date)

# convert to a list so we can index like an array
return [ message for message in query ]

我的index.yaml包含以下内容:

indexes:

- kind: Message
  properties:
  - name: author
  - name: ref
  - name: date
    direction: desc
2个回答

4

由于谷歌的风格需要在写入索引以加快速度时进行排序,因此您还需要指定“direction”。

因此,您的index.yaml应该像这样:

indexes:

- kind: Message
  properties:
  - name: author
  - name: ref
  - name: date
    direction: desc

这是关于“排序”的谷歌官方说明:
排序方向,升序为asc,降序为desc。这仅适用于查询中用于排序的属性,并且必须与查询中使用的方向相匹配。默认为升序。
希望这有所帮助。

谢谢。实际上,我忘记复制索引定义的最后一行了。应用程序引擎控制台显示该索引已创建为ref ▲,author ▲,date ▼。因此,我不认为这是我的问题,但我已更新了问题中的索引定义。 - deltanine

3

谢谢你,劳伦斯,你让我走上了正确的道路——我想我已经找到了答案。查询必须与索引定义完全匹配。

我通过在数据存储管理框中尝试不同的GQL查询来发现这一点。

例如,以下两个查询:

SELECT * FROM Message where ref='' and author='' order by date 
SELECT * FROM Message where ref='' and author='' order by date asc 

两种方法都失败了:

no matching index found.

The suggested index for this query is:
- kind: Message
  properties:
  - name: author
  - name: ref
  - name: date

然而,
SELECT * FROM Message where ref='' and author='' order by date desc

成功。同样,查询参数比索引包含的参数少也会失败,例如:

SELECT * FROM Message where ref='' order by date DESC

出现以下错误:

no matching index found.

The suggested index for this query is:
- kind: Message
  properties:
  - name: ref
  - name: date
    direction: desc

因此,问题出现在我的查询语句中,具体地说是这一行:
query = query.order(Message.date)

实际上是按升序排序,但我的索引显示为降序。修复方法如下:

query = query.order(-Message.date)

不客气!是的,这必须完全匹配你的查询和索引顺序。 - user7180

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接