首页
/ Hibernate Search 技术文档

Hibernate Search 技术文档

2024-12-20 12:00:20作者:宣利权Counsellor

1. 安装指南

1.1 环境要求

  • Java 8 或更高版本
  • Maven 或 Gradle 构建工具
  • Hibernate ORM 5.4 或更高版本

1.2 Maven 依赖

pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.hibernate.search</groupId>
    <artifactId>hibernate-search-mapper-orm</artifactId>
    <version>7.2.2.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate.search</groupId>
    <artifactId>hibernate-search-backend-lucene</artifactId>
    <version>7.2.2.Final</version>
</dependency>

1.3 Gradle 依赖

build.gradle 文件中添加以下依赖:

dependencies {
    implementation 'org.hibernate.search:hibernate-search-mapper-orm:7.2.2.Final'
    implementation 'org.hibernate.search:hibernate-search-backend-lucene:7.2.2.Final'
}

2. 项目的使用说明

2.1 配置文件

hibernate.cfg.xmlpersistence.xml 中添加 Hibernate Search 的配置:

<property name="hibernate.search.default.directory_provider" value="filesystem"/>
<property name="hibernate.search.default.indexBase" value="/path/to/indexes"/>

2.2 实体映射

使用注解或编程 API 将实体映射到索引字段。例如:

@Entity
@Indexed
public class Book {

    @Id
    @GeneratedValue
    private Integer id;

    @FullTextField
    private String title;

    @ManyToMany
    @IndexedEmbedded
    private Set<Author> authors = new HashSet<>();

    // Getters and setters
}

@Entity
public class Author {

    @Id
    @GeneratedValue
    private Integer id;

    @FullTextField
    private String name;

    @ManyToMany(mappedBy = "authors")
    private Set<Book> books = new HashSet<>();

    // Getters and setters
}

2.3 索引数据

使用 MassIndexer 索引现有数据:

SearchSession searchSession = Search.session(entityManager);
MassIndexer indexer = searchSession.massIndexer(Book.class);
indexer.startAndWait();

2.4 搜索数据

使用 Search DSL 构建全文搜索查询:

SearchResult<Book> result = Search.session(entityManager)
        .search(Book.class)
        .where(f -> f.match()
                .fields("title", "authors.name")
                .matching("Isaac"))
        .fetch(20);

List<Book> hits = result.hits();
long totalHitCount = result.total().hitCount();

3. 项目API使用文档

3.1 SearchSession API

SearchSession 是 Hibernate Search 的核心接口,用于执行搜索操作。

SearchSession searchSession = Search.session(entityManager);

3.2 MassIndexer API

MassIndexer 用于批量索引数据库中的所有实体。

MassIndexer indexer = searchSession.massIndexer(Book.class);
indexer.startAndWait();

3.3 Search DSL API

Search DSL 提供了丰富的查询构建功能,支持多种查询类型和排序方式。

SearchResult<Book> result = searchSession.search(Book.class)
        .where(f -> f.match()
                .fields("title", "authors.name")
                .matching("Isaac"))
        .fetch(20);

4. 项目安装方式

4.1 Maven 安装

通过 Maven 安装 Hibernate Search,只需在 pom.xml 中添加相应的依赖。

4.2 Gradle 安装

通过 Gradle 安装 Hibernate Search,只需在 build.gradle 中添加相应的依赖。

4.3 手动安装

可以从 SourceForge 下载 Hibernate Search 的发布包,并手动集成到项目中。

通过以上步骤,您可以成功安装并使用 Hibernate Search 进行全文搜索。

登录后查看全文
热门项目推荐