I want to query my Workout Collection for the latest workout from a routine. Meaning I query with whereEqualTo my routineKey, order it by the Started TimeStamp in descending order and then limit to 1 and then take the this 1st Key/Id of the Workout.
However this does not work. whereEqualTo and orderBy work separately but not combined. What am I doing wrong?
fm.getColRefWorkout().whereEqualTo("routineKey", routineKey).orderBy("startTimeStamp", Query.Direction.DESCENDING).limit(1).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
workoutKey = documentSnapshots.getDocuments().get(0).getId();
//To stuff with this workoutKey
}
});
This query will not work unless you create an index for it. This can be done, by creating it manually in your Firebase Console or if you are using Android Studio, you'll find in your logcat a message that sounds like this:
FAILED_PRECONDITION: The query requires an index. You can create it here: ...
You can simply click on that link or copy and paste the URL into a web browser and your index will be created automatically.
Related
I am doing Library db , sometimes I need to remove books and add a new one and I dont like how it starts missing lower ids and it just goes one . Because Serial just increade everytime . Is there a way how to do that ? For example different type of column instead of SERIAL
I don't know if that will solve your problem but I suggest that you do updating for all serial ids again.
So If you want it to be (1,2,3,4) so you can use this query :
ALTER SEQUENCE seq RESTART WITH 1;
UPDATE t SET idcolumn=nextval('seq');
source: How to reset sequence in postgres and fill id column with new data?
You can create a service that executes this query inside deleting books service, so after deleting books you will call this service to rearange ids
public void UpdateIds() {
// make a connection with your database and send query above to update ids
}
and in your service where you delete books, I suppose you have a service looks like that
public void deleteBooks(//some books ids to be deleted
){
//some code for deleting books by ids
// call the method above to update ids again
UpdateIds()
}
I'm working on an Android App written in Java.
I'm trying to query for documents in Cloud Firestore using collectionGroup and whereArrayContains.
My structure in Cloud Firestore looks like this:
Teams (collection)
- teamUUID (document)
- reservations(collection)
- reservationDate (document)
- places (collection)
- userUUIDs (array of strings)
-> one entry ->"vQn9vbWzTtcsB71hgPBhX2uWBuI3"
- placeID (document)
partial screenshot of the structure
I want to get all documents in the collection places, where the userUUIDs field contains a specific string. My code for this is the following:
db.collectionGroup("places")
.whereArrayContains("userUUIDs",
"vQn9vbWzTtcsB71hgPBhX2uWBuI3")
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
Log.d(TAG, String.valueOf(queryDocumentSnapshots.getDocuments().size()));
if (queryDocumentSnapshots.isEmpty()) {
//nothing found
Log.d(TAG, "nothing found for this user");
If this code is executed, the query is successful, but no documents are returned.
If I leave out .whereArrayContains("userUUIDs", "vQn9vbWzTtcsB71hgPBhX2uWBuI3"), one document is returned.
Google Firestore automatically created the index to query for "userUUIDs".
index created in firestore
Why are there no documents returned using whereArrayContains?
Edit:
The problem seams to exist with all queries.
I added a string testValue to places and made a whereEqualTo Query. The result was the same. After creating an index (automatically via link in the console) the onSuccessListener code was executed, but no document was found.
Thanks in advance.
Why are there no documents returned using whereArrayContains?
Because you most probably didn't create the correct index. If the userUUIDs exists within the documents from the "places" collection, when running the app you'll find a message like this in the logcat:
Caused by: io.grpc.StatusException: FAILED_PRECONDITION: The query requires a COLLECTION_GROUP_CONTAINS index for collection places and field userUUIDs. You can create it here: https://console.firebase.google.com/v1/r/project/...
You can simply click on that link or copy, and paste the URL into a web browser and your index will be created automatically.
I have a list of status enum values which I am currently iterating over and using a basic counter to store how many in my list have the specific value that I am looking for. I want to improve greatly on this however and think that there may be a way to use some kind of JPA query on a paging and sorting repository to accomplish the same thing.
My current version which isn't as optimized as I would like is as follows.
public enum MailStatus {
SENT("SENT"),
DELETED("DELETED"),
SENDING("SENDING"),
}
val mails = mailService.getAllMailForUser(userId).toMutableList()
mails.forEach { mail ->
if (mail.status === MailStatus.SENT) {
mailCounter++
}
}
With a paging and sorting JPA repository is there some way to query this instead and get a count of all mail that has a status of sent only?
I tried the following but seem to be getting everything rather than just the 'SENT' status.
fun countByUserIdAndMailStatusIn(userId: UUID, mailStatus: List<MailStatus>): Long
I'm trying to run a query on my firebase database in order to return only those results where timestamp = the date specified in the date picker (see picture of app) I want this query to run whenever I press the view records button
[![Firebase][3]][3]
I am able currently to print out all objects into the recycler view, however when attempting to run my query its not producing any results, no errors and no faults in debugging
If I need to provide anymore detail please let me know
[3]: https://i.stack.imgur.com/d2uu2.png
To solve this, please change the following line of code:
options = new FirebaseRecyclerOptions.Builder<Records>().setQuery(databaseReference, Records.class).build();
to
options = new FirebaseRecyclerOptions.Builder<Records>().setQuery(query, Records.class).build();
// ^ ^
You have to pass to the setQuery() method the query object and not the databaseReference object because the query object actually filters your data.
Edit:
According to your comment:
Yep its working when hardcoded, but it's not working when getting the text view to string
This means that passing the query object did the trick but the problem remains on how you convert the data to String. To sovle this, be sure that the String representation of the date is of type: 04-02-2017 and your problem will be solved.
I want to retrieve the data from Firestore using a query that consists of whereLessThan() and whereGreaterThan() methids. But when I use the following query it returns me empty snapshot:
Query query = firestore.collection("Users").whereLessThan("id",id).whereGreaterThan("id", id).orderBy("id");
But when I use only 1 clause it successfully retrives data:
Query query = firestore.collection("Users").whereLessThan("id",id); //Working Fine
I have also tried by attaching snapshotListener to query:
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent( QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e)
{
if(queryDocumentSnapshots.isEmpty()){
Toast.makeText(RetrieveUserActivity.this, "No data found", Toast.LENGTH_SHORT).show();
}
}
});
This shows Toast of No Data Found.
Here is my database structure:
If I understand it right, you are trying to exclude a single user with a specific id from your Users collection. If so, you should change the logic of your code because unfortunately, you cannot achieved this in the way you do. That's why you get an empty snapshot. If you would have been using the following line of code:
Query query = firestore.collection("Users")
.whereLessThanOrEqualTo("id",id)
.whereGreaterThanOrEqualTo("id", id)
.orderBy("id");
The snapshot object will contain only a single result, which is a single user with that particular id. The above line of code, could also be written in more simpler way like this:
Query query = firestore.collection("Users")
.whereEqualTo("id",id)
.orderBy("id");
I gave you this examples to understand better how this methods work. To solve your problem, according to the official documentation regarding Query limitations:
Cloud Firestore does not support the following types of queries:
Queries with a != clause. In this case, you should split the query into a greater-than query and a less-than query. For example,
although the query clause where("age", "!=", "30") is not supported,
you can get the same result set by combining two queries, one with
the clause where("age", "<", "30") and one with the clause
where("age", ">", 30).
So with other words, there is no != (not equal to) operator in Firestore. The only option that you have is to split your query into a greater-than and a less-than query and then it will work perfectly fine