简体   繁体   English

基本搜索功能 firebase

[英]Basic search functionality firebase

I am just trying to search by keyword.我只是想按关键字搜索。 I have a search-box and when the user types i am trying to query firestore to find the closest search term.我有一个搜索框,当用户输入时,我试图查询 firestore 以找到最接近的搜索词。 Please can I get help with do.请问我能得到帮助吗。 I just want.我只是想。 to let the user search and it displays similar search terms from the data state让用户搜索并显示来自data状态的相似搜索词

This is my code这是我的代码

const SearchScreen = (props) => {
    const [searchDetails, setSearchDetails] = useState('');
    const [data, setData] = useState([]);
    const [recent, setRecent] = useState(true);
    const inputRef = React.useRef()
  
    const searchFilterFunction = async (searchTerm) => {
        setRecent(false)
        setSearchDetails(searchTerm);
        let data = []
    const db =  firebase.firestore().collection('Posts')
    const check = searchDetails === undefined? '': searchDetails
    await db.orderBy('name').startAt(check ).endAt(check + "\uf8ff" ).get().then(()=>{
        for (let i = 0; i < db.docs.length; i++) {
            data.push(snapshot.docs[i].data());
          }
        setData(data)
    })

    };
    const handleSearchResults = (name) =>{
        if(recent!== true){
            dispatch(searchRecent(name))
        }
        searchFilterFunction(name)
        props.navigation.navigate({
            routeName: "SearchResults",
            params:{
                searchDetails: searchDetails,
                searchData: data,
            }
          })
    }
    return (
        <View style={styles.container}>
                <SearchBar
                    placeholder="Search Recipe or ingredient."
                    onChangeText={(text) => searchFilterFunction(text)}
                    value={searchDetails}
                    ref={inputRef}
                    onSubmitEditing={()=> handleSearchResults(searchDetails)}
                />
            {/* shows the search terms like auto suggest */}
               <FlatList
                    showsVerticalScrollIndicator={false}
                    data={data}
                    keyExtractor={(item, index) => item.postId}
                    renderItem={renderItem}

                />
        </View>
    );
};
export default SearchScreen;

The feature that you are looking for has to be done through a third-party library.您正在寻找的功能必须通过第三方库完成。 Cloud Firestore doesn't support native indexing or search for text fields in documents. Cloud Firestore 不支持原生索引或搜索文档中的文本字段。 Additionally, downloading an entire collection to search for fields client-side isn't practical.此外,下载整个集合以在客户端搜索字段是不切实际的。

One alternative is to use “ Algolia ”, consider a note-taking app where each note is a document:一种替代方法是使用“ Algolia ”,考虑一个笔记应用程序,其中每个笔记都是一个文档:

// /notes/${ID}
{
  owner: "{UID}", // Firebase Authentication's User ID of note owner
  text: "This is my first note!"
}

You can use Algolia with Cloud Functions to populate an index with the contents of each note and enable search.您可以将 Algolia 与 Cloud Functions 结合使用,用每个笔记的内容填充索引并启用搜索。 First, configure an Algolia client using your App ID and API key, here it is an example with Node.js:首先,使用您的 App ID 和 API 密钥配置 Algolia 客户端,这里是 Node.js 的示例:

// Initialize Algolia, requires installing Algolia dependencies:
// https://www.algolia.com/doc/api-client/javascript/getting-started/#install
//
// App ID and API Key are stored in functions config variables
const ALGOLIA_ID = functions.config().algolia.app_id;
const ALGOLIA_ADMIN_KEY = functions.config().algolia.api_key;
const ALGOLIA_SEARCH_KEY = functions.config().algolia.search_key;

const ALGOLIA_INDEX_NAME = 'notes';
const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY);

After that you have to add a function that updates the index each time a note is written:之后,您必须添加一个每次写笔记时更新索引的函数:

// Update the search index every time a blog post is written.
exports.onNoteCreated = functions.firestore.document('notes/{noteId}').onCreate((snap, context) => {
  // Get the note document
  const note = snap.data();

  // Add an 'objectID' field which Algolia requires
  note.objectID = context.params.noteId;

  // Write to the algolia index
  const index = client.initIndex(ALGOLIA_INDEX_NAME);
  return index.saveObject(note);
});

Once your data is indexed, you can use any of Algolia's integrations for iOS, Android, or Web to search through the data.一旦您的数据被索引,您可以使用任何 Algolia 的 iOS、Android 或 Web 集成来搜索数据。

For example, to use with React-navite you can check the link例如,要与 React-navite 一起使用,您可以查看链接

Also, found this useful video with an implementation example for Algolia and Firebase called from a Frontend.此外,还发现了这个有用的视频,其中包含从前端调用的 Algolia 和 Firebase 的实现示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM