Pattern replace token filter

Uses a regular expression to match and replace token substrings.

The pattern_replace filter uses Java’s regular expression syntax. By default, the filter replaces matching substrings with an empty substring ("").

Regular expressions cannot be anchored to the beginning or end of a token. Replacement substrings can use Java’s $g syntax to reference capture groups from the original token text.

A poorly-written regular expression may run slowly or return a StackOverflowError, causing the node running the expression to exit suddenly.

Read more about pathological regular expressions and how to avoid them.

This filter uses Lucene’s PatternReplaceFilter.

Example

The following analyze API request uses the pattern_replace filter to prepend watch to the substring dog in foxes jump lazy dogs.

  1. GET /_analyze
  2. {
  3. "tokenizer": "whitespace",
  4. "filter": [
  5. {
  6. "type": "pattern_replace",
  7. "pattern": "(dog)",
  8. "replacement": "watch$1"
  9. }
  10. ],
  11. "text": "foxes jump lazy dogs"
  12. }

The filter produces the following tokens.

  1. [ foxes, jump, lazy, watchdogs ]

Configurable parameters

all

(Optional, boolean) If true, all substrings matching the pattern parameter’s regular expression are replaced. If false, the filter replaces only the first matching substring in each token. Defaults to true.

pattern

(Required, string) Regular expression, written in Java’s regular expression syntax. The filter replaces token substrings matching this pattern with the substring in the replacement parameter.

replacement

(Optional, string) Replacement substring. Defaults to an empty substring ("").

Customize and add to an analyzer

To customize the pattern_replace filter, duplicate it to create the basis for a new custom token filter. You can modify the filter using its configurable parameters.

The following create index API request configures a new custom analyzer using a custom pattern_replace filter, my_pattern_replace_filter.

The my_pattern_replace_filter filter uses the regular expression [£|€] to match and remove the currency symbols £ and . The filter’s all parameter is false, meaning only the first matching symbol in each token is removed.

  1. PUT /my-index-000001
  2. {
  3. "settings": {
  4. "analysis": {
  5. "analyzer": {
  6. "my_analyzer": {
  7. "tokenizer": "keyword",
  8. "filter": [
  9. "my_pattern_replace_filter"
  10. ]
  11. }
  12. },
  13. "filter": {
  14. "my_pattern_replace_filter": {
  15. "type": "pattern_replace",
  16. "pattern": "[£|€]",
  17. "replacement": "",
  18. "all": false
  19. }
  20. }
  21. }
  22. }
  23. }