Pattern Capture Token Filter(模式匹配词元过滤器)

原文链接 :https://www.elastic.co/guide/en/elasticsearch/reference/5.4/analysis-pattern-capture-tokenfilter.html

译文链接 : http://www.apache.wiki/pages/viewpage.action?pageId=10028023

贡献者 : 李亚运ApacheCNApache中文网

简述

pattern_capture词元过滤器与pattern 分词器不同,为正则表达式中的每个捕获组发出一个token。

模式不会锚定到字符串的开始和结尾,每个模式可以匹配多次,并且允许重复匹配。

小心病态正则表达式 模式捕获令牌过滤器使用Java正则表达式 。 一个严重的正则表达式可能会运行得非常慢,甚至会抛出一个StackOverflowError,并导致其运行的节点突然退出。 阅读更多关于病态正则表达式和如何避免它们

示例-1

举例如下:

正则:

  1. "(([a-z]+)(\d*))"

待匹配文字:

  1. "abc123def456"

匹配结果:

  1. [ abc123, abc, 123, def456, def, 456 ]

如果preserve_original设置为true (默认值),那么它也会发出原始令牌: abc123def456

这对于索引文本(如驼峰式代码)特别有用,例如stripHTML ,用户可以在其中搜索"strip html""striphtml"

  1. PUT test
  2. {
  3. "settings" : {
  4. "analysis" : {
  5. "filter" : {
  6. "code" : {
  7. "type" : "pattern_capture",
  8. "preserve_original" : true,
  9. "patterns" : [
  10. "(\\p{Ll}+|\\p{Lu}\\p{Ll}+|\\p{Lu}+)",
  11. "(\\d+)"
  12. ]
  13. }
  14. },
  15. "analyzer" : {
  16. "code" : {
  17. "tokenizer" : "pattern",
  18. "filter" : [ "code", "lowercase" ]
  19. }
  20. }
  21. }
  22. }
  23. }

当处理如下文本内容时:

  1. import static org.apache.commons.lang.StringEscapeUtils.escapeHtml

结果如下:

  1. [ import, static, org, apache, commons, lang, stringescapeutils, string, escape, utils, escapehtml, escape, html ]

示例-2

别一个例子就是分析邮箱时,如下所示:

  1. PUT test
  2. {
  3. "settings" : {
  4. "analysis" : {
  5. "filter" : {
  6. "email" : {
  7. "type" : "pattern_capture",
  8. "preserve_original" : true,
  9. "patterns" : [
  10. "([^@]+)",
  11. "(\\p{L}+)",
  12. "(\\d+)",
  13. "@(.+)"
  14. ]
  15. }
  16. },
  17. "analyzer" : {
  18. "email" : {
  19. "tokenizer" : "uax_url_email",
  20. "filter" : [ "email", "lowercase", "unique" ]
  21. }
  22. }
  23. }
  24. }
  25. }

当邮箱格式如下时:

  1. john-smith_123@foo-bar.com

最终处理结果将为:

  1. john-smith_123@foo-bar.com, john-smith_123,
  2. john, smith, 123, foo-bar.com, foo, bar, com

需要多种模式以允许重复捕获,但也意味着模式不复杂和易于理解。

注意:所有token都以相同的位置处理,并且具有相同的字符偏移量,因此当与突出显示相结合时,整个原始token将被突出显示,而不仅仅是匹配的子集

例如,查询上述电子邮件地址"smith",将会突出显示整个原始token:

  1. <em>john-smith_123@foo-bar.com</em>

而非仅高亮smith:

  1. john-<em>smith</em>_123@foo-bar.com