dart: get SQL like "%text%" search from firebase database snapshot - android

i am currently working on a search function in my app. this gets a reference of my firebase database snapshot. im using the firebaseDatabase package for this.
currently im using this to search my database
FirebaseDatabase.instance.reference().child('products').orderByChild('title').equalTo(searchQuery)
the searchQuery variable is the the used string to search the database. this returns the list of products which the titles are equal to searchQuery.
searchQuery = 'hello';
title1 = 'hello';
title2 = 'hello there';
for now, only
searchQuery == title1;
searchQuery != title2;
but i also want this to be returned
searchQuery == title2;
is this possible in the way im using this for now?

You are looking for a contains query, but Firebase doesn't provide that. You can refine your actual query by looking for values that are equalTo or endAt or startAt (these methods are available to you as well). Making three requests is going to be costly, though.
If your database is not large and your data is not sensitive, I suggest fetching the whole data and making a client-side filter as shown here.

Related

Firebase Firestore OR query (Android Studio)

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.

How do I get data from a firebase realtime database and change one text field to represent that specific record?

This is my first post here so sorry for any confusion!
I recently started using Flutter and I'm new to Firebase too.
I'm using a realtime database as the backend for my app, and I've got a hierarchy that looks like:
What I want to do is lookup a specific user by their id, fetch their information (gender and name in this case) and then set a widget (in this case a text widget) to use that value.
How can this be accomplished?
I've searched through a lot of StackOverflow questions about this, and all of them use FutureBuilders or DataSnapshots and I can't quite work out how to go about sorting them out so they work.
All of the tutorials online also don't get info from a specific user and instead query the entirety of the database.
You can do the following:
db = FirebaseDatabase.instance.reference().child("Users");
db.orderByKey().equalTo(Id).once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key,values) {
print(values["name"]);
});
});
First, you get an instance to the node User, and then using orderByKey() you can search the user by the id, and retrieve the name and gender.
Check the link following for more information:
https://github.com/flutter/plugins/blob/master/packages/firebase_database/lib/src/query.dart#L183

Android's Firestore to join 2 collections into a recycler view

I have a users collection with uId, name, photo
I have a visits collection with uId, userId, location
I have a recyclerview in which I want to show the location with the user name and photo
Can I use the reference field type? If so, how will Firestore know to link visits.userId == users.uId ?
Maybe I first need to query all the visits and then query the relevant user but 2 things:
It means querying a lot of times.
I didn't understand how to collect the joined collection into the adapter, which is based on one query?
Please advice
Thanks
current code
visitsList = db.collection("visitsList");
Query query = visitsList.whereEqualTo("userId",prefs.getString("id","")).orderBy("visitDate", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<AVisit> options = new FirestoreRecyclerOptions.Builder<AVisit>().setQuery(query, AVisit.class).build();
adapter = new VisitsListAdapter(options, VisitsListActivity.this);
RecyclerView rv = findViewById(R.id.rvVisitsList);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setAdapter(adapter);
The code is a simple query from the collection, not sure how to get the name and photo from the userId field in that collection.
Can I use the reference field type?
Yes, you can use a reference field.
If so, how will Firestore know to link visits.userId == users.uId ?
Firestore results always comes from a single collection (at the moment). It does not automatically join the document from the users collection when you're reading from the visits collection. You will have to do this yourself.
That indeed means you'll be executing multiple reads, but it's often not nearly as slow as you may think. See Google Firestore - how to get document by multiple ids in one round trip?
Update: To show data from the user profile in a list of visits, there are two main options:
load the additional user document in populateView or with a custom parseSnapshot implementation.
duplicate the relevant user data in the visits collection (which is quite normal in NoSQL databases). Also see Alex' answer here: indexed query with FirestoreRecyclerAdapter.

How to get the document ID after replicating database

I am currently making a database program using couchbase on android. After I replicating the data, how can I get the document ID so I can list down all the things in database.
You need to make use of Queries!
If you would like to retrieve all the documents (or their IDs), you could use All-documents query.
Query query = database.createAllDocumentsQuery();
QueryEnumerator result = query.run();
for (Iterator<QueryRow> it = result; it.hasNext(); ) {
QueryRow row = it.next();
Log.w("MYAPP", "document ID: %s", row.getDocumentId()); // or QueryRow also has a way to get its source document.
}
You could write your own Views as per your need and later query them for results.
Also look at how to deal with document(s) in a database over here. In fact, I recommend going through entire guide.

How to retrieve data from multiple Parse.com Tables/Classes

I have two tables (Classes):
StudentInformation: with columns RollNumber, address, name, school
StudentMarks : with columns RollNumber, Marks1, Marks2, Marks3
I've been able to save the data from a single form into these two simultaneously, but not getting a clue on how to put a query while retrieving into a listview or any other view something like
'return rows (from both tables together) where roll number = 1234' / 'return rows (from both tables together) where Marks2 > 50'
I'm using Parse.com backend for Android
Kindly help
Thanks
First, the UI aspect of showing in a ListView is provided by ParseQueryAdapter. https://parse.com/docs/android_guide#ui-queryadapter
Regarding the query, I do not think you can join tables in the way you want. Instead, you could create a pointer in StudentMarks to StudentInformation.
Then you can query something like:
ParseQuery<ParseObject> query = ParseQuery.getQuery("StudentMarks");
query.include('studentInformation'); // include the pointer to get StudentInformation
query.whereEqualTo("RollNumber", 1234);
query.whereGreaterThan("Marks2", 50);
... // perform query
In the results StudentInformation will be available like this:
List<ParseObject> objects; // the result from the query
ParseObject studentMark = objects.get(0); // example using first object
ParseObject studentInformation = studentMark.get("studentInformation");
String studentName = studentInformation.get("name");
String studentAddress = studentInformation.get("address");
... // etc
Alternatively you could also store a Relation of StudentMarks on StudentInformation, just to let you know that this is also an option, though I do not feel like it fits your current need as well as the solution presented above.

Categories

Resources