API анализа
Выполняет анализ текстовой строки и возвращает получившиеся токены.
resp = client.indices.analyze(
analyzer="standard",
text="Quick Brown Foxes!",
)
print(resp) response = client.indices.analyze(
body: {
analyzer: 'standard',
text: 'Quick Brown Foxes!'
}
)
puts response const response = await client.indices.analyze({
analyzer: "standard",
text: "Quick Brown Foxes!",
});
console.log(response); GET /_analyze
{
"analyzer" : "standard",
"text" : "Quick Brown Foxes!"
} Запрос
GET /_analyze
POST /_analyze
GET /<index>/_analyze
POST /<index>/_analyze
Предварительные условия
- Если включены функции безопасности Elasticsearch, у вас должна быть
manageправо доступа к индексу для указанного индекса.
Параметры пути
-
<index> -
(Необязательно, строка) Индекс, используемый для получения анализатора.
Если указан, этот параметр
analyzerили<field>переопределяет это значение.Если анализатор или поле не указаны, API анализа использует по умолчанию анализатор для индекса.
Если индекс не указан или индекс не имеет анализатора по умолчанию, API анализа использует стандартный анализатор.
Параметры запроса
-
analyzer -
(Необязательно, строка) Имя анализатора, который должен быть применён к предоставленной
text. Это может быть встроенный анализатор, или анализатор, настроенный в индексе.Если этот параметр не указан, API анализа использует анализатор, определённый в маппинге поля.
Если поле не указано, API анализа использует анализатор по умолчанию для индекса.
Если индекс не указан или индекс не имеет анализатора по умолчанию, API анализа использует стандартный анализатор.
-
attributes - (Необязательно, массив строк) Массив атрибутов токенов, используемых для фильтрации выходных данных параметра
explain. -
char_filter - (Необязательно, массив строк) Массив фильтров символов, используемых для предварительной обработки символов перед токенизацией. См. Справочник по фильтрам символов для списка фильтров символов.
-
explain - (Необязательно, булево) Если
true, в ответ включаются атрибуты токенов и дополнительные сведения. По умолчаниюfalse. [preview] Формат дополнительной информации помечен как экспериментальный в Lucene, и он может быть изменён в будущем. -
field -
(Необязательно, строка) Поле, используемое для получения анализатора. Для использования этого параметра необходимо указать индекс.
Если указан, параметр
analyzerпереопределяет это значение.Если поле не указано, API анализа использует анализатор по умолчанию для индекса.
Если индекс не указан или индекс не имеет анализатора по умолчанию, API анализа использует стандартный анализатор.
-
filter - (Необязательно, массив строк) Массив фильтров токенов, используемых после токенизатора. См. Справочник по фильтрам токенов для списка фильтров токенов.
-
normalizer - (Необязательно, строка) Нормализующий элемент, используемый для преобразования текста в один токен. См. Нормализующие элементы для списка нормализующих элементов.
-
text - (Обязательно, строка или массив строк) Текст для анализа. Если указан массив строк, он анализируется как поле с несколькими значениями.
-
tokenizer - (Необязательно, строка) Токенизатор, используемый для преобразования текста в токены. См. Справочник по токенизаторам для списка токенизаторов.
Примеры
Не указан индекс
Вы можете применить любой из встроенных анализаторов к строке текста без указания индекса.
resp = client.indices.analyze(
analyzer="standard",
text="this is a test",
)
print(resp) response = client.indices.analyze(
body: {
analyzer: 'standard',
text: 'this is a test'
}
)
puts response const response = await client.indices.analyze({
analyzer: "standard",
text: "this is a test",
});
console.log(response); GET /_analyze
{
"analyzer" : "standard",
"text" : "this is a test"
} Массив строк текста
Если параметр text задан как массив строк, он анализируется как поле с несколькими значениями.
resp = client.indices.analyze(
analyzer="standard",
text=[
"this is a test",
"the second text"
],
)
print(resp) response = client.indices.analyze(
body: {
analyzer: 'standard',
text: [
'this is a test',
'the second text'
]
}
)
puts response const response = await client.indices.analyze({
analyzer: "standard",
text: ["this is a test", "the second text"],
});
console.log(response); GET /_analyze
{
"analyzer" : "standard",
"text" : ["this is a test", "the second text"]
} Пользовательский анализатор
Вы можете использовать API анализа для тестирования пользовательского временного анализатора, созданного из токенизаторов, токенизирующих фильтров и фильтров символов. Токенизирующие фильтры используют параметр filter:
resp = client.indices.analyze(
tokenizer="keyword",
filter=[
"lowercase"
],
text="this is a test",
)
print(resp) response = client.indices.analyze(
body: {
tokenizer: 'keyword',
filter: [
'lowercase'
],
text: 'this is a test'
}
)
puts response const response = await client.indices.analyze({
tokenizer: "keyword",
filter: ["lowercase"],
text: "this is a test",
});
console.log(response); GET /_analyze
{
"tokenizer" : "keyword",
"filter" : ["lowercase"],
"text" : "this is a test"
} resp = client.indices.analyze(
tokenizer="keyword",
filter=[
"lowercase"
],
char_filter=[
"html_strip"
],
text="this is a test</b>",
)
print(resp) response = client.indices.analyze(
body: {
tokenizer: 'keyword',
filter: [
'lowercase'
],
char_filter: [
'html_strip'
],
text: 'this is a test</b>'
}
)
puts response const response = await client.indices.analyze({
tokenizer: "keyword",
filter: ["lowercase"],
char_filter: ["html_strip"],
text: "this is a test</b>",
});
console.log(response); GET /_analyze
{
"tokenizer" : "keyword",
"filter" : ["lowercase"],
"char_filter" : ["html_strip"],
"text" : "this is a <b>test</b>"
} Пользовательские токенизаторы, токенизирующие фильтры и фильтры символов могут быть указаны в теле запроса следующим образом:
resp = client.indices.analyze(
tokenizer="whitespace",
filter=[
"lowercase",
{
"type": "stop",
"stopwords": [
"a",
"is",
"this"
]
}
],
text="this is a test",
)
print(resp) response = client.indices.analyze(
body: {
tokenizer: 'whitespace',
filter: [
'lowercase',
{
type: 'stop',
stopwords: [
'a',
'is',
'this'
]
}
],
text: 'this is a test'
}
)
puts response const response = await client.indices.analyze({
tokenizer: "whitespace",
filter: [
"lowercase",
{
type: "stop",
stopwords: ["a", "is", "this"],
},
],
text: "this is a test",
});
console.log(response); GET /_analyze
{
"tokenizer" : "whitespace",
"filter" : ["lowercase", {"type": "stop", "stopwords": ["a", "is", "this"]}],
"text" : "this is a test"
} Конкретный индекс
Вы также можете запустить API анализа для конкретного индекса:
resp = client.indices.analyze(
index="analyze_sample",
text="this is a test",
)
print(resp) response = client.indices.analyze(
index: 'analyze_sample',
body: {
text: 'this is a test'
}
)
puts response const response = await client.indices.analyze({
index: "analyze_sample",
text: "this is a test",
});
console.log(response); GET /analyze_sample/_analyze
{
"text" : "this is a test"
} Вышеприведенное выполнит анализ текста «this is a test», используя анализатор по умолчанию, связанный с индексом analyze_sample. Также можно указать analyzer для использования другого анализатора:
resp = client.indices.analyze(
index="analyze_sample",
analyzer="whitespace",
text="this is a test",
)
print(resp) response = client.indices.analyze(
index: 'analyze_sample',
body: {
analyzer: 'whitespace',
text: 'this is a test'
}
)
puts response const response = await client.indices.analyze({
index: "analyze_sample",
analyzer: "whitespace",
text: "this is a test",
});
console.log(response); GET /analyze_sample/_analyze
{
"analyzer" : "whitespace",
"text" : "this is a test"
} Получение анализатора из сопоставления полей
Анализатор можно получить на основе сопоставления полей, например:
resp = client.indices.analyze(
index="analyze_sample",
field="obj1.field1",
text="this is a test",
)
print(resp) response = client.indices.analyze(
index: 'analyze_sample',
body: {
field: 'obj1.field1',
text: 'this is a test'
}
)
puts response const response = await client.indices.analyze({
index: "analyze_sample",
field: "obj1.field1",
text: "this is a test",
});
console.log(response); GET /analyze_sample/_analyze
{
"field" : "obj1.field1",
"text" : "this is a test"
} Это приведет к тому, что анализ будет выполняться на основе анализатора, настроенного в сопоставлении для obj1.field1 (или, если он не задан, по умолчанию для индекса).
Нормализация
Для поля ключевых слов может быть предоставлен normalizer с нормализатором, связанным с индексом analyze_sample.
resp = client.indices.analyze(
index="analyze_sample",
normalizer="my_normalizer",
text="BaR",
)
print(resp) response = client.indices.analyze(
index: 'analyze_sample',
body: {
normalizer: 'my_normalizer',
text: 'BaR'
}
)
puts response const response = await client.indices.analyze({
index: "analyze_sample",
normalizer: "my_normalizer",
text: "BaR",
});
console.log(response); GET /analyze_sample/_analyze
{
"normalizer" : "my_normalizer",
"text" : "BaR"
} Или, создав пользовательский временный нормализатор из токенизирующих фильтров и фильтров символов.
resp = client.indices.analyze(
filter=[
"lowercase"
],
text="BaR",
)
print(resp) response = client.indices.analyze(
body: {
filter: [
'lowercase'
],
text: 'BaR'
}
)
puts response const response = await client.indices.analyze({
filter: ["lowercase"],
text: "BaR",
});
console.log(response); GET /_analyze
{
"filter" : ["lowercase"],
"text" : "BaR"
} Объяснение анализа
Если вам нужны более подробные сведения, установите explain на true (по умолчанию false). Это выведет все атрибуты токена для каждого токена. Вы можете отфильтровать атрибуты токенов, которые хотите вывести, установив опцию attributes.
Формат дополнительной информации по анализу обозначен как экспериментальный в Lucene и может измениться в будущем.
resp = client.indices.analyze(
tokenizer="standard",
filter=[
"snowball"
],
text="detailed output",
explain=True,
attributes=[
"keyword"
],
)
print(resp) response = client.indices.analyze(
body: {
tokenizer: 'standard',
filter: [
'snowball'
],
text: 'detailed output',
explain: true,
attributes: [
'keyword'
]
}
)
puts response const response = await client.indices.analyze({
tokenizer: "standard",
filter: ["snowball"],
text: "detailed output",
explain: true,
attributes: ["keyword"],
});
console.log(response); GET /_analyze
{
"tokenizer" : "standard",
"filter" : ["snowball"],
"text" : "detailed output",
"explain" : true,
"attributes" : ["keyword"]
} | Установите «keyword», чтобы вывести только атрибут «keyword» |
Запрос возвращает следующий результат:
{
"detail" : {
"custom_analyzer" : true,
"charfilters" : [ ],
"tokenizer" : {
"name" : "standard",
"tokens" : [ {
"token" : "detailed",
"start_offset" : 0,
"end_offset" : 8,
"type" : "<ALPHANUM>",
"position" : 0
}, {
"token" : "output",
"start_offset" : 9,
"end_offset" : 15,
"type" : "<ALPHANUM>",
"position" : 1
} ]
},
"tokenfilters" : [ {
"name" : "snowball",
"tokens" : [ {
"token" : "detail",
"start_offset" : 0,
"end_offset" : 8,
"type" : "<ALPHANUM>",
"position" : 0,
"keyword" : false
}, {
"token" : "output",
"start_offset" : 9,
"end_offset" : 15,
"type" : "<ALPHANUM>",
"position" : 1,
"keyword" : false
} ]
} ]
}
} | Выводятся только атрибуты «keyword», так как в запросе указано «attributes». |
Установка лимита на количество токенов
Генерация чрезмерного количества токенов может привести к тому, что у узла закончится оперативная память. Следующее значение позволяет ограничить количество создаваемых токенов:
-
index.analyze.max_token_count - Максимальное количество токенов, которое может быть создано с помощью API
_analyze. Значение по умолчанию —10000. Если создано больше токенов, чем этот предел, будет выброшено исключение. Конечная точка_analyzeбез указанного индекса всегда использует значение10000в качестве предела. Это значение позволяет контролировать предел для конкретного индекса:
resp = client.indices.create(
index="analyze_sample",
settings={
"index.analyze.max_token_count": 20000
},
)
print(resp) response = client.indices.create(
index: 'analyze_sample',
body: {
settings: {
'index.analyze.max_token_count' => 20_000
}
}
)
puts response const response = await client.indices.create({
index: "analyze_sample",
settings: {
"index.analyze.max_token_count": 20000,
},
});
console.log(response); PUT /analyze_sample
{
"settings" : {
"index.analyze.max_token_count" : 20000
}
} resp = client.indices.analyze(
index="analyze_sample",
text="this is a test",
)
print(resp) response = client.indices.analyze(
index: 'analyze_sample',
body: {
text: 'this is a test'
}
)
puts response const response = await client.indices.analyze({
index: "analyze_sample",
text: "this is a test",
});
console.log(response); GET /analyze_sample/_analyze
{
"text" : "this is a test"
}
© 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/indices-analyze.html