Фильтр токенов с условиями
Применяет набор фильтров токенов к токенам, которые соответствуют условиям в предоставленном скрипте-предикате.
Этот фильтр использует ConditionalTokenFilter из Lucene.
Пример
Следующий запрос API анализа использует фильтр condition для сопоставления токенов с длиной менее 5 символов в THE QUICK BROWN FOX. Затем к этим сопоставленным токенам применяется фильтр lowercase, преобразующий их в нижний регистр.
resp = client.indices.analyze(
tokenizer="standard",
filter=[
{
"type": "condition",
"filter": [
"lowercase"
],
"script": {
"source": "token.getTerm().length() < 5"
}
}
],
text="THE QUICK BROWN FOX",
)
print(resp) response = client.indices.analyze(
body: {
tokenizer: 'standard',
filter: [
{
type: 'condition',
filter: [
'lowercase'
],
script: {
source: 'token.getTerm().length() < 5'
}
}
],
text: 'THE QUICK BROWN FOX'
}
)
puts response const response = await client.indices.analyze({
tokenizer: "standard",
filter: [
{
type: "condition",
filter: ["lowercase"],
script: {
source: "token.getTerm().length() < 5",
},
},
],
text: "THE QUICK BROWN FOX",
});
console.log(response); GET /_analyze
{
"tokenizer": "standard",
"filter": [
{
"type": "condition",
"filter": [ "lowercase" ],
"script": {
"source": "token.getTerm().length() < 5"
}
}
],
"text": "THE QUICK BROWN FOX"
} Фильтр создаёт следующие токены:
[ the, QUICK, BROWN, fox ]
Настраиваемые параметры
-
filter -
(Обязательный, массив фильтров токенов) Массив фильтров токенов. Если токен соответствует скрипту-предикату в параметре
script, эти фильтры применяются к токену в указанном порядке.Эти фильтры могут включать пользовательские фильтры токенов, определённые в отображении индекса.
-
script -
(Обязательный, объект скрипта) Скрипт-предикат, используемый для применения фильтров токенов. Если токен соответствует этому скрипту, фильтры в параметре
filterприменяются к токену.Для допустимых параметров см. Написание скриптов. Поддерживаются только встроенные скрипты. Скрипты Painless выполняются в контексте предиката анализа и требуют свойство
token.
Настройка и добавление в анализатор
Чтобы настроить фильтр condition, дублируйте его, чтобы создать основу для нового пользовательского фильтра токенов. Вы можете изменить фильтр, используя его настраиваемые параметры.
Например, следующий запрос API создания индекса использует пользовательский фильтр condition для настройки нового пользовательского анализатора. Пользовательский фильтр condition сопоставляет первый токен в потоке. Затем он инвертирует этот сопоставленный токен, используя фильтр reverse.
resp = client.indices.create(
index="palindrome_list",
settings={
"analysis": {
"analyzer": {
"whitespace_reverse_first_token": {
"tokenizer": "whitespace",
"filter": [
"reverse_first_token"
]
}
},
"filter": {
"reverse_first_token": {
"type": "condition",
"filter": [
"reverse"
],
"script": {
"source": "token.getPosition() === 0"
}
}
}
}
},
)
print(resp) response = client.indices.create(
index: 'palindrome_list',
body: {
settings: {
analysis: {
analyzer: {
whitespace_reverse_first_token: {
tokenizer: 'whitespace',
filter: [
'reverse_first_token'
]
}
},
filter: {
reverse_first_token: {
type: 'condition',
filter: [
'reverse'
],
script: {
source: 'token.getPosition() === 0'
}
}
}
}
}
}
)
puts response const response = await client.indices.create({
index: "palindrome_list",
settings: {
analysis: {
analyzer: {
whitespace_reverse_first_token: {
tokenizer: "whitespace",
filter: ["reverse_first_token"],
},
},
filter: {
reverse_first_token: {
type: "condition",
filter: ["reverse"],
script: {
source: "token.getPosition() === 0",
},
},
},
},
},
});
console.log(response); PUT /palindrome_list
{
"settings": {
"analysis": {
"analyzer": {
"whitespace_reverse_first_token": {
"tokenizer": "whitespace",
"filter": [ "reverse_first_token" ]
}
},
"filter": {
"reverse_first_token": {
"type": "condition",
"filter": [ "reverse" ],
"script": {
"source": "token.getPosition() === 0"
}
}
}
}
}
}
© 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-condition-tokenfilter.html