使用同义词搜索
edit使用同义词搜索
edit同义词是具有相同或相似意义的单词或短语。 它们是搜索的重要方面,因为它们可以改善搜索体验并扩大搜索结果的范围。
同义词允许您:
- 提高搜索相关性通过查找使用不同术语表达相同概念的相关文档。
- 使特定领域的词汇更加用户友好,允许用户使用他们更熟悉的搜索词。
- 定义常见的拼写错误和打字错误以透明地处理常见错误。
同义词通过同义词集进行分组。 您可以根据需要拥有任意数量的同义词集。
为了在 Elasticsearch 中使用同义词集,您需要:
存储您的同义词集
edit您的同义词集需要存储在 Elasticsearch 中,以便您的分析器可以引用它们。 有三种方法可以存储您的同义词集:
同义词 API
edit您可以使用同义词API来管理同义词集。 这是最灵活的方法,因为它允许动态定义和修改同义词集。
您的同义词集的更改将自动重新加载关联的分析器。
同义词文件
edit您可以将同义词集存储在一个文件中。
同义词集文件需要上传到所有集群节点,并位于Elasticsearch分发的配置目录中。 如果您使用的是Elasticsearch服务,您可以使用自定义捆绑包上传同义词文件。
一个同义词文件示例:
# Blank lines and lines starting with pound are comments. # Explicit mappings match any token sequence on the left hand side of "=>" # and replace with all alternatives on the right hand side. # These types of mappings ignore the expand parameter in the schema. # Examples: i-pod, i pod => ipod sea biscuit, sea biscit => seabiscuit # Equivalent synonyms may be separated with commas and give # no explicit mapping. In this case the mapping behavior will # be taken from the expand parameter in the token filter configuration. # This allows the same synonym file to be used in different synonym handling strategies. # Examples: ipod, i-pod, i pod foozball , foosball universe , cosmos lol, laughing out loud # If expand==true in the synonym token filter configuration, # "ipod, i-pod, i pod" is equivalent to the explicit mapping: ipod, i-pod, i pod => ipod, i-pod, i pod # If expand==false, "ipod, i-pod, i pod" is equivalent # to the explicit mapping: ipod, i-pod, i pod => ipod # Multiple synonym mapping entries are merged. foo => foo bar foo => baz # is equivalent to foo => foo bar, baz
要更新现有的同义词集,请将新文件上传到您的集群。 同义词集文件必须在每个集群节点上保持同步。
当同义词集更新时,使用它的搜索分析器需要使用reload search analyzers API进行刷新
这种手动同步和重新加载使得这种方法不如使用同义词API灵活。
内联
edit您可以通过在您的词元过滤器定义中直接内联添加同义词来测试它们。
内联同义词不推荐用于生产环境。 大量内联同义词会增加集群大小,且可能导致性能问题。
配置同义词分词过滤器和分析器
edit一旦创建了同义词集,您就可以开始配置您的令牌过滤器和分析器以使用它们。
同义词集必须在添加到索引之前存在。 如果创建的索引引用了不存在的同义词集,索引将保持部分创建且无法操作的状态。 从这种情况恢复的唯一方法是确保同义词集存在,然后删除并重新创建索引,或者关闭并重新打开索引。
无效的同义词规则在应用分析器更改时可能会导致错误。 对于可重新加载的分析器,这会阻止重新加载和应用更改。 您必须更正同义词规则中的错误并重新加载分析器。
具有无效同义词规则的索引无法重新打开,使其在以下情况下无法操作:
- 包含索引的节点启动
- 从关闭状态打开索引
- 发生节点重启(重新打开分配给该节点的分片)
Elasticsearch 在 分析过程中使用同义词。 您可以使用两种类型的 token 过滤器来包含同义词:
- Synonym graph: 建议使用它,因为它可以正确处理多词同义词("hurriedly", "in a hurry")。
- Synonym: 如果你需要使用多词同义词,则不推荐使用。
请查阅每个同义词标记过滤器的文档以获取配置详细信息和将其添加到分析器的说明。
测试您的分析器
edit您可以在不修改索引设置的情况下测试分析器配置。 使用analyze API来测试您的分析器链:
GET /_analyze
{
"tokenizer": "standard",
"filter" : [
"lowercase",
{
"type": "synonym_graph",
"synonyms": ["pc => personal computer", "computer, pc, laptop"]
}
],
"text" : "Check how PC synonyms work"
}
在索引或搜索时应用同义词
edit分析器可以在索引时间或搜索时间应用。
你需要决定何时应用你的同义词:
使用同义词API创建的同义词集只能在搜索时使用。
您可以将包含同义词集的分析器指定为搜索时分析器或作为索引时分析器。
以下示例将 my_analyzer 作为搜索分析器添加到索引映射中的 title 字段:
"mappings": {
"properties": {
"title": {
"type": "text",
"search_analyzer": "my_analyzer",
"updateable": true
}
}
}