Elasticsearch 5.2.1配置:让含连字符字段支持精确搜索
解决Elasticsearch 5.2.1中带连字符标识符的精确搜索问题
针对你的需求,在fos_elastica.yaml中有两种常用配置方案,既能实现目标字段的精确搜索,又不影响其他字段的分词行为:
方案1:直接将目标字段设为keyword类型
如果该标识符字段只需要精确匹配(不需要拆分连字符后的部分搜索),直接将其映射为keyword类型,Elasticsearch会把整个标识符作为单一词汇索引,不会拆分连字符。
配置示例:
fos_elastica: indexes: # 替换为你的索引名称 your_index: types: # 替换为你的实体类型名称 your_entity: mappings: # 目标标识符字段 identifier: type: keyword # 其他字段保持默认配置,会使用默认分词器处理连字符拆分 title: ~ description: ~ persistence: driver: orm model: App\Entity\YourEntity provider: ~ finder: ~
方案2:多字段配置(兼顾精确与分词搜索)
如果需要该字段同时支持精确搜索和拆分后的部分匹配,可以配置多字段(multi-field):主字段使用默认分词逻辑,新增一个子字段用于精确匹配。
配置示例:
fos_elastica: indexes: your_index: types: your_entity: mappings: identifier: type: text fields: # 子字段用于精确搜索 exact: type: keyword # 其他字段正常配置 title: ~ description: ~ persistence: driver: orm model: App\Entity\YourEntity provider: ~ finder: ~
使用时,精确搜索需指定子字段,例如:
// 精确匹配标识符 $result = $finder->findOneBy(['identifier.exact' => '023-019125']);
注意事项
- 修改映射后,需要重新创建索引并全量导入数据(Elasticsearch 5.x不允许修改已有字段的映射类型)。
- 可以通过Elasticsearch API验证映射是否生效:
curl -XGET 'http://your-es-host:9200/your_index/_mapping/your_entity'
内容的提问来源于stack exchange,提问作者Alexander Álvarez
相关产品推荐
相关产品推荐

