Elasticsearch单索引如何同时应用停用词与同义词多项设置
Elasticsearch单索引同时配置停用词、同义词方案说明
你当前编写的两次es.indices.put_settings调用逻辑无法正常生效,存在三个核心问题:
- 第一,
put_settings接口仅支持修改索引的settings配置,你传入的两个配置结构体中都包含mappings字段,调用时会直接抛出参数非法错误。 - 第二,自定义分析器、自定义词元过滤器这类分析相关配置,首次新增时不能直接在开放状态的索引上通过
put_settings添加。你配置里写的updateable: true参数仅用于后续更新词库文件后的重载操作,不支持首次新增分析配置时跳过关闭索引的步骤。 - 第三,你两次配置都单独给
description字段指定了search_analyzer,第二次调用会直接覆盖第一次的配置,最终只会生效同义词分析器,停用词配置完全不会被触发。
正确配置方式
根据你的索引是否已经创建,分两种场景处理:
场景1:gene索引还未创建
直接把停用词、同义词的配置合并,在创建索引时一次性传入即可,不需要分多次调用。如果需要搜索时同时生效停用词过滤和同义词替换,可以把两个自定义过滤器放到同一个搜索分析器中,参考代码如下:
# 合并两类配置后的完整索引定义 index_config = { "settings": { "index": { "analysis": { "analyzer": { # 整合停用词+同义词能力的自定义搜索分析器 "my_search_analyzer": { "type": "custom", "tokenizer": "standard", "filter": ["my_stop_filter", "my_synonym_filter"] } }, "filter": { # 停用词过滤器 "my_stop_filter": { "type": "stop", "stopwords_path": "st.txt", "updateable": true }, # 同义词过滤器 "my_synonym_filter": { "type": "synonym", "synonyms_path": "sy.txt", "updateable": true } } } } }, "mappings": { "properties": { "description": { "type": "text", "analyzer": "standard", # 搜索时同时走停用词、同义词过滤逻辑 "search_analyzer": "my_search_analyzer" } } } } # 调用创建索引接口一次性完成配置 es.indices.create(index="gene", body=index_config)
场景2:gene是已存在的存量索引
需要按照以下步骤操作,不能直接调用put_settings写入全量配置:
- 先关闭目标索引
执行命令:es.indices.close(index="gene") - 传入合并后的分析相关settings,注意不要携带mappings字段
analysis_setting = { "settings": { "index": { "analysis": { "analyzer": { "my_search_analyzer": { "type": "custom", "tokenizer": "standard", "filter": ["my_stop_filter", "my_synonym_filter"] } }, "filter": { "my_stop_filter": { "type": "stop", "stopwords_path": "st.txt", "updateable": true }, "my_synonym_filter": { "type": "synonym", "synonyms_path": "sy.txt", "updateable": true } } } } } } es.indices.put_settings(index="gene", body=analysis_setting) - 单独调用mappings更新接口,给字段指定合并后的搜索分析器
mapping_update = { "properties": { "description": { "type": "text", "analyzer": "standard", "search_analyzer": "my_search_analyzer" } } } es.indices.put_mapping(index="gene", body=mapping_update) - 重新打开索引让配置生效
执行命令:es.indices.open(index="gene")
后续词库维护说明
配置里的updateable: true标记生效后,后续如果修改了服务器上的st.txt停用词文件、sy.txt同义词文件,不需要再关闭索引,直接调用es.indices.reload_search_analyzers(index="gene")就能重载新的词库内容,配置即时生效。
内容的提问来源于stack exchange,提问作者sim
相关产品推荐
相关产品推荐

