无法查询多个值的Firestore数据库 [英] Cannot query Firestore database on multiple values
问题描述
我有一个充满汽车的数据库. JSON
格式是这样的:
I have a database full with cars. The JSON
format is this:
docId: {
"countries": ["Netherlands"]
"cities": ["Amsterdam"]
}
我无法查询两个数组.
db.collection("EU-CARS")
.whereArrayContains("countries", "Netherlands")
.whereArrayContains("cities", "Amsterdam");
如何解决这个问题?
推荐答案
正如您已经注意到的,Firestore允许您仅使用一个 whereArrayContains()
方法调用来过滤汽车.如果您将使用多个,则将发生如下错误:
As you already noticed, Firestore allow you to filter your cars using only one whereArrayContains()
method call. If you will use more than one, an error like this will occur:
原因:java.lang.IllegalArgumentException:无效的查询.查询仅支持具有单个包含数组的过滤器.
Caused by: java.lang.IllegalArgumentException: Invalid Query. Queries only support having a single array-contains filter.
有两种方法可以解决此问题.第一个方法是像这样更改您的汽车文档的结构:
There are two ways in which you can solve this. The first one would be to change the structure your car document like this:
docId
|
--- filters
|
--- "country": "Netherlands"
|
--- "city": "Amsterdam"
通过这种方式,您可以使用以下方法过滤数据库:
In this way you can filter your database using:
Query query = db.collection("EU-CARS").
.whereEqualTo("filters.country", "Netherlands")
.whereEqualTo("filters.city", "Amsterdam");
在Firestore中允许束缚多个 whereEqualTo()
方法.
Chaining multiple whereEqualTo()
methods is permitted in Firestore.
或者,如果您仍然想使用数组,只需将两个名称连接成一个单数:
Or if you still want to use arrays, simply concatenate both names into a sigle one:
docId
|
--- "countries_cities": ["Netherlands_Amsterdam", "Netherlands_Utrecht"]
相应的查询应如下所示:
The corresponding query should look like this:
db.collection("EU-CARS")
.whereArrayContains("countries_cities", "Netherlands_Amsterdam");
如果您有多个国家/地区,则文档的结构应如下所示:
If you have multiple countries/cities, then the structure of your document should look like this:
docId
|
--- filters
|
--- "Netherlands": true
|
--- "Amsterdam": true
|
--- "Utrecht": true
通过这种方式,您可以使用以下方法过滤数据库:
In this way you can filter your database using:
Query query = db.collection("EU-CARS").
.whereEqualTo("filters.Netherlands", true)
.whereEqualTo("filters.Amsterdam", true);
这篇关于无法查询多个值的Firestore数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!