【问题标题】:Basic search functionality firebase基本搜索功能 firebase
【发布时间】:2020-12-27 17:22:37
【问题描述】:

我只是想按关键字搜索。我有一个搜索框,当用户键入时,我试图查询 firestore 以找到最接近的搜索词。请问我能得到帮助吗?我只是想。让用户搜索并显示来自data 状态的类似搜索词

这是我的代码

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;

【问题讨论】:

  • 有什么问题?具体来说:当您在调试器中单步执行此代码时,哪个特定行没有按照您的预期执行?如果它与数据库调用有关,您还需要显示您使用的check 的值、您搜索的数据以及您在回调中返回的结果。一般而言,请参阅how to create a minimal, complete, verifiable example,因为这是最大限度地提高他人可以提供帮助的更改的最佳方式。

标签: javascript firebase react-native google-cloud-firestore react-hooks


【解决方案1】:

您正在寻找的功能必须通过第三方库来完成。 Cloud Firestore 不支持原生索引或搜索文档中的文本字段。此外,下载整个集合以在客户端搜索字段是不切实际的。

另一种方法是使用“Algolia”,考虑一个笔记应用程序,其中每个笔记都是一个文档:

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

您可以将 Algolia 与 Cloud Functions 结合使用,以使用每个笔记的内容填充索引并启用搜索。首先,使用您的 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);

之后你必须添加一个函数,每次写笔记时更新索引:

// 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);
});

一旦您的数据被编入索引,您就可以使用 Algolia 的任何 iOS、Android 或 Web 集成来搜索数据。

例如,要与 React-navite 一起使用,您可以查看 link

此外,发现这个有用的 video 带有从前端调用的 Algolia 和 Firebase 的实现示例。

【讨论】:

  • 是否有更便宜的替代方案,因为我读到这可能会变得相当昂贵
  • 根据文档,替代方案之一是 ElasticSearch,elastic.co/home
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多