I would like to perform wildcard queries on a Firebase database,
and do not know whether the libraries support this. - (my guess it does not.)
I want an optimal solution where the network traffic will be as little as possible, assume the dataset is millions of records.
Dataset (using prefix wildcard):
user_id:
id_001123:
name: "java"
id_002124:
name: "objective-c"
id_003125:
name: "swift"
How would the code look like to retrieve the record id_002124 name field using a wildcard, you only have a portion of the id. eg. "%124".
The expected result would be id_002124, and the name being "objective-c"
Any mobile language example code would great.
(Objective-C/Swift/Java)
Firebase Database queries can order/filter data based on the object's keys (e.g. id_001123), their values (doesn't apply in your case), or the value of a child property (e.g. the fact that name = "java").
For each of these Firebase can match items that have a specific value you specify, items starting at a value you specify, or items ending at a value you specify.
So you can create a query matching the item named objective-c with:
ref.child("user_id").orderByChild("name").equalTo("objective-c")
Or you can create a query matching id_001124 and id_001125 with:
ref.child("user_id").orderByKey().startAt("id_001125")
Or simply getting all items starting with id_0011:
ref.child("user_id").orderByKey().startAt("id_0011")
Or you can create a query matching id_001123 and id_001124 with:
ref.child("user_id").orderByKey().endAt("id_001124")
Firebase Database cannot filter based on the end of a value. So there is no way in your current data structure to get all items whose key ends in a 4.
Please read more about Firebase Database queries here: https://firebase.google.com/docs/database/android/lists-of-data#sorting_and_filtering_data
And see some of the many previous questions about searching for FirebaseL
How to perform sql "LIKE" operation on firebase?
Firebase query - Find item with child that contains string
Firebase "like" search on string
Related
I've been trying to find a query for almost 2 days now
I want to search id (current user id) from the document 4 fields (customer1,customer2,customer3,customer4)
Here is the firestore document picture
tried this query
final Query userQuery = collectionReference
.whereEqualTo("customer1",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer2",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer3",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer4",firebaseAuth.getInstance().getCurrentUser().getUid());
but this only shows up if the current ID is present in all 4. Is there any easier way to do this.
You can do that by using a field that is an array containing the uids you want to test, and then applying array-contains on it. In your case:
In your case:
customer: [customer1, customer2, customer3, customer4]
collectionReference
.where("customer ", "array-contains", firebaseAuth.getInstance().getCurrentUser().getUid())
Firestore does not support logical OR queries among mulitple fields. So, what you're trying to do is not possible with a single query using the database structure you have now. You would have to perform multiple queries and merge the results in the client.
If you want to be able to use a single query, you will have to change your database. One option is to put all the customers into a single array field and use an array-contains query to find a customer in that field.
In my database:
-Users(Top level collection):
---user1(doc):
----------pets(sub collection):
--------------pet1(doc)
--------------pet2(doc)
---user2(doc):
----------pets(sub collection):
--------------pet3(doc)
--------------pet4(doc)
If i have a List of ids: list("pet2", "pet3", "pet4)
Is there a way to do something like this and get a back a List of DocumentsSnapshots?
firestore.collectionGruop("pets")whereIn(FieldPath.documentId(), list)
It works with a root collection but i dont know if this is possible with a collection group
A collection group query is the only place where a filter on FieldPath.documentId() does not work the way you expect. That's because of some details about the way that this token actually works. If you try to this anyway, you will get an error like this:
Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but 'x' is not because it has an odd number of segments.
If you want to do a filter on document IDs in a collection group query, you will need to store the ID of the document as the value of a field in each document. If you use the field called "id", then you can filter on that field like this:
firestore
.collectionGruop("pets")
.whereIn('id', list)
This will give you a different error saying that you need to create an index, and give you a link to do so. After you create that index (it might take some time), you should be good to go.
See also: How to perform collection group query using document ID in Cloud Firestore
I am trying to make blocks of data (10 each) as query.
The limitToLast() and limitToFirst() work without each other but crashes the app when together.
query = db_reference_type.limitToLast((int) (long_total_buildings - (long_list_page * 10))).limitToFirst(10);
With long_list_page = 0 and long_total_buildings = 10
query = db_reference_type.limitToLast(10).limitToFirst(10);
The app just crashes when the program gets to that line.
There is no way to combine limitToFirst() and limitToLast() in a single query. You seem to be building a pagination system, and looking for an offset() condition, which doesn't exist in Firebase.
It's easier to understand what is possible once you know how Firebase processes your request.
When it receives a query at a location, Firebase retrieves an index of the items on that location on the property that you order the query on (or on the key if no order is specified).
It then finds the value that you've indicated you want to start returning items from. So this is a value of the property that you order the query on (or on the key if no order is specified).
It then finds the value that you've indicated you want to end returning items at. This too is a value of the property that you order the query on (or on the key if no order is specified).
So at this point the database has a range of values in the index, and by association the keys of the items matching those values.
It then clips the items in the range by either the number of items from the start (if you use limitToFirst()) or from the end (if you use limitToLast).
And then finally it returns the remaining items that match all criteria.
Note that the value you pass to limitToFirst/limitToLast is only used in the last step of this process. It is not used in step 3, which is what you seem to be trying.
This question already has an answer here:
Firebase query if child of child contains a value
(1 answer)
Closed 3 years ago.
I need a firebase query to filter the list based on the value of an array.
if any of the index of GID(Array) contains the given key. e.g my key is YsGMyfLSGRNHxDWQmhpuPRqtxlq1 and one node's GID have that on 0th index and other have that on 1st index. So these two lists need to be returned.
Currently, I can only get the one at 0th index using the code
//userID = YsGMyfLSGRNHxDWQmhpuPRqtxlq1
firebaseDatabase.child("Groups").queryOrdered(byChild: "GID/0").queryEqual(toValue:userID)
When I try to combine the query I am getting errors.
I don't know about your database structure, But I can explain that There is a limitation in Firebase Realtime database that you can only order by 1 child.
So now if we require to order by 2 Childs we can combine 2 nodes and make it 1 node and can apply order by query on it. For example
If we have username & email fields we can make a new field username_email and can apply order by on it.
Like
user: {
username: "john",
email: "john#g.com"
username_email = "john_john#g.com"
}
Now we can write
firebaseDatabase.child("user").queryOrdered(byChild: "username_email").queryEqual(toValue: "john_john#g.com");
There is no way you can filter your groups based on a value that exist within an array. If you want to query your database to get all groups a particular user is apart of, then you should consider augmenting your data structure to allow a reverse lookup. This means that you should add under each user object the groups in which that user is present.
This means that you'll need to duplicate some data, but this is not a problem when it comes to Firebase. This is a quite common practice, which is named denormalization and for that, I recommend you see this video, Denormalization is normal with the Firebase Database.
When you are duplicating data, there is one thing that need to keep in mind. In the same way you are adding data, you need to maintain it. With other words, if you want to update/detele an item, you need to do it in every place that it exists.
However, what you need is actually allowed in Cloud Firestore. Its array-contains operator allow you to filter documents that have a certain value in an array. For more on this topic, please see the following post:
Better Arrays in Cloud Firestore.
I have the JSON structure above
I want to get the list of vehicles where their ids ends with "123"
I had tried to use Query.endAt() method but i'm not sure if i'm using it right or it shouldn't give the required output
Query vehiclesRef;
vehiclesRef = db.getReference("vehicles").orderByKey().endAt("\uf8ff123");
Firebase Database queries can only perform prefix matches, so strings starting with a specific string or starting with a range of string. It is not possible to query for strings ending with a specific value, nor those ending with a range of values.
If you really want to do this within Firebase, consider also storing the reversed strings in the database:
"321_1_0"
"321_3_0"
"654_52_0"
Then you can query for strings starting with 321 with
vehiclesQuery = db.getReference("vehicles").orderByKey().startAt("321").endAt("321\uf8ff");