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

Фильтр токенов Limit token count

Ограничивает количество выходных токенов. Фильтр limit обычно используется для ограничения размера значений полей документов на основе количества токенов.

По умолчанию фильтр limit сохраняет только первый токен в потоке. Например, фильтр может изменить поток токенов [ one, two, three ] на [ one ].

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

 If you want to limit the size of field values based on
_character length_, use the <<ignore-above,`ignore_above`>> mapping parameter.

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

max_token_count
(Необязательно, целое число) Максимальное количество токенов для сохранения. После достижения этого предела любые оставшиеся токены исключаются из вывода. По умолчанию 1.
consume_all_tokens
(Необязательно, логическое значение) Если true, фильтр limit обрабатывает весь поток токенов, даже если предел max_token_count уже достигнут. По умолчанию false.

Пример

Следующий запрос API анализа использует фильтр limit для сохранения только первых двух токенов в quick fox jumps over lazy dog:

resp = client.indices.analyze(
    tokenizer="standard",
    filter=[
        {
            "type": "limit",
            "max_token_count": 2
        }
    ],
    text="quick fox jumps over lazy dog",
)
print(resp)
response = client.indices.analyze(
  body: {
    tokenizer: 'standard',
    filter: [
      {
        type: 'limit',
        max_token_count: 2
      }
    ],
    text: 'quick fox jumps over lazy dog'
  }
)
puts response
const response = await client.indices.analyze({
  tokenizer: "standard",
  filter: [
    {
      type: "limit",
      max_token_count: 2,
    },
  ],
  text: "quick fox jumps over lazy dog",
});
console.log(response);
GET _analyze
{
  "tokenizer": "standard",
    "filter": [
    {
      "type": "limit",
      "max_token_count": 2
    }
  ],
  "text": "quick fox jumps over lazy dog"
}

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

[ quick, fox ]

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

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

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

Настройка

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

Например, следующий запрос создает пользовательский фильтр limit, который сохраняет только первые пять токенов из потока:

resp = client.indices.create(
    index="custom_limit_example",
    settings={
        "analysis": {
            "analyzer": {
                "whitespace_five_token_limit": {
                    "tokenizer": "whitespace",
                    "filter": [
                        "five_token_limit"
                    ]
                }
            },
            "filter": {
                "five_token_limit": {
                    "type": "limit",
                    "max_token_count": 5
                }
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'custom_limit_example',
  body: {
    settings: {
      analysis: {
        analyzer: {
          whitespace_five_token_limit: {
            tokenizer: 'whitespace',
            filter: [
              'five_token_limit'
            ]
          }
        },
        filter: {
          five_token_limit: {
            type: 'limit',
            max_token_count: 5
          }
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "custom_limit_example",
  settings: {
    analysis: {
      analyzer: {
        whitespace_five_token_limit: {
          tokenizer: "whitespace",
          filter: ["five_token_limit"],
        },
      },
      filter: {
        five_token_limit: {
          type: "limit",
          max_token_count: 5,
        },
      },
    },
  },
});
console.log(response);
PUT custom_limit_example
{
  "settings": {
    "analysis": {
      "analyzer": {
        "whitespace_five_token_limit": {
          "tokenizer": "whitespace",
          "filter": [ "five_token_limit" ]
        }
      },
      "filter": {
        "five_token_limit": {
          "type": "limit",
          "max_token_count": 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-limit-token-count-tokenfilter.html

Spec-Zone.ru

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