Query methods
Query lookup strategies
The Solr module supports defining a query manually as String or have it being derived from the method name. NOTE: There is no QueryDSL Support present at this time.
Declared queries
Deriving the query from the method name is not always sufficient and/or may result in unreadable method names. In this case one might make either use of Solr named queries (see solr.query-methods.named-queries ) or use the @Query
annotation (see solr.query-methods.at-query ).
Query creation
Generally the query creation mechanism for Solr works as described in repositories.query-methods . Here’s a short example of what a Solr query method translates into:
public interface ProductRepository extends Repository<Product, String> {
List<Product> findByNameAndPopularity(String name, Integer popularity);
}
The method name above will be translated into the following solr query
q=name:?0 AND popularity:?1
A list of supported keywords for Solr is shown below.
Keyword | Sample | Solr Query String |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Collections types can be used along with 'Like', 'NotLike', 'StartingWith', 'EndingWith' and 'Containing'. |
Page<Product> findByNameLike(Collection<String> name);
Using @Query Annotation
Using named queries ( solr.query-methods.named-queries ) to declare queries for entities is a valid approach and works fine for a small number of queries. As the queries themselves are tied to the Java method that executes them, you actually can bind them directly using the Spring Data Solr @Query
annotation.
@Query
annotation.public interface ProductRepository extends SolrRepository<Product, String> {
@Query("inStock:?0")
List<Product> findByAvailable(Boolean available);
}
Using NamedQueries
Named queries can be kept in a properties file and wired to the accroding method. Please mind the naming convention described in repositories.query-methods.query-lookup-strategies or use @Query
.
Product.findByNamedQuery=popularity:?0
Product.findByName=name:?0
public interface ProductRepository extends SolrCrudRepository<Product, String> {
List<Product> findByNamedQuery(Integer popularity);
@Query(name = "Product.findByName")
List<Product> findByAnnotatedNamedQuery(String name);
}