Solr电商分类:路径层次分词器实现及精准查询直接子分类
如何在电商场景中使用Solr路径层次分词器实现分类的直接子项分面查询?
问题描述
我在电商场景中使用Solr的路径层次分词器处理分类数据,当执行以下查询时:
http://localhost:8983/solr/mystore/select?facet.field=category&facet.prefix=Clothes&facet=on&q=*:*
得到了包含所有Clothes下层级的分面结果:
"facet_counts":{ "facet_queries":{}, "facet_fields":{ "category":[ "Clothes", 13, "Clothes/Man's", 10, "Clothes/Man's/T-shirt", 5, "Clothes/Man's/Pants", 4, "Clothes/Women's", 3, "Clothes/Man's/Pants/Breeches", 2, "Clothes/Man's/Pants/Jeans", 2, "Clothes/Man's/T-shirt/T-shirt", 2, "Clothes/Man's/T-shirt/Polo T-shirt", 2, "Clothes/Women's/Turtleneck", 1, "Clothes/Women's/leather jacket", 1, "Clothes/Women's/Parka", 1, "Clothes/Man's/Sweatshirt", 1 ] }, "facet_ranges":{}, "facet_intervals":{}, "facet_heatmaps":{} }
但我希望仅返回Clothes的直接子项(即Man's和Women's),期望结果如下:
"facet_counts":{ "facet_queries":{}, "facet_fields":{ "category":[ "Clothes/Man's", 10, "Clothes/Women's", 3 ] }, "facet_ranges":{}, "facet_intervals":{}, "facet_heatmaps":{} }
解决方案
要实现这个需求,你可以通过结合facet.prefix和正则表达式风格的facet.contains参数来精准过滤分面结果,调整后的查询如下:
http://localhost:8983/solr/mystore/select?facet.field=category&facet.prefix=Clothes/&facet.contains=[^/]*$&facet.contains.ignoreCase=true&facet=on&q=*:*
关键参数解析:
facet.prefix=Clothes/:将分面结果限定为以Clothes/开头的分类值,直接缩小范围到Clothes的子层级,排除顶层的Clothes本身。facet.contains=[^/]*$:使用正则表达式匹配结尾没有斜杠的路径——[^/]*表示匹配任意非斜杠字符,$表示字符串结尾。这样就能确保只保留Clothes/之后仅一级分类的项(没有更深的子目录),也就是我们需要的直接子项。facet.contains.ignoreCase=true:可选参数,用于忽略大小写差异,避免因分类值大小写不一致导致的结果遗漏。
执行上述查询后,就能得到你期望的仅包含Clothes直接子项的分面结果。
另外,如果你使用的是Solr 8.0及以上版本,也可以考虑在Schema中提前配置基于PathHierarchyTokenizer的分层字段,但上述查询方式无需修改Schema,更灵活快捷。
内容的提问来源于stack exchange,提问作者Anton Klichkov
相关产品推荐
相关产品推荐

