HTML 剥离字符过滤器
html_strip
字符过滤器从输入文本中移除 HTML 标签,例如 <div>
、<p>
和 <a>
,并将其转换为纯文本。该过滤器可以配置为保留某些标签,或将特定的 HTML 实体(例如
)解码为空格。
示例
以下请求将 html_strip
字符过滤器应用于提供的文本
GET /_analyze
{
"tokenizer": "keyword",
"char_filter": [
"html_strip"
],
"text": "<p>Commonly used calculus symbols include α, β and θ </p>"
}
响应中包含已将 HTML 字符转换为其解码值的词元
{
"tokens": [
{
"token": """
Commonly used calculus symbols include α, β and θ
""",
"start_offset": 0,
"end_offset": 74,
"type": "word",
"position": 0
}
]
}
参数
html_strip
字符过滤器可以使用以下参数进行配置。
参数 | 必需/可选 | 数据类型 | 描述 |
---|---|---|---|
escaped_tags | 可选 | 字符串数组 | 一个 HTML 元素名称数组,不带尖括号(< > )指定。当从文本中剥离 HTML 时,过滤器不会移除此列表中的元素。例如,将数组设置为 ["b", "i"] 将阻止 <b> 和 <i> 元素被剥离。 |
示例:带有小写过滤器的自定义分析器
以下示例请求创建一个自定义分析器,该分析器使用 html_strip
分析器和 lowercase
过滤器剥离 HTML 标签并将纯文本转换为小写
PUT /html_strip_and_lowercase_analyzer
{
"settings": {
"analysis": {
"char_filter": {
"html_filter": {
"type": "html_strip"
}
},
"analyzer": {
"html_strip_analyzer": {
"type": "custom",
"char_filter": ["html_filter"],
"tokenizer": "standard",
"filter": ["lowercase"]
}
}
}
}
}
使用以下请求检查使用该分析器生成的词元
GET /html_strip_and_lowercase_analyzer/_analyze
{
"analyzer": "html_strip_analyzer",
"text": "<h1>Welcome to <strong>OpenSearch</strong>!</h1>"
}
在响应中,HTML 标签已被移除,纯文本已转换为小写
{
"tokens": [
{
"token": "welcome",
"start_offset": 4,
"end_offset": 11,
"type": "<ALPHANUM>",
"position": 0
},
{
"token": "to",
"start_offset": 12,
"end_offset": 14,
"type": "<ALPHANUM>",
"position": 1
},
{
"token": "opensearch",
"start_offset": 23,
"end_offset": 42,
"type": "<ALPHANUM>",
"position": 2
}
]
}
示例:保留 HTML 标签的自定义分析器
以下示例请求创建一个保留 HTML 标签的自定义分析器
PUT /html_strip_preserve_analyzer
{
"settings": {
"analysis": {
"char_filter": {
"html_filter": {
"type": "html_strip",
"escaped_tags": ["b", "i"]
}
},
"analyzer": {
"html_strip_analyzer": {
"type": "custom",
"char_filter": ["html_filter"],
"tokenizer": "keyword"
}
}
}
}
}
使用以下请求检查使用该分析器生成的词元
GET /html_strip_preserve_analyzer/_analyze
{
"analyzer": "html_strip_analyzer",
"text": "<p>This is a <b>bold</b> and <i>italic</i> text.</p>"
}
在响应中,italic
和 bold
标签已按自定义分析器请求中的指定保留。
{
"tokens": [
{
"token": """
This is a <b>bold</b> and <i>italic</i> text.
""",
"start_offset": 0,
"end_offset": 52,
"type": "word",
"position": 0
}
]
}