Like query and order

LongLv :

I have a problem with query condition in google Cloud Firestore.

Anyone can help me.

This is my Collection and documents

Below is my code to get first Document start with HA_ and order by ID DESC

public Article getLastArticleProvider() {
    ApiFuture<QuerySnapshot> query = firebaseDB.getTblArticles()
            .whereGreaterThanOrEqualTo("articleId", "HA_")
            .orderBy("id", Query.Direction.DESCENDING)
            .limit(1)
            .get();

    QuerySnapshot snapshotApiFuture;
    Article article = null;

    try {
        snapshotApiFuture = query.get();
        List<QueryDocumentSnapshot> documents = snapshotApiFuture.getDocuments();
        for (QueryDocumentSnapshot document : documents) {
            article = document.toObject(Article.class);
        }
    } catch (InterruptedException | ExecutionException e) {
        return null;
    }
    return article;
}

I want to get last id of article with articleId start with "HA_" or "XE_"

Ex for above image:

  • if(articleId start with "HA_") => return object of id 831
  • if(articleId start with "XE_") => return object of id 833

Now i get an error

java.util.concurrent.ExecutionException: com.google.api.gax.rpc.InvalidArgumentException: io.grpc.StatusRuntimeException: INVALID_ARGUMENT: inequality filter property and first sort order must be the same: articleId and id

Alex Mamo :

As the following error says:

inequality filter property and first sort order must be the same: articleId and id

So you cannot filter your elements and sort them in the same time, using different properties, in your case articleId and id.

There is also an example of how not to do it in the official documentation:

  • Range filter and first orderBy on different fields

    citiesRef.whereGreaterThan("population", 100000).orderBy("country"); //Invalid
    

So to solve this, you should filter and order on the same document property.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151816&siteId=1