如何配置和使用基本的Field Facet?

解读

国内电商、内容、日志类项目面试中,Facet(面状导航/聚合)是 Solr 的必考点。面试官想确认三件事:

  1. 你是否理解 Facet 与普通 groupBy 的区别(无需预聚合、实时、可多级)。
  2. 能否在 schema 与 solrconfig 中完成最小闭环配置。
  3. 能否写出符合中文业务场景的查询语句,并解释常见“结果不对”的根因(字段未索引、分词过碎、缓存未命中等)。
    回答时先给“能跑起来”的最小配置,再补一句“线上必须关 cache 或做预热”,体现工程经验。

知识点

  1. Field Facet 本质:对指定字段的倒排表做“词条计数”,返回“值-出现次数”列表。
  2. 前置条件:字段必须 indexed="true"(若 docValues="true" 可省 uninvert 开销),multiValued 字段同样支持。
  3. 关键参数:facet=on、facet.field、facet.limit、facet.mincount、facet.sort、facet.method(enum/fc/fcs)。
  4. 中文陷阱:
    • text_ik 分词后词条过多 → 面版爆炸,需改用 string 类型或 copyField 到未分词字段。
    • 大小写折叠未统一 → 出现“北京”“北京”两条;需在 schema 中增加 LowerCaseFilter。
  5. 性能:默认 facet.method=fc(DocValues),数据量<200 万可全内存;亿级需搭配 facet.method=fcs(单段枚举)或 JSON Facet API。

答案

“我按‘三步走’落地 Field Facet:
第一步,schema 里声明聚合字段。以电商类目为例,保证类目字段既需要搜索又需要聚合,我建两个字段:
<field name="cat_path" type="text_ik" indexed="true" stored="true" multiValued="true"/>
<field name="cat_facet" type="string" indexed="true" docValues="true" stored="false"/>
通过 copyField 把 cat_path 原值拷贝到 cat_facet,保证聚合时不再分词。
第二步,solrconfig 中无需额外组件,但为减少 young GC,我给 cat_facet 加了默认的 filterCache 预热:
<listener event="firstSearcher" class="solr.QuerySenderListener">
<arr name="queries"><str>q=:&facet=true&facet.field=cat_facet&facet.limit=50</str></arr>
</listener>
第三步,查询端 URL:
/select?q=:&facet=on&facet.field=cat_facet&facet.limit=10&facet.mincount=1&facet.sort=count
返回片段:
"facet_fields":{
"cat_facet":["手机通讯",8650,"电脑整机",4200,"家居日用",3100]
}
若发现返回条数与业务库对不上,先检查 cat_facet 是否漏拷,再确认有无 fq 过滤导致基数缩小,最后用 debug=timing 看 facet 阶段耗时,超过 50 ms 就考虑把 method 改成 fcs 并开启 facet.threads=4。”

拓展思考

  1. 多级 Facet(pivot)与 Field Facet 混用:
    在电商筛选“品牌+价格区间”时,用 facet.pivot=brand,price_range 可一次返回二级树,减少两次 round-trip;但 pivot 内存开销是单字段的 n×m 倍,需开启 docValues=true 并限制 facet.pivot.mincount。
  2. 实时场景下的“索引可见性”:
    国内大促 0 点瞬间涌入增量,若 openSearcher=false 则新数据 Facet 不可见,需设置 commitWithin=1000 并配合 softCommit 保证近实时,同时把 facet.method 设成 fc 避免 reopen 时重新 uninvert。
  3. 安全与权限:
    对 toB 知识库项目,不同租户看到不同 Facet 值,需在自定义 SearchComponent 里对 Facet 结果做二次过滤,或提前把租户 ID 拼成字段值,如“tenantA_类目”,查询时自动加 fq=tenant_id:A,防止横向越权。