我试图做使用公司的FireStore三件事情:
在contents
集合中的文件看起来像这样(省去不必要的细节):
{
date: Timestamp;
contentType: string;
response: {
like: Number;
};
}
这里是iOS的代码:
let dateKey = "date"
let likeKey = "response.like"
let startDate = Date().setLocalHour(5)
let timestamp = Timestamp(date: startDate)
Firestore.firestore()
.collection(path: .contents)
.whereField(.contentType, isEqualTo: "basic")
.whereField(dateKey, isGreaterThanOrEqualTo: timestamp)
.order(by: dateKey, descending: true)
.order(by: likeKey, descending: true)
.limit(to: Constant.fetchLimit)
该order(by: dateKey)
部分只有必要的,因为火力地堡需要它。否则,会抛出异常,抱怨说,where子句和排序依据的条款不相符。
我已经创建了一个说contents
contentType Ascending date Descending response.like Descending
一个综合指数。
期望与结果
我期待通过like
数进行排序的文件,以及所有文件是“基本”型和过去的上午5点今天的创造。
取而代之的是,只有前两个条件被施加,并且所述第三被完全忽略。不同组合的两个条件的工作。这三个条件组合不工作。
所以我的问题是,由于火力地堡文件不说的有两个以上多个排序依据与其中任何的组合,这是一个错误或东西,只是没有可能?
我发现了一个解决方法的问题。
原来的查询所需的三个字段的复合索引。因此对date
只有一个范围比较 - contentType
仅用于相等性检查 - 和两个排序上date
和response.like
,二者组成的复合索引。
相反,我决定像这样的contents
文档中添加一个字段:
{
tags: string[]; // the new field.
date: Timestamp;
contentType: string;
response: {
like: Number;
};
}
而新的查询如下所示:
Firestore.firestore()
.collection(path: .contents)
.whereField(.tags, arrayContains: Date.getDatabaseKey())
.whereField(.contentType, isEqualTo: "basic")
.order(by: likeKey, descending: true)
.limit(to: Constant.fetchLimit)
(Date.getDatabaseKey()
只是创建基于当前日期yyyy-MM-dd
字符串。)
此查询需要两个复合索引:
tags Arrays response.like Descending
和contentType Ascending response.like Descending
。
幸运的是,这个工程就像一个魅力。
新增信息的原始查询检查5点某一天之后创建的文档集合,并给我的范围检查似乎是问题。
只要上述Date.getDatabaseKey()
方法生成具有几个小时五时00分00秒到第二天的4点59分59秒的同一天的一个关键,这个新查询具有基本相同的效果。