Introduction to Spring Data Solr – Spring Data Solr简介

最后修改: 2016年 11月 17日


1. Overview


In this article, we’ll explore the basics of Spring Data Solr in a practical manner.

在这篇文章中,我们将以实用的方式探索Spring Data Solr的基础知识

Apache Solr is an open-source ready-to-deploy enterprise full-text search engine. You can find more about the features of Solr on the official website.

Apache Solr是一个开源的、可随时部署的企业全文搜索引擎。你可以在官方网站上找到更多关于Solr的功能。

We’ll show how to do a simple Solr configuration and of course how to interact with the server.


First, we need to start a Solr server and create a core to store data (which, by default, Solr will create in schemaless mode).

First, we need to start a Solr server and create a core to store data (which, by default, Solr will create in schemaless mode).

2. Spring Data

2.Spring Data

Just as any other Spring Data project, Spring Data Solr has a clear goal to remove boilerplate codes, which we’ll definitely take advantage of.

就像其他Spring Data项目一样,Spring Data Solr有一个明确的目标,那就是去除模板代码,我们肯定会利用这个优势。

2.1. Maven Dependency


Let’s start by adding the Spring Data Solr dependency to our pom.xml:

让我们先把Spring Data Solr的依赖关系添加到我们的pom.xml


You can find the latest dependencies here.


2.2. Defining the Document


Let’s define a document called Product:


@SolrDocument(solrCoreName = "product")
public class Product {
    @Indexed(name = "id", type = "string")
    private String id;

    @Indexed(name = "name", type = "string")
    private String name;


@SolrDocument annotation indicates that the Product class is a Solr document and indexed to core named product. Fields annotated with @Indexed are indexed in Solr and will be searchable.


2.3. Defining Repository Interface


Next, we need to create a repository interface by extending a repository provided by Spring Data Solr. We’ll naturally parametrize this with Product and String as our entity id:

接下来,我们需要通过扩展Spring Data Solr提供的资源库来创建一个资源库接口。我们将自然地用ProductString作为我们的实体ID进行参数化。

public interface ProductRepository extends SolrCrudRepository<Product, String> {

    public List<Product> findByName(String name);

    @Query("id:*?0* OR name:*?0*")
    public Page<Product> findByCustomQuery(String searchTerm, Pageable pageable);

    @Query(name = "Product.findByNamedQuery")
    public Page<Product> findByNamedQuery(String searchTerm, Pageable pageable);


Notice how we’re defining three methods here, on top of the API provided by SolrCrudRepository. We’ll talk about these in the next few sections.


Also note that the Product.findByNamedQuery property is defined in Solr named query file in the classpath folder:


Product.findByNamedQuery=id:*?0* OR name:*?0*

2.4. Java Configuration

2.4. Java配置

Now we’ll explore the Spring configuration of Solr persistence layer:


  basePackages = "",
  namedQueriesLocation = "")
public class SolrConfig {

    public SolrClient solrClient() {
        return new HttpSolrClient.Builder("http://localhost:8983/solr").build();

    public SolrTemplate solrTemplate(SolrClient client) throws Exception {
        return new SolrTemplate(client);

We are using @EnableSolrRepositories to scan the packages for repositories. Note that we have specified the location of the named query properties file and enabled multi-core support.


If multi-core is not enabled, then by default Spring Data will assume that Solr configuration is for a single core. We’re enabling multi-core here, just for reference.

如果没有启用多核,那么默认情况下Spring Data会认为Solr的配置是单核的。我们在这里启用多核,只是为了参考。

3. Spring Data Solr with Spring Boot

3.Spring Data Solr与Spring Boot

In this section, we’ll have a look at what the setup looks like in a Spring Boot application.

在本节中,我们将看看Spring Boot应用程序中的设置是什么样子的。

Let’s start by adding the Spring Boot Starter Data Solr dependency to our pom.xml:

让我们先把Spring Boot Starter Data Solr的依赖关系添加到我们的pom.xml


You can find the latest version of the dependency here.


We also have to define the property in the file with the value of the Solr URL:

我们还必须在application.properties文件中用Solr URL的值定义属性 

Make sure that Solr is running on the specified URL.


This is all the configuration we need to set up Spring Data Solr in a Spring Boot application since having the starter on the classpath will load the auto-configuration.

这是我们在Spring Boot应用程序中设置Spring Data Solr所需的所有配置,因为在classpath上拥有启动器将加载自动配置。

4. Indexing, Updating, and Deleting

4. 索引、更新和删除

In order to search documents in Solr, documents should be indexed to Solr repository.


Following example indexes a product document in Solr repository simply by using the SolrCrudRepository’s save method:


Product phone = new Product();

Now let’s retrieve and update a document:


Product retrievedProduct = productRepository.findById("P0001").get();
retrievedProduct.setName("Smart Phone");;

Documents can be deleted by simply calling the delete method:



5. Querying

5 查询[/strong]

Let’s now explore different querying techniques provided by the Spring Data Solr API.

现在让我们来探索Spring Data Solr API提供的不同查询技术。

5.1. Method Name Query Generation


Method name based queries are generated by parsing the method name to generate the expected query to execute:


public List<Product> findByName(String name);

In our repository interface, we have findByName method which generates query based on method name:


List<Product> retrievedProducts = productRepository.findByName("Phone");

5.2. Query With @Query Annotation


Solr search queries can be created by having the query in a @Query annotation of a method. In our example findByCustomQuery is annotated with @Query annotation:


@Query("id:*?0* OR name:*?0*")
public Page<Product> findByCustomQuery(String searchTerm, Pageable pageable);

Let’s use this method to retrieve documents:


Page<Product> result 
  = productRepository.findByCustomQuery("Phone", PageRequest.of(0, 10));

By calling the findByCustomQuery(“Phone”, PageRequest.of(0, 10)) we obtain the first page of the product documents which contain the word “Phone” in any of its fields id or name.

通过调用findByCustomQuery(“Phone”, PageRequest.of(0, 10)),我们获得产品文档的第一页,其中任何一个字段idname中包含 “Phone”。

5.3. Named Query


Named queries are similar to queries with @Query annotation except the queries are declared in a separate properties file:


@Query(name = "Product.findByNamedQuery")
public Page<Product> findByNamedQuery(String searchTerm, Pageable pageable);

Note that the @Query annotation is not required if the key (findByNamedQuery) of the query in properties file matches the method name.


Let’s retrieve some documents using named query method:


Page<Product> result 
  = productRepository.findByNamedQuery("one", PageRequest.of(0, 10));

6. Conclusion


This article is a quick and practical introduction to Spring Data Solr, covering the basic configuration, defining repositories and naturally – querying.

本文是对Spring Data Solr的快速和实用的介绍,包括基本配置、定义存储库和自然-查询。

And as always, the examples used here are available as a sample project on Github.