Introduction to Spring Data Solr – Spring Data Solr简介

最后修改: 2016年 11月 17日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

我们将展示如何进行简单的Solr配置,当然还有如何与服务器互动。

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

2.1.Maven的依赖性

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

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

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-solr</artifactId>
    <version>4.3.14</version>
</dependency>

You can find the latest dependencies here.

你可以在这里找到最新的依赖性

2.2. Defining the Document

2.2.定义文件

Let’s define a document called Product:

让我们定义一个名为Product的文件。

@SolrDocument(solrCoreName = "product")
public class Product {
   
    @Id
    @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.

@SolrDocument注解表明Product类是一个Solr文档,并被索引到名为product的核心。带有@Indexed注释的字段在Solr中被索引,并且可以被搜索。

2.3. Defining Repository Interface

2.3.定义存储库接口

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.

注意我们在这里定义了三个方法,在SolrCrudRepository提供的API之上。我们将在接下来的几节中讨论这些方法。

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

还要注意,Product.findByNamedQuery属性是在classpath文件夹中的Solr命名查询文件solr-named-queries.properties中定义的。

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:

现在我们将探讨Solr持久层的Spring配置。

@Configuration
@EnableSolrRepositories(
  basePackages = "com.baeldung.spring.data.solr.repository",
  namedQueriesLocation = "classpath:solr-named-queries.properties")
@ComponentScan
public class SolrConfig {

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

    @Bean
    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.

我们正在使用@EnableSolrRepositories来扫描软件包中的存储库。注意,我们已经指定了命名查询属性文件的位置,并启用了多核支持。

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-solr</artifactId>
    <version>2.4.12</version>
</dependency>

You can find the latest version of the dependency here.

你可以在这里找到最新版本的依赖性

We also have to define the property spring.data.solr.host in the application.properties file with the value of the Solr URL:

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

spring.data.solr.host=http://localhost:8983/solr 

Make sure that Solr is running on the specified URL.

确保Solr正在指定的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.

为了在Solr中搜索文件,文件应该被索引到Solr资源库。

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

下面的例子是通过使用SolrCrudRepository的保存方法来索引Solr资源库中的产品文档。

Product phone = new Product();
phone.setId("P0001");
phone.setName("Phone");
productRepository.save(phone);

Now let’s retrieve and update a document:

现在我们来检索和更新一个文件。

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

Documents can be deleted by simply calling the delete method:

文件可以通过简单地调用删除方法而被删除。

productRepository.delete(retrievedProduct);

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

5.1.方法名称查询的生成

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:

在我们的版本库接口中,我们有findByName方法,它根据方法名称生成查询。

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

5.2. Query With @Query Annotation

5.2.使用@Query注释的查询

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:

Solr搜索查询可以通过在一个方法的@Query注解中拥有查询来创建。在我们的例子中,findByCustomQuery被注解为@Query注解。

@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

5.3.命名查询

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

命名查询与带有@Query注解的查询类似,只是查询是在一个单独的属性文件中声明的。

@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.

注意,如果属性文件中查询的键(findByNamedQuery)与方法名称相匹配,则不需要@Query注解。

Let’s retrieve some documents using named query method:

让我们使用命名查询方法检索一些文件。

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

6. Conclusion

6.结论

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.

而且像往常一样,这里使用的例子可以作为Github上的示例项目提供。