我有大约 100,000,000 条记录的 MongoDB 集合。
\n\n在网站上,用户使用“细化搜索”功能搜索这些记录,他们可以按多个条件进行过滤:
\n\n此外,他们还可以查看排序的搜索结果:
\n\n我需要创建索引以避免对上述任何组合进行全面扫描(因为用户使用大多数组合)。遵循相等排序范围规则,我必须创建很多索引:
\n\n所有过滤器组合 \xc3\x97 所有排序 \xc3\x97 所有范围过滤器,如下所示:
\n\ncountry_title\nstate_title\nregion_title\ntitle_price\nindustry_title\ncountry_title_price\ncountry_industry_title\nstate_industry_title\n...\ncountry_price\nstate_price\nregion_price\n...\ncountry_bestMatch\nstate_bestMatch\nregion_bestMatch\n...\nRun Code Online (Sandbox Code Playgroud)\n\n事实上,我有更多的标准(包括相等和范围),以及更多的排序。例如,我有多个价格字段,用户可以按任何价格排序,因此我必须为每个价格字段创建所有过滤索引,以防用户按该价格排序。
\n\n我们使用 MongoDB 4.0.9,目前只有一台服务器。
\n\n在我进行排序之前,这会更容易,至少我可以有一个复合索引,例如country_state_region当搜索某个地区时,并且始终在查询中包含国家/地区和州。但是在最后有排序字段,我不能再这样做了 - 即使对于位置(国家/州/地区),我也必须使用所有排序组合创建所有不同的索引。
另外,并不是所有的产品都有价格,所以我不能只按price字段排序。相反,我必须创建两个索引:{hasPrice: -1, price: 1}和{hasPrice: -1, price: -1}(此处,hasPrice 为 -1,无论价格排序方向如何,始终首先包含 hasPrice=true 的记录)。
目前,我使用 NodeJS 代码生成类似于以下内容的索引(这是简化的示例):
\n\ncountry_title\nstate_title\nregion_title\ntitle_price\nindustry_title\ncountry_title_price\ncountry_industry_title\nstate_industry_title\n...\ncountry_price\nstate_price\nregion_price\n...\ncountry_bestMatch\nstate_bestMatch\nregion_bestMatch\n...\nRun Code Online (Sandbox Code Playgroud)\n\n因此,上面的代码生成了 90 多个索引。而在我真正的任务中,这个数字甚至更多。 …