在Firebase数据库中查询关键字

时间:2017-06-15 17:45:39

标签: firebase firebase-realtime-database

支持我有一个如下数据库:

{
  "eventAttendees" : {
    "fm" : {
      "9" : "Alice",
      "23" : "Khanh",
      "43" : "Bach"
    }
  },
  "events" : {
    "fm" : {
      "date" : "2017-06-16",
      "name" : "I love Firebase Meetup in Tokyo yesterday". 
    },
    "gm" : {
      "date" : "2017-08-12",
      "name" : "Meet Linh"
    }
  },
  "users" : {
    "1" : {
      "name" : "David"
    },
    "2" : {
      "name" : "Alice"
    },
    "10" : {
      "name" : "Khanh"
    }
  }
}

如果我查询关键字" Firebase Meetup",则可以。

let query = ref.child("events").queryOrdered(byChild: "name").queryEqual(toValue: "Firebase Meetup").queryLimited(toFirst: 1)
        query.observe(.value, with: { (snapshot) in
             let content = snapshot.value as? [String : AnyObject] ?? [:]
            print(content)

- >返回

["fm": {
    date = "2017-06-16";
    "name" : "I love Firebase Meetup in Tokyo yesterday". ;
}]

但如果我查询关键字" Firebase",则无效。

如果可以查询" Firebase"得到如下结果?

 ["fm": {
            date = "2017-06-16";
            "name" : "I love Firebase Meetup in Tokyo yesterday". ;
        }]

1 个答案:

答案 0 :(得分:0)

你可以使用startAt()函数:

let query = ref.child("events").queryOrdered(byChild: "name").queryStart(at: "I love Firebase").queryLimited(toFirst: 1)
        query.observe(.value, with: { (snapshot) in
             let content = snapshot.value as? [String : AnyObject] ?? [:]
            print(content)

此处的文档https://firebase.google.com/docs/reference/js/firebase.database.Query#startAt

此外,如果您想从Firebase开始或以Meetup结束,请执行以下操作:

let query = ref.child("events").queryOrdered(byChild: "name").queryStart(at: "Firebase").queryEnd(at: "in Tokyo yesterday").queryLimited(toFirst: 1)
        query.observe(.value, with: { (snapshot) in
             let content = snapshot.value as? [String : AnyObject] ?? [:]
            print(content)

此处的文档https://firebase.google.com/docs/reference/js/firebase.database.Query#startAt