0

I'm working on a search functionality and my current code works for searching using the name_lower field in my firestore document.

Supposed I have this document in my collections:

{
  name_lower: 'burnik',
  keywords: ['gago', 'sira']
}
const searchArr = searchParams.split(' ');

const snap = await productsRef
        .where('name_lower', 'in', searchArr)
        .limit(12)  
        .get();

But how do I query if I also want to query for matched keywords in my document

This is not valid since I have combined a in and array-contains-any filter as the error says.

const snap = await productsRef
        .where('name_lower', 'in', searchArr)
        .where('keywords', 'array-contains-any', searchArr) // <------- invalid  
        .limit(12)
        .get();

I thought of a possible solution by making another query for matched keywords then filter and combine them.

const matchedNameSnap = await productsRef
        .where('name_lower', 'in', searchArr)
        .limit(12)  
        .get();

const matchedKeySnap = const snap = await productsRef
        .where('keywords', 'array-contains-any', searchArr)
        .limit(12)  
        .get();

// ... map and filter matchedKeySnap and matchedNameSnap

IS THERE AN 'OR' statement in Firebase or at least a better workaround how to query either of the WHERE clause?

Julius Guevarra
  • 690
  • 1
  • 7
  • 19
  • 1
    Firestore has no support for `OR` conditions across different fields. You'll have to do as you say: perform two separate queries, and merge the results in your application code. – Frank van Puffelen Dec 29 '20 at 04:58
  • Gotcha. I wonder how it would affect the performance. I have about 200 documents at the moment. Could be a huge workload if I have thousands. – Julius Guevarra Dec 29 '20 at 05:07
  • Firestore only allow queries for which is can guarantee the performance. The main guarantee is that a query will take the same amount of time, no matter how many documents are in the collection(s) queried. So if Firestore doesn't support a certain query feature it typically because it can't make that guarantee. In that case it's up to you to implement, so that you can also make your own determination on what the performance impact is. – Frank van Puffelen Dec 29 '20 at 05:13

0 Answers0