"array-contains-any" & "IN query" now on Firebase Firestore! Sample codes and demo.
nabettu
Posted on October 30, 2019
The convenient query array-contains-any & IN query has finally entered the JS SDK, so I tried using it!
Since it has just entered the SDK, there is no shadow or shape in the official document yet (as of 10/30/2019)
What is array-contains-any
Until now, if you specified "array-contains" for "where", you could search for a document with a specific value in array.
The actual code looks like this, and you can search for documents with "tech" in the array field in the blogs collection.
firebase
.firestore()
.collection("blogs")
.where("tags", "array-contains", "tech")
.get()
array-contains-any is an evolution of it. You can search for documents where the array contains one of the specific values.
The actual code looks like this, and you can search for documents that contain either "tech" or "game" in the array field in the blogs collection.
Basically the same as array-contains, but you can pass an array as the third argument of where.
firebase
.firestore()
.collection("blogs")
.where("tags", "array-contains-any", ["tech", "game"] )
.get()
And if any of this array is in, it will hit the search.
Now you can make a query that can describe an OR condition. Therefore, I think that the range that can be searched with Firestore alone will expand.
What is IN Query
The usage is as follows!
firebase
.firestore()
.collection("blogs")
.where("type", "in", ["tweet", "podcast"] )
.get()
A query that hits if it exactly matches either tweet or podcast in the type field.
You can now OR search for specific fields like array-contains-any! (Since it is an exact match, free string search is not possible yet)
Example of use) In a fold that contains a fixed type as described above, you can search for "when it matches a tweet or podcast".
This is a query that executes the data corresponding to "==" in all the arrays and summarizes the results.
Created a sample site
https://firestore-sandbox.netlify.com
Here you can execute both Array Contains and Array Contains Any on the sample data.
Click here for the repository.
https://github.com/nabettu/firestore-sandbox
Summary
The conditions that can be used so far are the same as array-contains, but the range of search can be made without using Algolia, so it seems to be useful!
that's all!
Posted on October 30, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 22, 2024