To enhance the search functionality, consider adding a new property called searchTerms
when creating or updating a document. Here's how you can achieve this:
let docName = 'blueberry pie';
let ref = /* some path */.collection('items').doc();
let doc = { /* initialize your doc here */ }
doc.searchTerms = docName.split(' ').reduce((acc, term) => {
acc[term] = true;
return acc;
}, {});
ref.set(doc)
When querying for these docs later, use the following approach:
let targetTerm = 'pie'
let key = `searchTerms.${targetTerm}`;
let query = /* some path */.collection('items').where(key, '==', true)
In a recent update in August, the platform added support for searching arrays in Firestore. This allows you to simplify the code by using where-contains
in the query:
// same as before
doc.searchTerms = docName.split(' ');
ref.set(doc)
For future implementation, you can create a cloud trigger with onCreate
to automate the process of building the search terms field. This way, developers working on document creation don't have to worry about this aspect.