BigQuery正则文本分类:如何遍历所有CASE WHEN条件输出多匹配标签
SQL正则多标签分类实现
问题根因
原生CASE WHEN逻辑是顺序短路执行的:只要命中第一个满足的分支就会直接返回结果,后续所有判断条件不会被执行,天然不适合需要全量匹配所有规则的多标签分类场景。
实现全量命中的核心是:把每个匹配规则拆为独立的判断单元,不依赖CASE的分支返回,收集所有符合条件的标签后再做输出,常见有两种适配不同需求的实现方式。
方式1:整行返回标签数组
直接在单条文本对应的结果行里,把所有命中的标签存储为数组结构,适配需要保留原文本整行、同时携带全量标签的场景。
实现逻辑:将每个正则判断拆成独立的IF表达式,把命中的标签值收集为数组,自动过滤掉未匹配的空值元素。
WITH source_text AS ( SELECT 'It is undeniable that AI will change the landscape of the future. There is a frequent increase in the demand for AI-related jobs, especially in data science and machine learning positions. It is believed that artificial intelligence will change the world, just like how electricity changed the world about 100 years ago. As Professor Andrew NG has famously stated multiple times “Artificial Intelligence is the new electricity.” We have advanced immensely in the field of artificial intelligence. With the increase in the processing and computational power, thanks to graphical processing units (GPUs), and also due to the abundance of data, we have reached a position of supremacy in Deep Learning and modern algorithms.' AS text ) SELECT ARRAY( SELECT matched_tag FROM UNNEST([ IF(REGEXP_CONTAINS(text, r'(?i)ai'), 'AI', NULL), IF(REGEXP_CONTAINS(text, r'(?i)computational power'), 'Engineering', NULL), IF(REGEXP_CONTAINS(text, r'(?i)deep learning'), 'Deep Learning', NULL) ]) AS matched_tag WHERE matched_tag IS NOT NULL ) AS matched_topics, text FROM source_text
执行后,matched_topics字段会直接返回包含AI、Engineering、Deep Learning三个元素的数组,所有规则都会独立完成匹配计算,不会出现提前短路的问题。
方式2:每个标签拆为独立结果行
如果后续需要对标签维度做统计分析,可以将每个命中的标签拆成独立的结果行,这种方式的规则扩展性更强:后续新增分类规则不需要修改主查询逻辑,只需要在规则表中新增对应行即可。
实现逻辑:将所有正则规则和对应标签维护成独立的规则表,和原始文本做笛卡尔关联后,过滤出文本命中规则的关联行。
WITH source_text AS ( -- 待分类的原始文本数据集 SELECT 'It is undeniable that AI will change the landscape of the future. There is a frequent increase in the demand for AI-related jobs, especially in data science and machine learning positions. It is believed that artificial intelligence will change the world, just like how electricity changed the world about 100 years ago. As Professor Andrew NG has famously stated multiple times “Artificial Intelligence is the new electricity.” We have advanced immensely in the field of artificial intelligence. With the increase in the processing and computational power, thanks to graphical processing units (GPUs), and also due to the abundance of data, we have reached a position of supremacy in Deep Learning and modern algorithms.' AS text ), classify_rules AS ( -- 维护所有分类规则:标签值 + 匹配正则 SELECT 'AI' AS topic, r'(?i)ai' AS match_pattern UNION ALL SELECT 'Engineering', r'(?i)computational power' UNION ALL SELECT 'Deep Learning', r'(?i)deep learning' ) SELECT r.topic, t.text FROM source_text t CROSS JOIN classify_rules r WHERE REGEXP_CONTAINS(t.text, r.match_pattern)
这种方式下,示例文本会输出3行结果,每一行对应一个命中的标签。如果需要调整标签的排序权重,只需要在classify_rules表中新增权重字段,查询时增加排序规则即可。
内容的提问来源于stack exchange,提问作者Racana
相关产品推荐
相关产品推荐

