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

Фильтр токенов Common Grams

Генерирует биграммы для заданного набора общих слов.

Например, вы можете указать is и the как общие слова. Этот фильтр затем преобразует токены [the, quick, fox, is, brown] в [the, the_quick, quick, fox, fox_is, is, is_brown, brown].

Вы можете использовать фильтр common_grams вместо фильтра стоп-токенов, когда вы не хотите полностью игнорировать общие слова.

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

Пример

Следующий запрос API анализа создаёт биграммы для is и the:

resp = client.indices.analyze(
    tokenizer="whitespace",
    filter=[
        {
            "type": "common_grams",
            "common_words": [
                "is",
                "the"
            ]
        }
    ],
    text="the quick fox is brown",
)
print(resp)
response = client.indices.analyze(
  body: {
    tokenizer: 'whitespace',
    filter: [
      {
        type: 'common_grams',
        common_words: [
          'is',
          'the'
        ]
      }
    ],
    text: 'the quick fox is brown'
  }
)
puts response
const response = await client.indices.analyze({
  tokenizer: "whitespace",
  filter: [
    {
      type: "common_grams",
      common_words: ["is", "the"],
    },
  ],
  text: "the quick fox is brown",
});
console.log(response);
GET /_analyze
{
  "tokenizer" : "whitespace",
  "filter" : [
    {
      "type": "common_grams",
      "common_words": ["is", "the"]
    }
  ],
  "text" : "the quick fox is brown"
}

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

[ the, the_quick, quick, fox, fox_is, is, is_brown, brown ]

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

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

resp = client.indices.create(
    index="common_grams_example",
    settings={
        "analysis": {
            "analyzer": {
                "index_grams": {
                    "tokenizer": "whitespace",
                    "filter": [
                        "common_grams"
                    ]
                }
            },
            "filter": {
                "common_grams": {
                    "type": "common_grams",
                    "common_words": [
                        "a",
                        "is",
                        "the"
                    ]
                }
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'common_grams_example',
  body: {
    settings: {
      analysis: {
        analyzer: {
          index_grams: {
            tokenizer: 'whitespace',
            filter: [
              'common_grams'
            ]
          }
        },
        filter: {
          common_grams: {
            type: 'common_grams',
            common_words: [
              'a',
              'is',
              'the'
            ]
          }
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "common_grams_example",
  settings: {
    analysis: {
      analyzer: {
        index_grams: {
          tokenizer: "whitespace",
          filter: ["common_grams"],
        },
      },
      filter: {
        common_grams: {
          type: "common_grams",
          common_words: ["a", "is", "the"],
        },
      },
    },
  },
});
console.log(response);
PUT /common_grams_example
{
  "settings": {
    "analysis": {
      "analyzer": {
        "index_grams": {
          "tokenizer": "whitespace",
          "filter": [ "common_grams" ]
        }
      },
      "filter": {
        "common_grams": {
          "type": "common_grams",
          "common_words": [ "a", "is", "the" ]
        }
      }
    }
  }
}

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

common_words

(Обязательно*, массив строк) Список токенов. Фильтр генерирует биграммы для этих токенов.

Требуется либо этот, либо параметр common_words_path.

common_words_path

(Обязательно*, строка) Путь к файлу, содержащему список токенов. Фильтр генерирует биграммы для этих токенов.

Этот путь должен быть абсолютным или относительным к расположению config. Файл должен быть закодирован в UTF-8. Каждый токен в файле должен быть разделен переводом строки.

Требуется либо этот, либо параметр common_words.

ignore_case
(Необязательно, Булево) Если true, соответствия общим словам игнорируют регистр. По умолчанию false.
query_mode

(Необязательно, Булево) Если true, фильтр исключает следующие токены из вывода:

  • Однограммы для общих слов
  • Однограммы для терминов, за которыми следуют общие слова

По умолчанию false. Рекомендуется включить этот параметр для анализаторов поиска.

Например, вы можете включить этот параметр и указать is и the в качестве общих слов. Этот фильтр преобразует токены [the, quick, fox, is, brown] в [the_quick, quick, fox_is, is_brown,].

Настройка

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

Например, следующий запрос создаёт пользовательский фильтр common_grams с ignore_case и query_mode, установленным на true:

resp = client.indices.create(
    index="common_grams_example",
    settings={
        "analysis": {
            "analyzer": {
                "index_grams": {
                    "tokenizer": "whitespace",
                    "filter": [
                        "common_grams_query"
                    ]
                }
            },
            "filter": {
                "common_grams_query": {
                    "type": "common_grams",
                    "common_words": [
                        "a",
                        "is",
                        "the"
                    ],
                    "ignore_case": True,
                    "query_mode": True
                }
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'common_grams_example',
  body: {
    settings: {
      analysis: {
        analyzer: {
          index_grams: {
            tokenizer: 'whitespace',
            filter: [
              'common_grams_query'
            ]
          }
        },
        filter: {
          common_grams_query: {
            type: 'common_grams',
            common_words: [
              'a',
              'is',
              'the'
            ],
            ignore_case: true,
            query_mode: true
          }
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "common_grams_example",
  settings: {
    analysis: {
      analyzer: {
        index_grams: {
          tokenizer: "whitespace",
          filter: ["common_grams_query"],
        },
      },
      filter: {
        common_grams_query: {
          type: "common_grams",
          common_words: ["a", "is", "the"],
          ignore_case: true,
          query_mode: true,
        },
      },
    },
  },
});
console.log(response);
PUT /common_grams_example
{
  "settings": {
    "analysis": {
      "analyzer": {
        "index_grams": {
          "tokenizer": "whitespace",
          "filter": [ "common_grams_query" ]
        }
      },
      "filter": {
        "common_grams_query": {
          "type": "common_grams",
          "common_words": [ "a", "is", "the" ],
          "ignore_case": true,
          "query_mode": true
        }
      }
    }
  }
}

© 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-common-grams-tokenfilter.html

Spec-Zone.ru

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