skip to Main Content

I made a writing function with Firebase, but when I search for the title if it’s "ice cream", it comes out when I search for "ice cream", but it doesn’t come out when I search for "cream".

I’ve tried a plug-in called searchflex, but it doesn’t work.
I asked about the method I ordered on the Internet and AI, but I can’t do what I was told, so I have a question left.

import { db } from './firebaseConfig.js';
import { collection, getDocs } from 'firebase/firestore';
import { PostListManager } from './PostListManager.js';

export async function setupSearch() {
    const searchButton = document.getElementById('searchBtn');
    const searchInput = document.getElementById('searchInput');
    const resultsContainer = document.getElementById('results');

    const postListManager = new PostListManager('results');


    async function loadData() {
        try {
            const querySnapshot = await getDocs(collection(db, 'posts'));
            const posts = querySnapshot.docs.map(doc => ({
                id: doc.id,
                ...doc.data()
            }));
            return posts;
        } catch (error) {
            console.error('Error loading data from Firestore:', error);
            return [];
        }
    }

  
    async function performSearch() {
        const searchText = searchInput.value.trim().toLowerCase();
        if (searchText === "") {
            console.log("Empty search text.");
            return;
        }

        try {
            const posts = await loadData();
            const filteredPosts = posts.filter(post => {
                const titleMatch = post.title && post.title.toLowerCase().includes(searchText);
                const descriptionMatch = post.description && post.description.toLowerCase().includes(searchText);
                const contentMatch = post.content && post.content.toLowerCase().includes(searchText);
                return titleMatch || descriptionMatch || contentMatch;
            });

            if (filteredPosts.length === 0) {
                console.log('No matching documents found.');
            } else {
                console.log(`Found ${filteredPosts.length} matching documents.`);
            }

            postListManager.renderPosts(filteredPosts, false);
        } catch (error) {
            console.error('Error during search:', error);
        }
    }

    // 검색 버튼 클릭 이벤트
    searchButton.addEventListener('click', performSearch);

    // 엔터 키 입력 시 검색 수행
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
}

2

Answers


  1. I made a writing function with Firebase, but when I search for the title if it’s "ice cream", it comes out when I search for "ice cream", but it doesn’t come out when I search for "cream".

    That’s the expected behavior. There is no way you can search in Firestore after a substring. Firestore doesn’t support full-text search. Besides that, downloading an entire collection to search for fields client-side isn’t practical at all.

    Seeing the official documentation regarding full-text search in Firestore, there are three options available by the time I’m answering this question, which are Elastic Search, Algolia, and Typesense.

    If you want, you can simplify the process by using the corresponding Firebase Extensions, which are:

    Login or Signup to reply.
  2. One option for performing word searches in Firestore is store the original sentence or text as a document property and then break down the sentence or paragraph into individual words and store them in a separate array. Upon querying and finding a match, the document is returned so you can get the original text.

    A document could look like this pseudo-document

      sentences
         document_id_0
            original_text: "People of the Earth can you hear me"
            word_array:
                 0: "people"
                 1: "of"
                 2: "the"
                 3: "earth"
                 4: "can"
                 5: "you"
                 6: "hear"
                 7: "me"
    

    Query the sentences node for documents where word_array using array-contains that contain "earth", which will return document_id_0 (in this case) and the sentence contained in "original_text" property. Storing the words a lower case and querying lower case is advised.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search