如何在Firestore中通过单次API调用读取含关联数据的单条或批量歌曲?
Firestore 关联数据查询方案与结构优化
当前数据结构
albums (collection) - album_id1 (doc) year: 1994 title: "1942: A Love Story" uploaded_at: February 23, 1997 at 7:15:52 AM UTC+5:30 thumbnail: "https:localhost:3000/album-image/1942alovestory" - album_id2 (doc) year: 2014 title: "2 States" uploaded_at: July 23, 2018 at 7:15:52 AM UTC+5:30 thumbnail: "https:localhost:3000/album-image/2states" ... artists (collection) - artist_id1 (doc) name: "2 Chainz" thumbnail: "https:localhost:3000/artist-image/2chainz" - artist_id2 (doc) name: "Arijit Singh" thumbnail: "https:localhost:3000/artist-image/arijitsingh" ... genres (collection) - genre_id1 (doc) name: "English" - genre_id2 (doc) name: "Hindi" songs (collection) - song_id1 (doc) album: (ref) /albums/album_id1 artists: [ (ref) /artists/artist_id1, (ref) /artists/artist_id2 ] genre: (ref) /genres/genre_id1 title: "Ek ladki ko dekha" ...
需求实现方案
Firestore不支持SQL式的JOIN查询,无法通过单次API调用直接拉取关联数据,但可以通过批量读取把调用次数降到最少:
1. 单条歌曲+关联数据查询
最少需要2次API调用:
- 第一步:调用
db.collection('songs').doc(songId).get()获取目标歌曲文档,提取其中的album引用、artists引用数组、genre引用。 - 第二步:把所有关联的文档整理成一个数组,调用
db.getAll(...refs)一次性获取所有关联的专辑、艺人、流派文档。
2. 25条歌曲+关联数据查询
同样最少2次API调用:
- 第一步:调用
db.collection('songs').limit(25).get()获取25条歌曲文档。 - 第二步:遍历所有歌曲,收集所有唯一的专辑、艺人、流派引用(避免重复读取同一文档),调用
db.getAll(...uniqueRefs)一次性获取所有关联文档,最后将关联数据与对应歌曲匹配。
数据结构调整建议
当前结构是规范的关系型拆分方式,适合关联数据频繁更新的场景。如果想进一步减少API调用次数,可做以下优化:
- 嵌入静态数据:比如流派名称基本不会变动,可直接把
genreName字段嵌入到song文档中,无需存储引用,查询时不用额外拉取流派数据。 - 部分嵌入关联数据:如果艺人、专辑的核心展示字段(名称、缩略图)更新频率低,可把这些字段嵌入到song文档里,比如在song中存
albumInfo: {title: "...", thumbnail: "..."}、artistsInfo: [{name: "...", thumbnail: "..."}],查询歌曲时直接拿到展示数据,不用再拉取关联文档。但要注意,嵌入数据会带来同步问题,关联数据更新时需手动更新所有相关song文档,仅适合低更新频率字段。
内容的提问来源于stack exchange,提问作者TheWorrier
相关产品推荐
相关产品推荐

