【问题标题】:How to fix index error when querying GAE datastore?查询 GAE 数据存储时如何修复索引错误?
【发布时间】:2013-04-22 01:05:38
【问题描述】:

当我尝试在按日期排序的数据存储上运行查询时,我收到以下错误:

NeedIndexError: no matching index found.
The suggested index for this query is:

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

如果我不尝试按日期排序,则查询运行不会出错。数据存储索引下的 appengine 控制台显示:

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

【问题讨论】:

    标签: google-app-engine google-cloud-datastore app-engine-ndb


    【解决方案1】:

    您还需要指定“方向”,因为“排序”是在编写索引时完成的,以便按照 Google 的风格加快速度。

    所以,你的 index.yaml 应该是这样的:

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

    这是谷歌关于订单的官方描述:

    排序方向,asc 表示升序,desc 表示 下降。这仅对排序顺序中使用的属性是必需的 查询的方向,并且必须与查询使用的方向相匹配。这 默认为 asc。

    我希望这会有所帮助。

    【讨论】:

    • 谢谢。实际上,我忘了复制索引定义的最后一行。应用引擎控制台指示索引已创建为 ref ▲ 、 author ▲ 、 date ▼ 。所以我不认为这是我的问题,但我已经更新了问题中的索引定义。
    【解决方案2】:

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

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

    例如以下2个查询:

    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)
    

    实际上是按升序排序,但我的索引显示的是 DESCENDING 顺序。解决方法是:

    query = query.order(-Message.date)
    

    【讨论】:

    • 不客气!是的,它必须与您的查询和索引顺序完全匹配。
    猜你喜欢
    • 2018-08-12
    • 2013-06-21
    • 2014-08-04
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    相关资源
    最近更新 更多