0

I have a database full with cars. The JSON format is this:

docId: {
        "countries": ["Netherlands"]
        "cities": ["Amsterdam"]
   }

I cannot query both arrays.

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

How to solve this?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Jorn
  • 252
  • 1
  • 15

1 Answers1

1

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:

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");

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");

Edit:

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);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thanks for answering. I'll go with the arrays but how about storing multiple cities and countries when using the first solution? Just curious. – Jorn Apr 15 '19 at 10:08
  • Oh ya, you're right. My bad, sorry about that, Please see my updated answer. – Alex Mamo Apr 15 '19 at 10:13