Firebase 无法在多个值上查询Firestore数据库

Firebase 无法在多个值上查询Firestore数据库,firebase,google-cloud-firestore,Firebase,Google Cloud Firestore,我有一个装满汽车的数据库。JSON格式如下: docId: { "countries": ["Netherlands"] "cities": ["Amsterdam"] } 我不能同时查询两个数组 db.collection("EU-CARS") .whereArrayContains("countries", "Netherlands") .whereArrayContains("cities", "Amsterdam"); 如何解决这

我有一个装满汽车的数据库。
JSON
格式如下:

docId: {
        "countries": ["Netherlands"]
        "cities": ["Amsterdam"]
   }
我不能同时查询两个数组

db.collection("EU-CARS")
    .whereArrayContains("countries", "Netherlands")
    .whereArrayContains("cities", "Amsterdam");

如何解决这个问题?

正如您已经注意到的,Firestore允许您只使用一个
whererrayContains()
方法调用来过滤您的汽车。如果要使用多个,将出现如下错误:

原因:java.lang.IllegalArgumentException:查询无效。查询仅支持单个数组包含筛选器

有两种方法可以解决这个问题。第一个是更改car文档的结构,如下所示:

docId
  |
  --- filters
       |
       --- "country": "Netherlands"
       |
       --- "city": "Amsterdam"
db.collection("EU-CARS")
    .whereArrayContains("countries_cities", "Netherlands_Amsterdam");
docId
  |
  --- filters
       |
       --- "Netherlands": true
       |
       --- "Amsterdam": true
       |
       --- "Utrecht": true
通过这种方式,您可以使用以下各项筛选数据库:

Query query = db.collection("EU-CARS").
    .whereEqualTo("filters.country", "Netherlands")
    .whereEqualTo("filters.city", "Amsterdam");
Query query = db.collection("EU-CARS").
    .whereEqualTo("filters.Netherlands", true)
    .whereEqualTo("filters.Amsterdam", true);
Firestore中允许链接多个
whereEqualTo()
方法

或者,如果仍要使用数组,只需将两个名称连接成一个单号:

docId
  |
  --- "countries_cities": ["Netherlands_Amsterdam", "Netherlands_Utrecht"]
相应的查询应如下所示:

docId
  |
  --- filters
       |
       --- "country": "Netherlands"
       |
       --- "city": "Amsterdam"
db.collection("EU-CARS")
    .whereArrayContains("countries_cities", "Netherlands_Amsterdam");
docId
  |
  --- filters
       |
       --- "Netherlands": true
       |
       --- "Amsterdam": true
       |
       --- "Utrecht": true
编辑:

如果您有多个国家/城市,则文档的结构应如下所示:

docId
  |
  --- filters
       |
       --- "country": "Netherlands"
       |
       --- "city": "Amsterdam"
db.collection("EU-CARS")
    .whereArrayContains("countries_cities", "Netherlands_Amsterdam");
docId
  |
  --- filters
       |
       --- "Netherlands": true
       |
       --- "Amsterdam": true
       |
       --- "Utrecht": true
通过这种方式,您可以使用以下各项筛选数据库:

Query query = db.collection("EU-CARS").
    .whereEqualTo("filters.country", "Netherlands")
    .whereEqualTo("filters.city", "Amsterdam");
Query query = db.collection("EU-CARS").
    .whereEqualTo("filters.Netherlands", true)
    .whereEqualTo("filters.Amsterdam", true);

谢谢你的回答。我将使用阵列,但在使用第一个解决方案时,如何存储多个城市和国家?只是好奇。哦,是的,你说得对。我的错,很抱歉,请查看我的最新答案。