You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lucene查询中添加按城市ID过滤的WHERE条件

添加城市ID过滤条件的Lucene查询方案

很简单,我们只需要把原来的模糊关键词查询和城市ID的精确查询通过**布尔查询(BooleanQuery)**组合起来,让两个条件同时生效即可。具体调整如下:

步骤说明

  • 保留你原来的模糊关键词查询逻辑,负责匹配name、description、address字段的关键词
  • 新增一个精确匹配city_id字段的查询,限定结果的城市ID等于传入的studentCity参数
  • 使用bool().must()方法把两个查询组合,确保只有同时满足两个条件的记录才会被返回

修改后的完整代码

public List<Spot> search(String search, Long studentCity) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Spot.class).get();

    // 1. 原来的模糊关键词查询
    Query keywordQuery = qb.keyword().fuzzy()
            .withEditDistanceUpTo(1)
            .withPrefixLength(1)
            .onFields("name", "description", "address")
            .matching(search)
            .createQuery();

    // 2. 新增城市ID精确匹配查询
    Query cityQuery = qb.keyword()
            .onField("city_id") // 这里要和Spot实体中对应student_table.city_id的字段名一致
            .matching(studentCity)
            .createQuery();

    // 3. 组合两个查询:必须同时满足关键词匹配和城市ID匹配
    Query luceneQuery = qb.bool()
            .must(keywordQuery)
            .must(cityQuery)
            .createQuery();

    // 执行查询并返回结果
    javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Spot.class);
    return jpaQuery.getResultList();
}

关键细节提醒

  • 确保Spot实体中存在对应数据库student_table.city_id的字段(比如字段名是cityId或者city_id,要和onField()里的参数一致),并且这个字段已经被Hibernate Search正确索引
  • 如果你的城市ID是数值类型,直接用matching(studentCity)就可以实现精确匹配,不需要额外处理

内容的提问来源于stack exchange,提问作者ralhanani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:02:35