面试题答案
一键面试1. 基本索引设计与利用
- 视图函数编写:在CouchDB中,视图是基于map函数创建的。例如,如果要根据时间范围查询数据,假设文档结构中有一个
timestamp
字段。map函数可这样编写:
function (doc) {
if (doc.timestamp) {
emit(doc.timestamp, doc);
}
}
通过这个map函数,CouchDB会根据timestamp
创建索引。查询时,可利用这个索引快速定位符合时间范围的数据。
- 查询优化:在查询时,利用
startkey
和endkey
参数来限定范围。例如,查询2023 - 01 - 01
到2023 - 12 - 31
的数据:
GET /your - db/_design/your - design - doc/_view/your - view?startkey="2023 - 01 - 01"&endkey="2023 - 12 - 31"
2. 复合索引处理
- 复合索引设计:若需根据多个字段查询,如
timestamp
和category
,则需创建复合索引。map函数修改为:
function (doc) {
if (doc.timestamp && doc.category) {
emit([doc.timestamp, doc.category], doc);
}
}
这里将timestamp
和category
组合作为键进行emit
,CouchDB会创建复合索引。
- 复合索引查询:查询时,根据复合索引的顺序传递参数。例如,查询
category
为news
且timestamp
在2023 - 01 - 01
到2023 - 12 - 31
的数据:
GET /your - db/_design/your - design - doc/_view/your - view?startkey=["2023 - 01 - 01", "news"]&endkey=["2023 - 12 - 31", "news"]
3. 选择性索引
- 理解选择性索引:选择性索引针对部分数据创建索引。比如,数据库中有大量文档,但只对特定类型(如
type
为important
)的文档感兴趣。 - 选择性索引设计:map函数可这样编写:
function (doc) {
if (doc.type === "important" && doc.timestamp) {
emit(doc.timestamp, doc);
}
}
这样只对type
为important
的文档根据timestamp
创建索引,减少索引大小,提高对这部分数据的查询性能。
- 选择性索引查询:查询方式与基本索引类似,但由于只对特定类型数据有索引,查询时也针对这部分数据。如查询
type
为important
且timestamp
在2023 - 01 - 01
到2023 - 12 - 31
的数据:
GET /your - db/_design/your - design - doc/_view/your - view?startkey="2023 - 01 - 01"&endkey="2023 - 12 - 31"
由于索引限制,此查询仅返回type
为important
的数据。
4. 索引维护与调优
- 定期重建索引:随着数据的不断更新,索引可能会碎片化。定期重建索引可优化查询性能。可通过删除并重新创建设计文档(包含视图)来重建索引。
- 分析查询模式:持续分析实际的查询模式,确保索引设计与查询需求匹配。若发现新的查询模式,及时调整索引设计。