Фильтр токенов скрипта предиката
Удаляет токены, которые не соответствуют предоставленному скрипту предиката. Фильтр поддерживает только скрипты Painless встраиваемого типа. Скрипты оцениваются в контексте предиката анализа.
Пример
Следующий запрос API анализа использует фильтр predicate_token_filter, чтобы выводить только токены, длина которых превышает три символа, из the fox jumps the lazy dog.
resp = client.indices.analyze(
tokenizer="whitespace",
filter=[
{
"type": "predicate_token_filter",
"script": {
"source": "\n token.term.length() > 3\n "
}
}
],
text="the fox jumps the lazy dog",
)
print(resp) response = client.indices.analyze(
body: {
tokenizer: 'whitespace',
filter: [
{
type: 'predicate_token_filter',
script: {
source: "\n token.term.length() > 3\n "
}
}
],
text: 'the fox jumps the lazy dog'
}
)
puts response const response = await client.indices.analyze({
tokenizer: "whitespace",
filter: [
{
type: "predicate_token_filter",
script: {
source: "\n token.term.length() > 3\n ",
},
},
],
text: "the fox jumps the lazy dog",
});
console.log(response); GET /_analyze
{
"tokenizer": "whitespace",
"filter": [
{
"type": "predicate_token_filter",
"script": {
"source": """
token.term.length() > 3
"""
}
}
],
"text": "the fox jumps the lazy dog"
} Фильтр генерирует следующие токены.
[ jumps, lazy ]
Ответ API содержит позицию и смещения каждого выведенного токена. Обратите внимание, что фильтр predicate_token_filter не изменяет исходных позиций или смещений токенов.
Ответ
{
"tokens" : [
{
"token" : "jumps",
"start_offset" : 8,
"end_offset" : 13,
"type" : "word",
"position" : 2
},
{
"token" : "lazy",
"start_offset" : 18,
"end_offset" : 22,
"type" : "word",
"position" : 4
}
]
} Настраиваемые параметры
-
script -
(Обязательно, объект скрипта) Скрипт, содержащий условие, используемое для фильтрации входных токенов. В выходные данные включаются только токены, соответствующие этому скрипту.
Этот параметр поддерживает только встраиваемые скрипты Painless. Скрипт оценивается в контексте предиката анализа.
Настройка и добавление в анализатор
Чтобы настроить фильтр predicate_token_filter, дублируйте его, чтобы создать основу для нового пользовательского фильтра токенов. Вы можете изменить фильтр, используя его настраиваемые параметры.
Следующий запрос API создания индекса настраивает новый пользовательский анализатор с использованием пользовательского фильтра predicate_token_filter, my_script_filter.
Фильтр my_script_filter удаляет токены любого типа, кроме ALPHANUM.
resp = client.indices.create(
index="my-index-000001",
settings={
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "standard",
"filter": [
"my_script_filter"
]
}
},
"filter": {
"my_script_filter": {
"type": "predicate_token_filter",
"script": {
"source": "\n token.type.contains(\"ALPHANUM\")\n "
}
}
}
}
},
)
print(resp) response = client.indices.create(
index: 'my-index-000001',
body: {
settings: {
analysis: {
analyzer: {
my_analyzer: {
tokenizer: 'standard',
filter: [
'my_script_filter'
]
}
},
filter: {
my_script_filter: {
type: 'predicate_token_filter',
script: {
source: "\n token.type.contains(\"ALPHANUM\")\n "
}
}
}
}
}
}
)
puts response const response = await client.indices.create({
index: "my-index-000001",
settings: {
analysis: {
analyzer: {
my_analyzer: {
tokenizer: "standard",
filter: ["my_script_filter"],
},
},
filter: {
my_script_filter: {
type: "predicate_token_filter",
script: {
source:
'\n token.type.contains("ALPHANUM")\n ',
},
},
},
},
},
});
console.log(response); PUT /my-index-000001
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "standard",
"filter": [
"my_script_filter"
]
}
},
"filter": {
"my_script_filter": {
"type": "predicate_token_filter",
"script": {
"source": """
token.type.contains("ALPHANUM")
"""
}
}
}
}
}
}
© 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-predicatefilter-tokenfilter.html