我正在尝试使用Firebase查询进行关键字搜索,但它们似乎从未检索到正确的值。它始终是数据库的第一个子级。数据库通过autoid使用child进行组织。我的数据看起来像这样

posts :
-KJj6DMQVcaOIBZ76X03
      category:
         "cleaner"
      dishname:
         "Lysol"
        likes
      8QCQPfShSTdYe1VbCxHK4dkJPFj1:
         true
      likesCount:
           1
       picURL:
      "https://firebasestorage.googleapis.com/v0/b/dis..."
       poster:
      "8QCQPfShSTdYe1VbCxHK4dkJPFj1"
       price:
         "$5"
       restaurant:
         "house"
-KJj6PaHt9EfXQ5-EU-m

-KJnTUcb3BvZDMI0Pxgo

-KJnTl4giuy5QMvdeEo5


执行搜索的功能如下所示

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    filteredPosts.removeAll()
    let postref = firebase.child("posts")
    let  search = searchController.searchBar.text!
    print(search)
    let postQ = (postref.queryOrderedByKey().queryEndingAtValue(search))
    // postQ.keepSynced(true)
    postQ.observeSingleEventOfType(.ChildAdded, withBlock: { (snapshot) in
    self.filteredPosts.append(snapshot)
    print(snapshot)
    self.shouldShowSearchResults = 2
        self.tableView.reloadData()
    })
    searchController.searchBar.resignFirstResponder()
 }


真令人沮丧。请帮忙

最佳答案

您要按键postref.queryOrderedByKey()排序,然后按该键的值queryEndingAtValue(search)查询。

因此,除非您的search变量是childByAutoId值(-KJnTUcb3BvZDMI0Pxgo)之一,否则我认为您不会获得想要的结果。

而是按要搜索的子属性排序。假设您要按帖子的category搜索。

var search = "cleaner"
let categoryQuery = postref
   .queryOrderedByChild("category")
   .queryEndingAtValue(search)


这将拉回-KJj6DMQVcaOIBZ76X03的记录。

10-07 19:26
查看更多