如何在Spring中自定义Solr查询获取色调接近指定值的Imagen数据?
解决Spring Data Solr中按数值范围查询字段的问题
看起来你遇到的问题是Spring Data Solr的方法名解析逻辑导致的——它把predominantColor_hue里的下划线当成了对象属性的路径分隔符,误以为你要访问predominantColor(这是个String数组)的hue属性,自然就会报错"No property hue found for type String"。下面给你几个可行的解决方案:
方案1:使用@Query注解自定义查询
这是最直接的方式,绕过方法名解析,直接写Solr的查询语句来指定范围:
public interface ImagenRepository extends SolrCrudRepository<Imagen, String> { @Query("predominantColor_hue:[?0 TO ?1]") List<Imagen> findByPredominantColorHueRange(double lowerBound, double upperBound); }
调用时传入目标值±5的范围即可:
double targetHue = 180.0; List<Imagen> results = imagenRepository.findByPredominantColorHueRange(targetHue - 5, targetHue + 5);
如果想更贴合"接近输入值"的需求,还可以用Solr的函数查询计算差值:
@Query("{!frange l=0 u=5}abs(predominantColor_hue - ?0)") List<Imagen> findByPredominantColorHueNear(double targetHue);
这个查询会直接返回predominantColor_hue与目标值的绝对值差≤5的文档。
方案2:调整实体类字段名(驼峰命名)
Spring Data更适配驼峰命名的属性,你可以修改实体类字段名,同时通过@Field注解保留Solr中的原始字段名:
@SolrDocument(solrCoreName = "images") public class Imagen { @Id @Field private String id; @Field("origin_url") public String originUrl; @Field("predominantColor") public String[] predominantColor; @Field("predominantColor_hue") public double predominantColorHue; // 改为驼峰命名 }
之后Repository的方法名就能正常解析了:
List<Imagen> findByPredominantColorHueBetween(double lowerBound, double upperBound);
调用时同样传入targetValue-5和targetValue+5即可。
方案3:使用SolrTemplate手动构建查询
如果需要更复杂的查询逻辑,SolrTemplate能提供更大的控制权:
@Autowired private SolrTemplate solrTemplate; public List<Imagen> findHueNear(double targetHue) { Criteria criteria = Criteria.where("predominantColor_hue") .between(targetHue - 5, targetHue + 5); Query query = new SimpleQuery(criteria); return solrTemplate.queryForList(query, Imagen.class); }
或者用函数查询实现差值判断:
public List<Imagen> findHueNear(double targetHue) { String functionQuery = String.format("abs(predominantColor_hue - %.2f) <=5", targetHue); Query query = new SimpleQuery(functionQuery); return solrTemplate.queryForList(query, Imagen.class); }
这几个方案里,我个人推荐第一种用@Query的方式,既简单又能直接贴合你的需求,不需要修改实体类结构。
内容的提问来源于stack exchange,提问作者Andres Molina
相关产品推荐
相关产品推荐

