[论文解读] Replace or Retrieve Keywords In Documents at Scale
本文提出 FlashText,一种基于字典树(trie-based)数据结构的快速、线性时间算法,用于在大规模文本文档中进行可扩展的关键词搜索与替换。与关键词集合较大时性能急剧下降的正则表达式(regex)不同,FlashText 的时间复杂度恒为 O(N),无论关键词数量多少,处理单个文档中 15,000 个关键词时,性能最高可比 regex 快 82 倍。
In this paper we introduce, the FlashText algorithm for replacing keywords or finding keywords in a given text. FlashText can search or replace keywords in one pass over a document. The time complexity of this algorithm is not dependent on the number of terms being searched or replaced. For a document of size N (characters) and a dictionary of M keywords, the time complexity will be O(N). This algorithm is much faster than Regex, because regex time complexity is O(MxN). It is also different from Aho Corasick Algorithm, as it doesn't match substrings. FlashText is designed to only match complete words (words with boundary characters on both sides). For an input dictionary of {Apple}, this algorithm won't match it to 'I like Pineapple'. This algorithm is also designed to go for the longest match first. For an input dictionary {Machine, Learning, Machine learning} on a string 'I like Machine learning', it will only consider the longest match, which is Machine Learning. We have made python implementation of this algorithm available as open-source on GitHub, released under the permissive MIT License.
研究动机与目标
- 解决在处理大规模关键词词典(如 10,000 个以上词条)时,基于正则表达式的关键词搜索与替换所面临的性能瓶颈。
- 设计一种与关键词数量无关、仅随文档长度线性增长的解决方案。
- 提供一个实用的开源工具,适用于简历解析、同义词标准化等真实世界的信息检索工作负载。
- 通过在不同关键词集合大小和文档长度下对比 FlashText 与 regex 的性能,量化其性能提升。
提出的方法
- 从输入关键词构建字典树字典,其中每个节点代表一个字符,词尾标记(eot)存储标准化的替换形式。
- 使用单词边界标记(\b)确保仅匹配完整单词,避免部分子串匹配(例如,'Apple' 不应匹配 'Pineapple')。
- 对输入文档进行单次逐字符扫描,通过遍历字典树检测完整关键词匹配。
- 在关键词搜索中,收集所有匹配项及其标准化形式;在替换操作中,将匹配项替换为其标准化对应形式输出。
- 优先匹配最长关键词(例如,'Machine Learning' 优先于 'Machine' 或 'Learning'),以避免替换歧义或重叠。
- 使用 Python 实现该算法,并以 MIT 许可证发布,供开源使用。
实验结果
研究问题
- RQ1在单个文档中搜索大量关键词时,FlashText 的性能与 regex 相比如何?
- RQ2随着关键词数量增加,FlashText 是否能保持常数时间性能,而 regex 的性能则随关键词数量线性增长?
- RQ3FlashText 是否能有效处理最长匹配优先级和单词边界约束,且无误报?
- RQ4在大规模文档处理流水线中,FlashText 相较于 regex 的实际性能提升有多大?
- RQ5FlashText 是否能高效用于信息检索工作负载中的关键词提取与替换?
主要发现
- 在 10,000 个词的文档中处理 15,000 个关键词时,FlashText 将搜索时间从 regex 的 0.165 秒降低至 0.002 秒,实现 82 倍加速。
- FlashText 的时间复杂度为 O(N),其中 N 为文档长度,且与关键词数量无关,因此具有极强的可扩展性。
- regex 的性能随关键词数量线性增长,而 FlashText 在关键词集合规模增加时仍保持近乎恒定的运行时间。
- 该算法正确处理了单词边界,确保仅完整单词被匹配,有效防止了如 'Apple' 匹配 'Pineapple' 等误报。
- 在关键词替换任务中,FlashText 在相同基准测试下性能最高可比 regex 快 82 倍,且在关键词集合不断增大时表现稳定。
- FlashText 的开源实现使开发人员能够在简历解析、同义词标准化和数据去重等生产环境中,实现高效、可投入使用的关键词处理。
更好的研究,从现在开始
从论文设计到论文写作,大幅缩短您的研究时间。
无需绑定信用卡
本解读由 AI 生成,并经人工编辑审核。