Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›Анализ текста ›Справочник по фильтрам токенов

Фильтр токенов n-грамм

Формирует n-граммы указанной длины из токена.

Например, вы можете использовать фильтр токенов ngram, чтобы изменить fox на [ f, fo, o, ox, x ].

Этот фильтр использует NGramTokenFilter из Lucene.

Фильтр ngram похож на edge_ngram. Однако фильтр edge_ngram выводит только n-граммы, начинающиеся в начале токена.

Пример

Следующий запрос API анализа ngram использует фильтр ngram для преобразования Quick fox в n-граммы длиной в 1 и 2 символа:

resp = client.indices.analyze(
    tokenizer="standard",
    filter=[
        "ngram"
    ],
    text="Quick fox",
)
print(resp)
response = client.indices.analyze(
  body: {
    tokenizer: 'standard',
    filter: [
      'ngram'
    ],
    text: 'Quick fox'
  }
)
puts response
const response = await client.indices.analyze({
  tokenizer: "standard",
  filter: ["ngram"],
  text: "Quick fox",
});
console.log(response);
GET _analyze
{
  "tokenizer": "standard",
  "filter": [ "ngram" ],
  "text": "Quick fox"
}

Фильтр генерирует следующие токены:

[ Q, Qu, u, ui, i, ic, c, ck, k, f, fo, o, ox, x ]

Добавление в анализатор

Следующий запрос API создания индекса ngram использует фильтр ngram для настройки нового пользовательского анализатора.

resp = client.indices.create(
    index="ngram_example",
    settings={
        "analysis": {
            "analyzer": {
                "standard_ngram": {
                    "tokenizer": "standard",
                    "filter": [
                        "ngram"
                    ]
                }
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'ngram_example',
  body: {
    settings: {
      analysis: {
        analyzer: {
          standard_ngram: {
            tokenizer: 'standard',
            filter: [
              'ngram'
            ]
          }
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "ngram_example",
  settings: {
    analysis: {
      analyzer: {
        standard_ngram: {
          tokenizer: "standard",
          filter: ["ngram"],
        },
      },
    },
  },
});
console.log(response);
PUT ngram_example
{
  "settings": {
    "analysis": {
      "analyzer": {
        "standard_ngram": {
          "tokenizer": "standard",
          "filter": [ "ngram" ]
        }
      }
    }
  }
}

Настраиваемые параметры

max_gram
(Необязательно, целое число) Максимальная длина символов в n-грамме. По умолчанию 2.
min_gram
(Необязательно, целое число) Минимальная длина символов в n-грамме. По умолчанию 1.
preserve_original
(Необязательно, логическое значение) Выводить оригинальный токен, если установлено в true. По умолчанию false.

Вы можете использовать параметр уровня индекса index.max_ngram_diff для управления максимальным допустимым различием между значениями max_gram и min_gram.

Настройка

Чтобы настроить фильтр ngram, дублируйте его, чтобы создать основу для нового пользовательского фильтра токенов. Вы можете изменить фильтр, используя его настраиваемые параметры.

Например, следующий запрос создает пользовательский фильтр ngram, который формирует n-граммы от 3 до 5 символов. Запрос также увеличивает значение index.max_ngram_diff до 2.

resp = client.indices.create(
    index="ngram_custom_example",
    settings={
        "index": {
            "max_ngram_diff": 2
        },
        "analysis": {
            "analyzer": {
                "default": {
                    "tokenizer": "whitespace",
                    "filter": [
                        "3_5_grams"
                    ]
                }
            },
            "filter": {
                "3_5_grams": {
                    "type": "ngram",
                    "min_gram": 3,
                    "max_gram": 5
                }
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'ngram_custom_example',
  body: {
    settings: {
      index: {
        max_ngram_diff: 2
      },
      analysis: {
        analyzer: {
          default: {
            tokenizer: 'whitespace',
            filter: [
              '3_5_grams'
            ]
          }
        },
        filter: {
          "3_5_grams": {
            type: 'ngram',
            min_gram: 3,
            max_gram: 5
          }
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "ngram_custom_example",
  settings: {
    index: {
      max_ngram_diff: 2,
    },
    analysis: {
      analyzer: {
        default: {
          tokenizer: "whitespace",
          filter: ["3_5_grams"],
        },
      },
      filter: {
        "3_5_grams": {
          type: "ngram",
          min_gram: 3,
          max_gram: 5,
        },
      },
    },
  },
});
console.log(response);
PUT ngram_custom_example
{
  "settings": {
    "index": {
      "max_ngram_diff": 2
    },
    "analysis": {
      "analyzer": {
        "default": {
          "tokenizer": "whitespace",
          "filter": [ "3_5_grams" ]
        }
      },
      "filter": {
        "3_5_grams": {
          "type": "ngram",
          "min_gram": 3,
          "max_gram": 5
        }
      }
    }
  }
}

© 2023-2025 Elasticsearch
As of September 2024, Elasticsearch is available under a choice of three licenses: the Server Side Public License (SSPL), the Elastic License, or the AGPLv3 (OSI approved).
Elasticsearch and the Elasticsearch logo are trademarks of Elasticsearch B.V., registered in the U.S. and in other countries.
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/analysis-ngram-tokenfilter.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API