Spring Data Elasticsearch查询结果不符合预期求助
问题解决:Spring Data Elasticsearch findByText()查询无结果
问题原因
核心矛盾是Spring Data Elasticsearch默认派生查询与直接ES查询的逻辑不一致:
- 直接通过ES端口查询时,你用的是
match查询,它会对输入文本分词,再匹配text字段(Text类型)的分词结果; - 而
findByText()默认生成term查询,会尝试精确匹配整个输入字符串,你的text字段存储值是"top 20 tweets of",和输入的"top 20 tweets of ABC"完全不匹配,因此返回空结果。
解决方案
方案1:自定义@Query实现match查询
在ElasticsearchRepository接口中添加自定义方法,手动指定match查询逻辑:
public interface ESKeywordsRepository extends ElasticsearchRepository<ESKeywords, Long> { // 自定义match查询,匹配text字段的分词结果 @Query("{\"match\": {\"text\": \"?0\"}}") List<ESKeywords> findByTextMatch(String text); }
调用findByTextMatch("top 20 tweets of ABC")即可得到预期结果。
方案2:用派生查询关键字生成match查询
Spring Data Elasticsearch支持通过关键字自动生成分词匹配查询,比如Containing或Matches:
public interface ESKeywordsRepository extends ElasticsearchRepository<ESKeywords, Long> { // 生成match查询,对输入文本分词后匹配text字段 List<ESKeywords> findByTextContaining(String text); // 或用Matches关键字,效果一致 List<ESKeywords> findByTextMatches(String text); }
这两种方法的逻辑和直接ES查询一致,传入搜索文本就能返回匹配结果。
注意事项
- 不要将
text字段类型改为Keyword,否则会失去分词能力,不符合你的查询需求; - 若使用Spring Data Elasticsearch 3.x及以下版本,部分关键字可能不支持,优先采用@Query注解的方式。
内容的提问来源于stack exchange,提问作者Sanat Chandravanshi
相关产品推荐
相关产品推荐

