Skip to content

Instantly share code, notes, and snippets.

@Ebrahim-Ramadan
Created August 26, 2024 19:23
Show Gist options
  • Save Ebrahim-Ramadan/2a48e4317495794cbf238b5045fece4b to your computer and use it in GitHub Desktop.
Save Ebrahim-Ramadan/2a48e4317495794cbf238b5045fece4b to your computer and use it in GitHub Desktop.
partial text search in firebase (the impossible task lol)
export const updateDocumentsWithVinyls = async () => {
try {
const collectionRef = collection(db, 'frames');
const querySnapshot = await getDocs(collectionRef);
for (const docSnapshot of querySnapshot.docs) {
const documentData = docSnapshot.data();
// Check if the document has a 'keywords' field and it's a comma-separated string
if (documentData.keywords ) {
const docRef = doc(db, 'frames', docSnapshot.id);
// Generate prefixes for each keyword and combine them into a single array
const prefixesArray = documentData.keywords.flatMap(keyword => generatePrefixes(keyword));
const updateData = {
keywords: prefixesArray // Update 'keywords' field with the array of prefixes
};
await updateDoc(docRef, updateData);
console.log(`Document ${docSnapshot.id} updated successfully.`);
}
}
} catch (error) {
console.error('Error updating documents:', error);
}
};
function generatePrefixes(str) {
const prefixes = [];
for (let i = 1; i <= str.length; i++) {
prefixes.push(str.substring(0, i));
}
return prefixes;
}
export const searchFrames = async (keyword) => {
try {
const lowercaseKeyword = keyword.trim();
// Create Firestore query
const framesRef = collection(db, "frames");
const q = query(
framesRef,
where('keywords', 'array-contains', lowercaseKeyword)
);
// Fetch documents
const querySnapshot = await getDocs(q);
console.log("Fetched documents:", querySnapshot.docs.map(doc => doc.data()));
const matchingProducts = [];
querySnapshot.forEach((doc) => {
let data = doc.data();
data.id = doc.id;
// Ensure arrays are properly formatted
if (data.color && typeof data.color === 'string') {
data.color = data.color.split(',').map(item => item.trim());
}
if (data.type && typeof data.type === 'string') {
data.type = data.type.split(',').map(item => item.trim());
}
if (data.price && typeof data.price === 'string') {
data.price = data.price.split(',').map(item => item.trim());
} else if (typeof data.price === 'number') {
data.price = [data.price.toString()];
}
matchingProducts.push(data);
});
return matchingProducts;
} catch (error) {
console.error('Error searching products:', error);
return [];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment