title: 数据索引


本篇文档介绍如何在规则表达式中使用 .indexOn 规则为节点建立索引,提高查询效率。

规则表达式包含以下两种 .indexOn 的索引方式:

索引方式 说明
orderByChild 根据子节点索引
orderByValue 根据值索引

提示:

节点的名称 (key) 和优先级 (priority) 已默认建立索引,不需要额外设置。

orderByChild 索引

为子节点建立索引,可以提高 orderByChild 的查询效率。

例如,在下面学生的信息中,可以根据姓名、年龄、分数进行排序,数据结构如下:

  1. {
  2. "students": {
  3. "Jack": {
  4. "age" : 21,
  5. "score" : 88,
  6. "weight": 63
  7. },
  8. "Lucy": {
  9. "age" : 22,
  10. "score" : 91,
  11. "weight" : 49
  12. }
  13. }
  14. }

通过 .indexOn 规则,为这些节点建立索引:

  1. {
  2. "rules": {
  3. "students": {
  4. ".indexOn": ["age", "score"]
  5. }
  6. }
  7. }

orderByValue 索引

为节点的值建立索引,可以提高 orderByValue 的查询效率。

例如,为学生分数建立一个排行榜,数据结构如下:

  1. {
  2. "scores": {
  3. "Jack" : 55,
  4. "Lucy" : 81,
  5. "LiLei" : 80,
  6. "HanMeimei" : 93,
  7. "Michael" : 66,
  8. "Jane" : 78
  9. }
  10. }

通过 .indexOn 规则,为这些节点建立索引。

  1. {
  2. "rules": {
  3. "scores": {
  4. ".indexOn": ".value"
  5. }
  6. }
  7. }