使用複合查詢字串在Firebase 中尋找參與者的聊天
在Firebase 中建立資料時,優化資料庫存取以實現高效檢索至關重要。在查詢複雜關係時,這一點變得尤為重要。
原始查詢問題
想像一個名為「chats」的 Firebase 表,其中包含參與者清單和聊天項目。目標是尋找所有涉及指定使用者名稱的聊天。不幸的是,目前查詢:
this.af.database.list('chats', { query: { orderByChild: 'participants', equalTo: username, // How to check if participants contain username } });
無效。這是因為:
最佳化資料結構
要解決這些問題,請考慮透過在樹的頂層儲存類別並展平資料庫結構來反轉索引:
userChatrooms: { john: { chatRoom1: true, chatRoom2: true }, puf: { chatRoom1: true, chatRoom3: true } }
此結構可讓您有效查詢特定使用者的聊天室清單:
ref.child('userChatrooms').child('john')
使用Cloud Firestore 進行複合查詢
如果使用Cloud Firestore,您可以利用其強大的功能數組包含運算符並將數組視為集合:
db.collection('chats').where('participants', 'array-contains', username)
此查詢有效地尋找包含指定使用者作為參與者的聊天。
透過最佳化資料結構並採用適當的查詢技術,您可以顯著提高複雜關係情境下 Firebase 查詢的效能。
以上是如何有效率地查詢 Firebase 中涉及特定參與者的聊天?的詳細內容。更多資訊請關注PHP中文網其他相關文章!