第二阶段 15 · prefix / wildcard / fuzzy 模糊匹配

15 · prefix / wildcard / fuzzy 模糊匹配

阶段:第二阶段 / 查询能力

ES 查询:prefix / wildcard / fuzzy | PostgreSQL 对照:LIKE 'abc%' / LIKE '%x%' / 模糊纠错


1. 概念

三种「非精确」匹配,都作用在 keyword(或 text 的词项)上:

ES 查询 作用 SQL 对应
prefix 前缀匹配 LIKE 'abc%'
wildcard 通配符匹配(* 多字符,? 单字符) LIKE '%x%' / LIKE 'a?c'
fuzzy 允许拼写误差(编辑距离) PG 没有直接语法(近似 pg_trgm

⚠️ 这三种都可能很慢 (尤其前置通配 *abc),生产环境慎用大范围。


2. PostgreSQL 对照

sql 复制代码
-- prefix
SELECT * FROM salesdata WHERE invoice_number LIKE 'INV-2026%';

-- wildcard(包含)
SELECT * FROM salesdata WHERE invoice_number LIKE '%2026%';

-- fuzzy(拼写容错,PG 需 pg_trgm 扩展)
SELECT * FROM salesdata WHERE material % 'ThinkPd';  -- 相似度

3. ES DSL

prefix(前缀)

复制代码
GET salesdata_idx/_search
{
  "query": { "prefix": { "invoice_number": "INV-2026" } }
}

wildcard(通配符)

复制代码
GET salesdata_idx/_search
{
  "query": { "wildcard": { "invoice_number": "*2026*" } }
}

fuzzy(拼写容错)

复制代码
GET salesdata_idx/_search
{
  "query": {
    "fuzzy": {
      "material": { "value": "ThinkPd", "fuzziness": "AUTO" }
    }
  }
}

fuzziness: AUTO 会根据词长自动决定允许的编辑距离(通常 1~2)。


4. Spring Boot 实现

java 复制代码
@Component
public class Doc15FuzzyQuery {

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    /** LIKE 'prefix%' */
    public List<Map<String, Object>> prefix(String indexName, String field, String prefix)
            throws IOException {
        SearchResponse<Map> resp = elasticsearchClient.search(s -> s
                .index(indexName)
                .query(q -> q.prefix(p -> p.field(field).value(prefix))),
                Map.class);
        return toSourceList(resp);
    }

    /** LIKE '%pattern%',pattern 里用 * 和 ? */
    public List<Map<String, Object>> wildcard(String indexName, String field, String pattern)
            throws IOException {
        SearchResponse<Map> resp = elasticsearchClient.search(s -> s
                .index(indexName)
                .query(q -> q.wildcard(w -> w.field(field).value(pattern))),
                Map.class);
        return toSourceList(resp);
    }

    /** 拼写容错 */
    public List<Map<String, Object>> fuzzy(String indexName, String field, String value)
            throws IOException {
        SearchResponse<Map> resp = elasticsearchClient.search(s -> s
                .index(indexName)
                .query(q -> q.fuzzy(f -> f.field(field).value(value).fuzziness("AUTO"))),
                Map.class);
        return toSourceList(resp);
    }

    private List<Map<String, Object>> toSourceList(SearchResponse<Map> resp) {
        return resp.hits().hits().stream()
                .map(Hit::source).filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}

5. 坑与最佳实践

  1. 前置通配符 *abc 极慢 :等于全表扫倒排词典,能避免就避免;必要时用 wildcard 字段类型或 n-gram。
  2. 作用在 keyword :对分词后的 text 用 wildcard 结果常常反直觉。
  3. 大小写keyword 默认大小写敏感,wildcard 也是。需要不敏感可加 case_insensitive: true(8.x 支持)。
  4. fuzzy 有性能代价 :编辑距离越大越慢,AUTO 通常够用。
  5. 能用 prefix 就别用 wildcard:前缀匹配比通配快得多。

下一篇

16-match_phrase-短语.md

相关推荐
vHelios3 天前
【电商项目】商品搜索开发复盘(1):根据需求拆解搜索接口的设计逻辑
java·微服务·es
cfm_291412 天前
Logstash 8.x 入门实战
安全·es
倒流时光三十年17 天前
第五阶段 40 · 深分页与性能(from/size、search_after、scroll、PIT)
es
倒流时光三十年19 天前
第三阶段 29 · suggester 自动补全(搜索框联想 / 拼写纠错)
es
倒流时光三十年19 天前
第三阶段 24 · filter / filters 桶聚合
es
倒流时光三十年20 天前
第二阶段 17 · multi_match 多字段匹配
es
倒流时光三十年20 天前
第三阶段 23 · 嵌套与子聚合 / top_hits
es
倒流时光三十年20 天前
第二阶段 19 · _source 字段裁剪
es
粗体鱼21 天前
RAG/Agent 记忆混合检索多路召回:RRF 算法与Chunk RRF、Document RRF如何决策TopK
postgresql·milvus·es·rag·rff·mermory