The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

Use Hibernate Search with Hibernate ORM and Elasticsearch/OpenSearch

Hibernate ORMベースのアプリケーションを持ってますか?フル機能の全文検索をユーザーに提供したいですか?あなたは正しいドキュメントを読んでいます。

このガイドでは、Hibernate Search を使用して、エンティティを Elasticsearch または OpenSearch クラスタに瞬時に同期させる方法を学びます。また、Hibernate Search API を使用して Elasticsearch または OpenSearch クラスタにクエリを実行する方法についても説明します。

前提条件

このガイドを完成させるには、以下が必要です:

  • ざっと 20 minutes

  • IDE

  • JDK 17+がインストールされ、 JAVA_HOME が適切に設定されていること

  • Apache Maven 3.9.6

  • 動作するコンテナランタイム(Docker, Podman)

  • 使用したい場合は、 Quarkus CLI

  • ネイティブ実行可能ファイルをビルドしたい場合、MandrelまたはGraalVM(あるいはネイティブなコンテナビルドを使用する場合はDocker)をインストールし、 適切に設定していること

アーキテクチャ

このガイドに記載されているアプリケーションは、(シンプルな) 図書館を管理することができます:あなたは、著者とその本を管理します。

エンティティはPostgreSQLデータベースに格納され、Elasticsearchクラスターにインデックスされます。

ソリューション

次の章で紹介する手順に沿って、ステップを踏んでアプリを作成することをお勧めします。ただし、完成した例にそのまま進んでも構いません。

Gitレポジトリをクローンするか git clone https://github.com/quarkusio/quarkus-quickstarts.gitアーカイブ をダウンロードします。

The solution is located in the hibernate-search-orm-elasticsearch-quickstart directory.

提供されるソリューションには、テストやテストのインフラストラクチャなど、いくつかの追加要素が含まれています。

Mavenプロジェクトの作成

まず、新しいプロジェクトが必要です。以下のコマンドで新規プロジェクトを作成します:

コマンドラインインタフェース
quarkus create app org.acme:hibernate-search-orm-elasticsearch-quickstart \
    --extension='hibernate-orm-panache,jdbc-postgresql,hibernate-search-orm-elasticsearch,rest-jackson' \
    --no-code
cd hibernate-search-orm-elasticsearch-quickstart

Gradleプロジェクトを作成するには、 --gradle または --gradle-kotlin-dsl オプションを追加します。

Quarkus CLIのインストールと使用方法の詳細については、 Quarkus CLI ガイドを参照してください。

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:3.9.3:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=hibernate-search-orm-elasticsearch-quickstart \
    -Dextensions='hibernate-orm-panache,jdbc-postgresql,hibernate-search-orm-elasticsearch,rest-jackson' \
    -DnoCode
cd hibernate-search-orm-elasticsearch-quickstart

Gradleプロジェクトを作成するには、 -DbuildTool=gradle または -DbuildTool=gradle-kotlin-dsl オプションを追加します。

Windowsユーザーの場合:

  • cmdを使用する場合、(バックスラッシュ \ を使用せず、すべてを同じ行に書かないでください)。

  • Powershellを使用する場合は、 -D パラメータを二重引用符で囲んでください。例: "-DprojectArtifactId=hibernate-search-orm-elasticsearch-quickstart"

このコマンドは、以下のエクステンションをインポートするMaven構造体を生成します:

  • Hibernate ORM with Panache,

  • PostgreSQL JDBCドライバー,

  • Hibernate Search + Elasticsearch,

  • Quarkus REST (formerly RESTEasy Reactive) and Jackson.

すでにQuarkusプロジェクトが設定されている場合は、プロジェクトのベースディレクトリーで以下のコマンドを実行することで、プロジェクトに hibernate-search-orm-elasticsearch エクステンションを追加することができます。

コマンドラインインタフェース
quarkus extension add hibernate-search-orm-elasticsearch
Maven
./mvnw quarkus:add-extension -Dextensions='hibernate-search-orm-elasticsearch'
Gradle
./gradlew addExtension --extensions='hibernate-search-orm-elasticsearch'

これにより、 pom.xml に以下が追加されます:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-search-orm-elasticsearch</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-hibernate-search-orm-elasticsearch")

ただのエンティティの作成

まず、 model サブパッケージに Hibernate ORM エンティティ BookAuthor を作成しましょう。

package org.acme.hibernate.search.elasticsearch.model;

import java.util.List;
import java.util.Objects;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.OneToMany;

import io.quarkus.hibernate.orm.panache.PanacheEntity;

@Entity
public class Author extends PanacheEntity { (1)

    public String firstName;

    public String lastName;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) (2)
    public List<Book> books;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Author)) {
            return false;
        }

        Author other = (Author) o;

        return Objects.equals(id, other.id);
    }

    @Override
    public int hashCode() {
        return 31;
    }
}
1 Hibernate ORM with Panacheを使用していますが、必須ではありません。
2 私たちは、これらの要素がJSON出力に存在するように前もってロードしています。実際のアプリケーションでは、おそらくDTOアプローチを使うべきでしょう。
package org.acme.hibernate.search.elasticsearch.model;

import java.util.Objects;

import jakarta.persistence.Entity;
import jakarta.persistence.ManyToOne;

import com.fasterxml.jackson.annotation.JsonIgnore;

import io.quarkus.hibernate.orm.panache.PanacheEntity;

@Entity
public class Book extends PanacheEntity {

    public String title;

    @ManyToOne
    @JsonIgnore (1)
    public Author author;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Book)) {
            return false;
        }

        Book other = (Book) o;

        return Objects.equals(id, other.id);
    }

    @Override
    public int hashCode() {
        return 31;
    }
}
1 このプロパティを @JsonIgnore でマークしてJacksonでシリアル化する際の無限ループを避けます。

RESTサービスの初期化

まだRESTサービスの設定はすべて終わっていませんが、必要となる標準的なCRUD操作で初期化することができます。

org.acme.hibernate.search.elasticsearch.LibraryResource クラスを作成します:

package org.acme.hibernate.search.elasticsearch;

import java.util.List;
import java.util.Optional;

import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.MediaType;

import org.acme.hibernate.search.elasticsearch.model.Author;
import org.acme.hibernate.search.elasticsearch.model.Book;
import org.hibernate.search.mapper.orm.session.SearchSession;
import org.jboss.resteasy.reactive.RestForm;
import org.jboss.resteasy.reactive.RestQuery;

import io.quarkus.runtime.StartupEvent;

@Path("/library")
public class LibraryResource {

    @PUT
    @Path("book")
    @Transactional
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void addBook(@RestForm String title, @RestForm Long authorId) {
        Author author = Author.findById(authorId);
        if (author == null) {
            return;
        }

        Book book = new Book();
        book.title = title;
        book.author = author;
        book.persist();

        author.books.add(book);
        author.persist();
    }

    @DELETE
    @Path("book/{id}")
    @Transactional
    public void deleteBook(Long id) {
        Book book = Book.findById(id);
        if (book != null) {
            book.author.books.remove(book);
            book.delete();
        }
    }

    @PUT
    @Path("author")
    @Transactional
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void addAuthor(@RestForm String firstName, @RestForm String lastName) {
        Author author = new Author();
        author.firstName = firstName;
        author.lastName = lastName;
        author.persist();
    }

    @POST
    @Path("author/{id}")
    @Transactional
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void updateAuthor(Long id, @RestForm String firstName, @RestForm String lastName) {
        Author author = Author.findById(id);
        if (author == null) {
            return;
        }
        author.firstName = firstName;
        author.lastName = lastName;
        author.persist();
    }

    @DELETE
    @Path("author/{id}")
    @Transactional
    public void deleteAuthor(Long id) {
        Author author = Author.findById(id);
        if (author != null) {
            author.delete();
        }
    }
}

特別なことは何もありません。RESTサービスでのPanacheの処理と古き良きHibernateです。

実は、全文検索アプリケーションを動作させるために必要な要素はごくわずかです。

Hibernate Searchアノテーションの使用

エンティティに戻りましょう。

全文検索機能を有効にするには、いくつかのアノテーションを追加するだけで簡単です。

Book エンティティを再度編集して、この内容を入れてみましょう:

package org.acme.hibernate.search.elasticsearch.model;

import java.util.Objects;

import jakarta.persistence.Entity;
import jakarta.persistence.ManyToOne;

import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;

import com.fasterxml.jackson.annotation.JsonIgnore;

import io.quarkus.hibernate.orm.panache.PanacheEntity;

@Entity
@Indexed (1)
public class Book extends PanacheEntity {

    @FullTextField(analyzer = "english") (2)
    public String title;

    @ManyToOne
    @JsonIgnore
    public Author author;

    // Preexisting equals()/hashCode() methods
}
1 まず、 @Indexed アノテーションを使って、 Book エンティティを全文検索インデックスの一部として登録してみましょう。
2 @FullTextField アノテーションは、全文検索用に特別に調整されたインデックスのフィールドを宣言します。特に、トークン(~単語)を分割して分析するためのアナライザーを定義する必要があります。 - これについては後で説明します。

Book がインデックス化されたことで、 Author にも同じことができるようになりました。

Author クラスを開き、以下の内容を記載します。

@Indexed@FullTextField@KeywordField のアノテーションを使用していますが、こちらもよく似ている機能です。

しかし、いくつかの違いや付加価値があります。それを見てみましょう。

package org.acme.hibernate.search.elasticsearch.model;

import java.util.List;
import java.util.Objects;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.OneToMany;

import org.hibernate.search.engine.backend.types.Sortable;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.KeywordField;

import io.quarkus.hibernate.orm.panache.PanacheEntity;

@Entity
@Indexed
public class Author extends PanacheEntity {

    @FullTextField(analyzer = "name") (1)
    @KeywordField(name = "firstName_sort", sortable = Sortable.YES, normalizer = "sort") (2)
    public String firstName;

    @FullTextField(analyzer = "name")
    @KeywordField(name = "lastName_sort", sortable = Sortable.YES, normalizer = "sort")
    public String lastName;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    @IndexedEmbedded (3)
    public List<Book> books;

    // Preexisting equals()/hashCode() methods
}
1 @FullTextFieldBook と同様のものを使用しますが、アナライザーが異なることに気がつくでしょう - これについては後で説明します。
2 このように、同じプロパティに複数のフィールドを定義することができます。ここでは、固有の名前を持つ @KeywordField を定義しています。主な違いは、キーワードフィールドはトークン化されません(文字列は1つのトークンとして保持される)が、正規化(すなわちフィルタリング)することができるということです。これについては後で説明します。このフィールドは Author のソートに使用することを意図しているため、ソート可能であるとマークされています。
3 The purpose of @IndexedEmbedded is to include the Book fields into the Author index. In this case, we just use the default configuration: all the fields of the associated Book entities are included in the index (i.e. the title field). The nice thing with @IndexedEmbedded is that it is able to automatically reindex an Author if one of its Books has been updated thanks to the bidirectional relation. @IndexedEmbedded also supports nested documents (using the structure = NESTED attribute), but we don’t need it here. You can also specify the fields you want to embed in your parent index using the includePaths/excludePaths attributes if you don’t want them all.

アナライザーとノーマライザー

はじめに

アナライズは全文検索の大きな部分を占めています。インデックス作成や検索クエリ構築の際に、テキストがどのように処理されるかを定義します。

アナライザーの役割は、テキストをトークン(~単語)に分割し、フィルターをかけることです(例えば、すべて小文字にしたり、アクセントを削除したり)。

ノーマライザーは入力を1つのトークンとして保持する特殊なアナライザです。特に、キーワードのソートやインデックス作成に有効です。

多くのバンドルされたアナライザーがありますが、自分の目的に合わせて独自に開発することもできます。

Elasticsearchアナリシスフレームワークについては、 ElasticsearchドキュメントのText analysis セクション で詳しく説明しています。

使用するアナライザーの定義

エンティティにHibernate Searchアノテーションを追加する際に、使用するアナライザーとノーマライザーを定義しました。典型的には:

@FullTextField(analyzer = "english")
@FullTextField(analyzer = "name")
@KeywordField(name = "lastName_sort", sortable = Sortable.YES, normalizer = "sort")

以下のものを使用しています:

  • 人名用の name というアナライザー,

  • 書籍のタイトル用の english というアナライザー,

  • ソートフィールド用の sort というノーマライザー

ですが、まだ設定していません。

それでは、Hibernate Searchを使ってどのように設定できるのか見てみましょう。

アナライザーのセットアップ

これは簡単な作業で、 ElasticsearchAnalysisConfigurer の実装を作成するだけです(そして、それを使用するようにQuarkusを設定します、詳細は後述します)。

要件を満たすために、次のような実装を作ってみましょう:

package org.acme.hibernate.search.elasticsearch.config;

import org.hibernate.search.backend.elasticsearch.analysis.ElasticsearchAnalysisConfigurationContext;
import org.hibernate.search.backend.elasticsearch.analysis.ElasticsearchAnalysisConfigurer;

import io.quarkus.hibernate.search.orm.elasticsearch.SearchExtension;

@SearchExtension (1)
public class AnalysisConfigurer implements ElasticsearchAnalysisConfigurer {

    @Override
    public void configure(ElasticsearchAnalysisConfigurationContext context) {
        context.analyzer("name").custom() (2)
                .tokenizer("standard")
                .tokenFilters("asciifolding", "lowercase");

        context.analyzer("english").custom() (3)
                .tokenizer("standard")
                .tokenFilters("asciifolding", "lowercase", "porter_stem");

        context.normalizer("sort").custom() (4)
                .tokenFilters("asciifolding", "lowercase");
    }
}
1 Configurerの実装に @SearchExtension アノテーションを付けて、QuarkusにすべてのElasticsearchインデックスに(デフォルトで)デフォルトの永続化ユニットを使用するように指示します。

アノテーションは、特定の永続ユニット (@SearchExtension(persistenceUnit = "nameOfYourPU"))、 バックエンド (@SearchExtension(backend = "nameOfYourBackend"))、 インデックス (@SearchExtension(index = "nameOfYourIndex"))もターゲットにすることができます。

2 これは、スペースで単語を分離し、ASCII以外の文字をASCIIの対応する文字で置換し(したがって、アクセントを除去し)、すべてを小文字にするシンプルなアナライザーです。これは、例では著者名に使用されています。
3 これはもう少し積極的で、ステミングも含まれています。インデックス化された入力に mysteries が含まれていても、 mystery を検索して結果を得ることができます。人名に対しては確かに強引すぎますが、書籍のタイトルに対しては完璧です。
4 ここではソートに使われるノーマライザーを紹介します。最初のアナライザーと非常によく似ていますが、1つだけのトークンが欲しいので、単語をトークン化しないことを除けば同じです。

また、何らかの理由で @SearchExtension アノテーションを付けられない、あるいは付けたくない場合には、単純に @Dependent @Named("myAnalysisConfigurer") のアノテーションを付けて設定のプロパティから参照することも可能です:

quarkus.hibernate-search-orm.elasticsearch.analysis.configurer=bean:myAnalysisConfigurer

For more information about configuring analyzers, see this section of the reference documentation.

RESTサービスに全文検索機能を追加

既存の LibraryResource に、SearchSession をインジェクションするだけです:

    @Inject
    SearchSession searchSession; (1)
1 Hibernate Search セッションをインジェクションします。このセッションは内部で EntityManager に依存しています。複数の永続化ユニットを持つアプリケーションではCDI修飾子 @io.quarkus.hibernate.orm.PersistenceUnit を使用して正しいユニットを選択することができます: CDI統合 を参照してください。

And then the magic begins. When we added annotations to our entities, we made them available for full text search; we can now query the index using the Hibernate Search DSL, simply by adding the following method (and a few imports):

    @GET
    @Path("author/search")
    @Transactional (1)
    public List<Author> searchAuthors(@RestQuery String pattern, (2)
            @RestQuery Optional<Integer> size) {
        return searchSession.search(Author.class) (3)
                .where(f ->
                    pattern == null || pattern.trim().isEmpty() ?
                        f.matchAll() : (4)
                        f.simpleQueryString()
                                .fields("firstName", "lastName", "books.title").matching(pattern) (5)
                )
                .sort(f -> f.field("lastName_sort").then().field("firstName_sort")) (6)
                .fetchHits(size.orElse(20)); (7)
    }
1 Important point: we need a transactional context for this method.
2 パラメーター名の繰り返しを避けるために org.jboss.resteasy.annotations.jaxrs.QueryParam アノテーションを使用します。
3 Author を検索していることを示しています。
4 述語を作成します。パターンが空の場合は matchAll() 述語を使用します。
5 有効なパターンがあれば、パターンにマッチする firstNamelastNamebooks.title フィールドに対する simpleQueryString() 述語を作成します。
6 結果のソート順を定義します。ここでは、姓でソートし、次に名でソートしています。ソートには作成した特定のフィールドを使用していることに注意してください。
7 size で指定した数の一致度が高いものをフェッチします。デフォルトでは 20 です。もちろんページングもサポートしています。

Hibernate Search DSLはElasticsearchの述語(match、range、nested、phrase、spatial…​)の重要なサブセットをサポートしています。オートコンプリートを使ってDSLをご自由にお試しください。

When that’s not enough, you can always fall back to defining a predicate using JSON directly.

Automatic data initialization

このデモの目的のために、初期データセットをインポートしてみましょう。

Let’s create a src/main/resources/import.sql file with the following content (we’ll reference it in configuration later):

INSERT INTO author(id, firstname, lastname) VALUES (1, 'John', 'Irving');
INSERT INTO author(id, firstname, lastname) VALUES (2, 'Paul', 'Auster');
ALTER SEQUENCE author_seq RESTART WITH 3;

INSERT INTO book(id, title, author_id) VALUES (1, 'The World According to Garp', 1);
INSERT INTO book(id, title, author_id) VALUES (2, 'The Hotel New Hampshire', 1);
INSERT INTO book(id, title, author_id) VALUES (3, 'The Cider House Rules', 1);
INSERT INTO book(id, title, author_id) VALUES (4, 'A Prayer for Owen Meany', 1);
INSERT INTO book(id, title, author_id) VALUES (5, 'Last Night in Twisted River', 1);
INSERT INTO book(id, title, author_id) VALUES (6, 'In One Person', 1);
INSERT INTO book(id, title, author_id) VALUES (7, 'Avenue of Mysteries', 1);
INSERT INTO book(id, title, author_id) VALUES (8, 'The New York Trilogy', 2);
INSERT INTO book(id, title, author_id) VALUES (9, 'Mr. Vertigo', 2);
INSERT INTO book(id, title, author_id) VALUES (10, 'The Brooklyn Follies', 2);
INSERT INTO book(id, title, author_id) VALUES (11, 'Invisible', 2);
INSERT INTO book(id, title, author_id) VALUES (12, 'Sunset Park', 2);
INSERT INTO book(id, title, author_id) VALUES (13, '4 3 2 1', 2);
ALTER SEQUENCE book_seq RESTART WITH 14;

Because this data above will be inserted into the database without Hibernate Search’s knowledge, it won’t be indexed — unlike upcoming updates coming through Hibernate ORM operations, which will be synchronized automatically to the full text index.

In our existing LibraryResource, let’s add the following content (and a few imports) to index that initial data:

If you don’t import data manually in the database, you don’t need this: the mass indexer should then only be used when you change your indexing configuration (adding a new field, changing an analyzer’s configuration…​) and you want the new configuration to be applied to your existing data.

    @Inject
    SearchMapping searchMapping; (1)

    void onStart(@Observes StartupEvent ev) throws InterruptedException { (2)
        // only reindex if we imported some content
        if (Book.count() > 0) {
            searchMapping.scope(Object.class) (3)
                    .massIndexer() (4)
                    .startAndWait(); (5)
        }
    }
1 Inject a Hibernate Search SearchMapping, which relies on the EntityManagerFactory under the hood. Applications with multiple persistence units can use the CDI qualifier @io.quarkus.hibernate.orm.PersistenceUnit to select the right one: see CDI統合.
2 Add a method that will get executed on application startup.
3 Create a "search scope" targeting all indexed entity types that extend Object — that is, every single indexed entity types (Author and Book).
4 Create an instance of Hibernate Search’s mass indexer, which allows indexing a lot of data efficiently (you can fine tune it for better performance).
5 Start the mass indexer and wait for it to finish.

アプリケーションの設定

いつものように、Quarkusの設定ファイル( application.properties )ですべての設定を行うことができます。

以下の内容の src/main/resources/import.sql ファイルを作成してみましょう:

quarkus.ssl.native=false (1)

quarkus.datasource.db-kind=postgresql (2)

quarkus.hibernate-orm.sql-load-script=import.sql (3)

quarkus.hibernate-search-orm.elasticsearch.version=8 (4)
quarkus.hibernate-search-orm.indexing.plan.synchronization.strategy=sync (5)

%prod.quarkus.datasource.jdbc.url=jdbc:postgresql://localhost/quarkus_test (6)
%prod.quarkus.datasource.username=quarkus_test
%prod.quarkus.datasource.password=quarkus_test
%prod.quarkus.hibernate-orm.database.generation=create
%prod.quarkus.hibernate-search-orm.elasticsearch.hosts=localhost:9200 (6)
1 SSLは使用しないので、ネイティブ実行可能ファイルをよりコンパクトにするために無効にしています。
2 それでは、PostgreSQLのデータソースを作成してみましょう。
3 We load some initial data on startup (see Automatic data initialization).
4 使用するElasticsearchのバージョンをHibernate Searchに伝える必要があります。Elasticsearchのバージョンによってマッピング構文に大きな違いがあるので重要です。マッピングは起動時間を短縮するためにビルド時に作成されるので、Hibernate Searchはクラスタに接続してバージョンを自動的に検出することができません。なお、OpenSearchの場合は、バージョンの前に opensearch: を付ける必要があります; OpenSearch対応を参照してください。
5 これは、エンティティが検索可能になるのを待ってから書き込みが完了したとみなすことを意味します。本番環境では、デフォルトの write-sync の方がパフォーマンスが高くなります。テスト時にはエンティティがすぐに検索可能になる必要があるため sync を使用することが特に重要です。
6 For development and tests, we rely on Dev Services, which means Quarkus will start a PostgreSQL database and Elasticsearch cluster automatically. In production mode, however, we will want to start a PostgreSQL database and Elasticsearch cluster manually, which is why we provide Quarkus with this connection info in the prod profile (%prod. prefix).

Because we rely on Dev Services, the database and Elasticsearch schema will automatically be dropped and re-created on each application startup in tests and dev mode (unless quarkus.hibernate-search-orm.schema-management.strategy is set explicitly).

何らかの理由でDev Servicesを利用できない場合は以下のプロパティを設定することで、同様の動作をさせることができます:

%dev,test.quarkus.hibernate-orm.database.generation=drop-and-create
%dev,test.quarkus.hibernate-search-orm.schema-management.strategy=drop-and-create
For more information about configuration of the Hibernate Search ORM extension, refer to the Configuration Reference.

フロントエンドの作成

それでは、 LibraryResource を操作するための簡単なWebページを追加してみましょう。Quarkusは、 META-INF/resources ディレクトリの下にある静的リソースを自動的に提供します。 src/main/resources/META-INF/resources ディレクトリで、既存の index.html ファイルを、この index.html ファイルの内容で上書きしてください。

アプリケーションで遊ぶ時間

これで、REST サービスと対話できるようになりました:

  • 次のようにQuarkusアプリケーションを起動します:

    コマンドラインインタフェース
    quarkus dev
    Maven
    ./mvnw quarkus:dev
    Gradle
    ./gradlew --console=plain quarkusDev
  • ブラウザで http://localhost:8080/ を開きます

  • 著者や書名の検索してください(いくつかのデータを入れておきました)

  • 新しい著者や書籍を作成し、それらを検索することもできます

ご覧のように、すべての更新が自動的にElasticsearchクラスタに同期されます。

ネイティブ実行可能ファイルの構築

以下のコマンドでネイティブの実行可能ファイルをビルドすることができます。

コマンドラインインタフェース
quarkus build --native
Maven
./mvnw install -Dnative
Gradle
./gradlew build -Dquarkus.package.type=native

ネイティブ実行可能ファイルのコンパイルと同様に、この操作は大量のメモリーを消費します。

ネイティブ実行可能ファイルをビルドしている間は2つのコンテナーを停止して、ビルドが終わったら再度起動した方が安全かもしれません。

Running the native executable is as simple as executing ./target/hibernate-search-orm-elasticsearch-quickstart-1.0.0-SNAPSHOT-runner.

その後、ブラウザで http://localhost:8080/ を開きアプリケーションを使用します。

起動がいつもより少し遅いのは、起動時に毎回データベーススキーマとElasticsearchマッピングを落として再作成しているのが原因です。また、いくつかのデータを注入し、マスインデクサーを実行しています。

In a real life application, it is obviously something you won’t do on every startup.

Dev Services (Configuration Free Datastores)

Quarkus supports a feature called Dev Services that allows you to start various containers without any config.

In the case of Elasticsearch this support extends to the default Elasticsearch connection. What that means practically, is that if you have not configured quarkus.hibernate-search-orm.elasticsearch.hosts, Quarkus will automatically start an Elasticsearch container when running tests or in dev mode, and automatically configure the connection.

アプリケーションの本番環境版を実行する場合、Elasticsearch接続は通常通り設定する必要があります。したがって、 application.properties に本番環境版のデータベース設定を含め、Dev Servicesを引き続き使用したい場合は、 %prod. プロファイルを使用してElasticsearch設定を定義することをお勧めします。

Dev Services for Elasticsearchは現時点では複数のクラスタを同時に起動することができず、デフォルトの永続化ユニットのデフォルトのバックエンドでのみ動作します:名前付き永続化ユニットや名前付きバックエンドはDev Services for Elasticsearchを利用することができません。

詳細については、 Dev Services for Elasticsearch ガイド をご覧ください。

Programmatic mapping

If, for some reason, adding Hibernate Search annotations to entities is not possible, mapping can be applied programmatically instead. Programmatic mapping is configured through the ProgrammaticMappingConfigurationContext that is exposed via a mapping configurer (HibernateOrmSearchMappingConfigurer).

A mapping configurer (HibernateOrmSearchMappingConfigurer) allows much more than just programmatic mapping capabilities. It also allows configuring annotation mapping, bridges, and more.

Below is an example of a mapping configurer that applies programmatic mapping:

package org.acme.hibernate.search.elasticsearch.config;

import org.hibernate.search.mapper.orm.mapping.HibernateOrmMappingConfigurationContext;
import org.hibernate.search.mapper.orm.mapping.HibernateOrmSearchMappingConfigurer;
import org.hibernate.search.mapper.pojo.mapping.definition.programmatic.TypeMappingStep;

import io.quarkus.hibernate.search.orm.elasticsearch.SearchExtension;

@SearchExtension (1)
public class CustomMappingConfigurer implements HibernateOrmSearchMappingConfigurer {

	@Override
    public void configure(HibernateOrmMappingConfigurationContext context) {
        TypeMappingStep type = context.programmaticMapping()    (2)
            .type(SomeIndexedEntity.class);                     (3)
        type.indexed()                                          (4)
            .index(SomeIndexedEntity.INDEX_NAME);               (5)
        type.property("id").documentId();                       (6)
        type.property("text").fullTextField();                  (7)
    }
}
1 Annotate the configurer implementation with the @SearchExtension qualifier to tell Quarkus it should be used by Hibernate Search in the default persistence unit.

The annotation can also target a specific persistence unit (@SearchExtension(persistenceUnit = "nameOfYourPU")).

2 Access the programmatic mapping context.
3 Create mapping step for the SomeIndexedEntity entity.
4 Define the SomeIndexedEntity entity as indexed.
5 Provide an index name to be used for the SomeIndexedEntity entity.
6 Define the document id property.
7 Define a full-text search field for the text property.

Alternatively, if for some reason you can’t or don’t want to annotate your mapping configurer with @SearchExtension, you can simply annotate it with @Dependent @Named("myMappingConfigurer") and then reference it from configuration properties:

quarkus.hibernate-search-orm.mapping.configurer=bean:myMappingConfigurer

OpenSearch対応

Hibernate Searchは ElasticsearchOpenSearchの両方に対応していますが、デフォルトではElasticsearchクラスタとの連携を前提としています。

To have Hibernate Search work with an OpenSearch cluster instead, prefix the configured version with opensearch:, as shown below.

quarkus.hibernate-search-orm.elasticsearch.version=opensearch:2.11

その他の設定オプションやAPIはElasticsearchの場合と全く同じです。

You can find more information about compatible distributions and versions of Elasticsearch in this section of Hibernate Search’s reference documentation.

複数の永続化ユニット

複数の永続化ユニットを設定

Hibernate ORM エクステンションでは、 複数の永続化ユニットを設定することができ、それぞれが独自のデータソースと設定を持つことができます。

複数の永続化ユニットを宣言する場合は、それぞれの永続化ユニットに対して個別にHibernate Searchを設定することになります。

quarkus.hibernate-search-orm. 名前空間のルートにあるプロパティは、デフォルトの永続化ユニットを定義します。たとえば、次のスニペットでは、デフォルトのデータソースとデフォルトの永続化ユニットを定義し、その永続化ユニットのElasticsearchホストを es1.mycompany.com:9200 に設定しています。

quarkus.datasource.db-kind=h2
quarkus.datasource.jdbc.url=jdbc:h2:mem:default;DB_CLOSE_DELAY=-1

quarkus.hibernate-search-orm.elasticsearch.hosts=es1.mycompany.com:9200
quarkus.hibernate-search-orm.elasticsearch.version=8

マップベースのアプローチで名前付きの永続化ユニットを構成することも可能です:

quarkus.datasource."users".db-kind=h2 (1)
quarkus.datasource."users".jdbc.url=jdbc:h2:mem:users;DB_CLOSE_DELAY=-1

quarkus.datasource."inventory".db-kind=h2 (2)
quarkus.datasource."inventory".jdbc.url=jdbc:h2:mem:inventory;DB_CLOSE_DELAY=-1

quarkus.hibernate-orm."users".datasource=users (3)
quarkus.hibernate-orm."users".packages=org.acme.model.user

quarkus.hibernate-orm."inventory".datasource=inventory (4)
quarkus.hibernate-orm."inventory".packages=org.acme.model.inventory

quarkus.hibernate-search-orm."users".elasticsearch.hosts=es1.mycompany.com:9200 (5)
quarkus.hibernate-search-orm."users".elasticsearch.version=8

quarkus.hibernate-search-orm."inventory".elasticsearch.hosts=es2.mycompany.com:9200 (6)
quarkus.hibernate-search-orm."inventory".elasticsearch.version=8
1 users という名前のデータソースを定義します。
2 inventory という名前のデータソースを定義します。
3 users データソースを指す users という名前の永続化ユニットを定義します。
4 inventory データソースを指す inventory という名前の永続化ユニットを定義します。
5 users 永続化ユニットにHibernate Searchを設定し、その永続化ユニットのElasticsearchホストを es1.mycompany.com:9200 に設定します。
6 inventory 永続化ユニットにHibernate Searchを設定し、その永続化ユニットのElasticsearchホストを es2.mycompany.com:9200 に設定します。

モデルクラスの永続化ユニットへのアタッチメント

各永続化ユニットについて、Hibernate Searchは、その永続化ユニットにアタッチされているインデックス付きエンティティのみを考慮します。エンティティは、 Hibernate ORMエクステンションを設定することで、永続化ユニットにアタッチされます。

CDI統合

Injecting entry points

CDI を使用して、Hibernate Search のメインエントリーポイント SearchSessionSearchMapping をインジェクションすることができます:

@Inject
SearchSession searchSession;

これは、デフォルトの永続化ユニットの SearchSession をインジェクションします。

名前付き永続化ユニット(この例では users )の SearchSession を注入するには、修飾子を追加するだけです。

@Inject
@PersistenceUnit("users") (1)
SearchSession searchSession;
1 これは @io.quarkus.hibernate.orm.PersistenceUnit アノテーションです。

全く同じメカニズムを使って、名前付き永続化ユニットの SearchMapping をインジェクションすることができます:

@Inject
@PersistenceUnit("users")
SearchMapping searchMapping;

Plugging in custom components

The Quarkus extension for Hibernate Search with Hibernate ORM will automatically inject components annotated with @SearchExtension into Hibernate Search.

The annotation can optionally target a specific persistence unit (@SearchExtension(persistenceUnit = "nameOfYourPU")), backend (@SearchExtension(backend = "nameOfYourBackend")), index (@SearchExtension(index = "nameOfYourIndex")), or a combination of those (@SearchExtension(persistenceUnit = "nameOfYourPU", backend = "nameOfYourBackend", index = "nameOfYourIndex")), when it makes sense for the type of the component being injected.

This feature is available for the following component types:

org.hibernate.search.engine.reporting.FailureHandler

A component that should be notified of any failure occurring in a background process (mainly index operations).

Scope: one per persistence unit.

org.hibernate.search.mapper.orm.mapping.HibernateOrmSearchMappingConfigurer

A component used to configure the Hibernate Search mapping, in particular programmatically.

Scope: one or more per persistence unit.

See this section of this guide for more information.

org.hibernate.search.mapper.pojo.work.IndexingPlanSynchronizationStrategy

A component used to configure how to synchronize between application threads and indexing.

Scope: one per persistence unit.

Can also be set to built-in implementations through quarkus.hibernate-search-orm.indexing.plan.synchronization.strategy.

org.hibernate.search.backend.elasticsearch.analysis.ElasticsearchAnalysisConfigurer

A component used to configure full text analysis (e.g. analyzers, normalizers).

Scope: one or more per backend.

See this section of this guide for more information.

org.hibernate.search.backend.elasticsearch.index.layout.IndexLayoutStrategy

A component used to configure the Elasticsearch layout: index names, index aliases, …​

Scope: one per backend.

Can also be set to built-in implementations through quarkus.hibernate-search-orm.elasticsearch.layout.strategy.

オフライン起動

デフォルトではHibernate Search は起動時に Elasticsearch クラスタにいくつかのリクエストを送信します。Hibernate Searchの起動時にElasticsearchクラスタが稼働していない場合は起動失敗の原因となります。

これに対処するためには起動時にリクエストを送信しないようにHibernate Searchを設定します:

もちろん、この構成でも、Elasticsearchクラスタにアクセスできるようになるまでは、Hibernate Searchはインデックスを作成したり、検索クエリを実行したりすることはできません。

quarkus.hibernate-search-orm.schema-management.strategynone に設定してスキーマの自動作成を無効にした場合、アプリケーションがエンティティの永続化/更新や検索リクエストの実行を開始する前に、手動でスキーマを作成する必要があります。

アウトボックスポーリングによる調整

アウトボックスポーリングによる調整は、プレビューとみなされます。

プレビュー版 では、後方互換性やエコシステムでの存在は保証されていません。具体的な改善のためには、設定やAPI、あるいはストレージのフォーマットを変更する必要があるかもしれませんが、 安定化 に向けた計画は進行中です。ご意見・ご感想は、 メーリングリストGitHubのイシュートラッカーでお寄せください。

While it’s technically possible to use Hibernate Search and Elasticsearch in distributed applications, by default they suffer from a few limitations.

これらはHibernate Searchがデフォルトではスレッドやアプリケーションノード間の調整を行わないことによる制限です。

In order to get rid of these limitations, you can use the outbox-polling coordination strategy. This strategy creates an outbox table in the database to push entity change events to, and relies on a background processor to consume these events and perform indexing.

outbox-polling 調整ストラテジーを有効にするには、追加のエクステンションが必要です:

コマンドラインインタフェース
quarkus extension add hibernate-search-orm-outbox-polling
Maven
./mvnw quarkus:add-extension -Dextensions='hibernate-search-orm-outbox-polling'
Gradle
./gradlew addExtension --extensions='hibernate-search-orm-outbox-polling'

Once the extension is there, you will need to explicitly select the outbox-polling strategy by setting quarkus.hibernate-search-orm.coordination.strategy to outbox-polling.

最後に、Hibernate Searchによって追加されたHibernate ORMエンティティ(アウトボックスとエージェントを表す)が、データベース内に対応するテーブル/シーケンスを持っていることを確認する必要があります:

上記の作業が完了したら、アウトボックスを使ったHibernate Searchを使用する準備が整いました。コードを変更せず、アプリケーションを起動するだけで大丈夫です。複数のアプリケーションが同じデータベースに接続されていることを自動的に検出し、それに応じてインデックスの更新が調整されます。

Hibernate Searchは、 outbox-polling 調整ストラテジーを使用してもしなくても、ほとんど同じ動作をします。アプリケーションコード(エンティティの永続化、検索など)を変更する必要はありません。

しかし重要な違いが1つあります。インデックスの更新は必然的に非同期で行われ、 いつかは 行われることが保証されますが、すぐには行われません。

This means in particular that the configuration property quarkus.hibernate-search-orm.indexing.plan.synchronization.strategy cannot be set when using the outbox-polling coordination strategy: Hibernate Search will always behave as if this property was set to write-sync (the default).

この動作は、Elasticsearchの Near real-time searchと一致しており、連携が無効な場合でもHibernate Searchを使用する場合は推奨されています。

For more information about coordination in Hibernate Search, see this section of the reference documentation.

調整に関連する設定オプションの詳細については、 アウトボックスポーリングとの連携の設定 を参照してください。

AWSのリクエストの署名

Amazonが管理するElasticsearchサービスを使用する必要がある場合、リクエストの署名を含む独自の認証方法を必要になります。

Hibernate SearchでAWSリクエストの署名を有効にするには、専用のエクステンションをプロジェクトに追加して設定します。

Management endpoint

Hibernate Search’s management endpoint is considered preview.

プレビュー版 では、後方互換性やエコシステムでの存在は保証されていません。具体的な改善のためには、設定やAPI、あるいはストレージのフォーマットを変更する必要があるかもしれませんが、 安定化 に向けた計画は進行中です。ご意見・ご感想は、 メーリングリストGitHubのイシュートラッカーでお寄せください。

The Hibernate Search extension provides an HTTP endpoint to reindex your data through the management interface. By default, this endpoint is not available. It can be enabled through configuration properties as shown below.

quarkus.management.enabled=true (1)
quarkus.hibernate-search-orm.management.enabled=true (2)
1 Enable the management interface.
2 Enable Hibernate Search specific management endpoints.

Once the management is enabled, data can be re-indexed via /q/hibernate-search/reindex, where /q is the default management root path and /hibernate-search is the default Hibernate Search root management path. It (/hibernate-search) can be changed via configuration property as shown below.

quarkus.hibernate-search-orm.management.root-path=custom-root-path (1)
1 Use a custom custom-root-path path for Hibernate Search’s management endpoint. If the default management root path is used then the reindex path becomes /q/custom-root-path/reindex.

This endpoint accepts POST requests with application/json content type only. All indexed entities will be re-indexed if an empty request body is submitted. If only a subset of entities must be re-indexed or if there is a need to have a custom configuration of the underlying mass indexer then this information can be passed through the request body as shown below.

{
  "filter": {
    "types": ["EntityName1", "EntityName2", "EntityName3", ...], (1)
  },
  "massIndexer":{
    "typesToIndexInParallel": 1, (2)
  }
}
1 An array of entity names that should be re-indexed. If unspecified or empty, all entity types will be re-indexed.
2 Sets the number of entity types to be indexed in parallel.

The full list of possible filters and available mass indexer configurations is presented in the example below.

{
  "filter": { (1)
    "types": ["EntityName1", "EntityName2", "EntityName3", ...], (2)
    "tenants": ["tenant1", "tenant2", ...] (3)
  },
  "massIndexer":{ (4)
    "typesToIndexInParallel": 1, (5)
    "threadsToLoadObjects": 6,  (6)
    "batchSizeToLoadObjects": 10, (7)
    "cacheMode": "IGNORE", (8)
    "mergeSegmentsOnFinish": false, (9)
    "mergeSegmentsAfterPurge": true, (10)
    "dropAndCreateSchemaOnStart": false, (11)
    "purgeAllOnStart": true, (12)
    "idFetchSize": 100, (13)
    "transactionTimeout": 100000, (14)
  }
}
1 Filter object that allows to limit the scope of reindexing.
2 An array of entity names that should be re-indexed. If unspecified or empty, all entity types will be re-indexed.
3 An array of tenant ids, in case of multi-tenancy. If unspecified or empty, all tenants will be re-indexed.
4 Mass indexer configuration object.
5 Sets the number of entity types to be indexed in parallel.
6 Sets the number of threads to be used to load the root entities.
7 Sets the batch size used to load the root entities.
8 Sets the cache interaction mode for the data loading tasks.
9 Whether each index is merged into a single segment after indexing.
10 Whether each index is merged into a single segment after the initial index purge, just before indexing.
11 Whether the indexes and their schema (if they exist) should be dropped and re-created before indexing.
12 Whether all entities are removed from the indexes before indexing.
13 Specifies the fetch size to be used when loading primary keys if objects to be indexed.
14 Specifies the timeout of transactions for loading ids and entities to be re-indexed.

Note all the properties in the json are optional, and only those that are needed should be used.

For more detailed information on mass indexer configuration see the corresponding section of the Hibernate Search reference documentation.

Submitting the reindexing request will trigger indexing in the background. Mass indexing progress will appear in the application logs. For testing purposes, it might be useful to know when the indexing finished. Adding wait_for=finished query parameter to the URL will result in the management endpoint returning a chunked response that will report when the indexing starts and then when it is finished.

When working with multiple persistence units, the name of the persistence unit to reindex can be supplied through the persistence_unit query parameter: /q/hibernate-search/reindex?persistence_unit=non-default-persistence-unit.

参考資料

If you are interested in learning more about Hibernate Search 6, the Hibernate team publishes an extensive reference documentation.

FAQ

なぜElasticsearchだけなのか?

Hibernate SearchはLuceneバックエンドとElasticsearchバックエンドの両方をサポートしています。

Quarkusとマイクロサービスを構築するという文脈では、後者の方がより理にかなっていると考えました。そこで、私たちは後者に力を入れました。

今のところ、QuarkusでLuceneバックエンドをサポートする予定はありません。

Configuration Reference for Hibernate Search with Hibernate ORM

主な構成

ビルド時に固定される構成プロパティ - 他のすべての構成プロパティは実行時にオーバーライド可能

Configuration property

デフォルト

Whether Hibernate Search is enabled during the build.

If Hibernate Search is disabled during the build, all processing related to Hibernate Search will be skipped, but it will not be possible to activate Hibernate Search at runtime: quarkus.hibernate-search-orm.active will default to false and setting it to true will lead to an error.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ENABLED

Show more

boolean

true

A bean reference to a component that should be notified of any failure occurring in a background process (mainly index operations).

The referenced bean must implement FailureHandler.

Instead of setting this configuration property, you can simply annotate your custom FailureHandler implementation with @SearchExtension and leave the configuration property unset: Hibernate Search will use the annotated implementation automatically. See this section for more information.

If this configuration property is set, it takes precedence over any @SearchExtension annotation.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_BACKGROUND_FAILURE_HANDLER

Show more

string

The strategy to use for coordinating between threads or even separate instances of the application, in particular in automatic indexing.

See coordination for more information.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_STRATEGY

Show more

string

none

One or more bean references to the component(s) used to configure the Hibernate Search mapping, in particular programmatically.

The referenced beans must implement HibernateOrmSearchMappingConfigurer.

See Programmatic mapping for an example on how mapping configurers can be used to apply programmatic mappings.

Instead of setting this configuration property, you can simply annotate your custom HibernateOrmSearchMappingConfigurer implementations with @SearchExtension and leave the configuration property unset: Hibernate Search will use the annotated implementation automatically. See this section for more information.

If this configuration property is set, it takes precedence over any @SearchExtension annotation.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_MAPPING_CONFIGURER

Show more

list of string

Whether Hibernate Search should be active for this persistence unit at runtime.

If Hibernate Search is not active, it won’t index Hibernate ORM entities, and accessing the SearchMapping/SearchSession of the relevant persistence unit for search or other operation will not be possible.

Note that if Hibernate Search is disabled (i.e. quarkus.hibernate-search-orm.enabled is set to false), it won’t be active for any persistence unit, and setting this property to true will fail.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ACTIVE

Show more

boolean

'true' if Hibernate Search is enabled; 'false' otherwise

The schema management strategy, controlling how indexes and their schema are created, updated, validated or dropped on startup and shutdown.

Available values:

Strategy

Definition

none

Do nothing: assume that indexes already exist and that their schema matches Hibernate Search’s expectations.

validate

Validate that indexes exist and that their schema matches Hibernate Search’s expectations.

If it does not, throw an exception, but make no attempt to fix the problem.

create

For indexes that do not exist, create them along with their schema.

For indexes that already exist, do nothing: assume that their schema matches Hibernate Search’s expectations.

create-or-validate (default unless using Dev Services)

For indexes that do not exist, create them along with their schema.

For indexes that already exist, validate that their schema matches Hibernate Search’s expectations.

If it does not, throw an exception, but make no attempt to fix the problem.

create-or-update

For indexes that do not exist, create them along with their schema.

For indexes that already exist, validate that their schema matches Hibernate Search’s expectations; if it does not match expectations, try to update it.

This strategy is unfit for production environments, due to several important limitations, but can be useful when developing.

drop-and-create

For indexes that do not exist, create them along with their schema.

For indexes that already exist, drop them, then create them along with their schema.

drop-and-create-and-drop (default when using Dev Services)

For indexes that do not exist, create them along with their schema.

For indexes that already exist, drop them, then create them along with their schema.

Also, drop indexes and their schema on shutdown.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_SCHEMA_MANAGEMENT_STRATEGY

Show more

SchemaManagementStrategyName

drop-and-create-and-drop when using Dev Services; create-or-validate otherwise

The strategy to use when loading entities during the execution of a search query.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_QUERY_LOADING_CACHE_LOOKUP_STRATEGY

Show more

skip, persistence-context, persistence-context-then-second-level-cache

skip

The fetch size to use when loading entities during the execution of a search query.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_QUERY_LOADING_FETCH_SIZE

Show more

int

100

How to synchronize between application threads and indexing, in particular when relying on (implicit) listener-triggered indexing on entity change, but also when using a SearchIndexingPlan explicitly.

Defines how complete indexing should be before resuming the application thread after a database transaction is committed.

Indexing synchronization is only relevant when coordination is disabled (which is the default).

With the outbox-polling coordination strategy, indexing happens in background threads and is always asynchronous; the behavior is equivalent to the write-sync synchronization strategy.

Available values:

Strategy

Throughput

Guarantees when the application thread resumes

Changes applied

Changes safe from crash/power loss

Changes visible on search

async

Best

write-sync (default)

Medium

read-sync

Medium to worst

sync

Worst

This property also accepts a bean reference to a custom implementations of IndexingPlanSynchronizationStrategy.

Instead of setting this configuration property, you can simply annotate your custom IndexingPlanSynchronizationStrategy implementation with @SearchExtension and leave the configuration property unset: Hibernate Search will use the annotated implementation automatically. See this section for more information.

If this configuration property is set, it takes precedence over any @SearchExtension annotation.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_INDEXING_PLAN_SYNCHRONIZATION_STRATEGY

Show more

string

write-sync

An exhaustive list of all tenant identifiers that may be used by the application when multi-tenancy is enabled.

Mainly useful when using the {@code outbox-polling} coordination strategy, since it involves setting up one background processor per tenant.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_MULTI_TENANCY_TENANT_IDS

Show more

list of string

Root path for reindexing endpoints. This value will be resolved as a path relative to ${quarkus.management.root-path}.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_MANAGEMENT_ROOT_PATH

Show more

string

hibernate-search/

If management interface is turned on the reindexing endpoints will be published under the management interface. This property allows to enable this functionality by setting it to `true.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_MANAGEMENT_ENABLED

Show more

boolean

false

Configuration for backends

デフォルト

The version of Elasticsearch used in the cluster.

As the schema is generated without a connection to the server, this item is mandatory.

It doesn’t have to be the exact version (it can be 7 or 7.1 for instance) but it has to be sufficiently precise to choose a model dialect (the one used to generate the schema) compatible with the protocol dialect (the one used to communicate with Elasticsearch).

There’s no rule of thumb here as it depends on the schema incompatibilities introduced by Elasticsearch versions. In any case, if there is a problem, you will have an error when Hibernate Search tries to connect to the cluster.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_VERSION

Show more

ElasticsearchVersion

A bean reference to the component used to configure the Elasticsearch layout: index names, index aliases, …​

The referenced bean must implement IndexLayoutStrategy.

Available built-in implementations:

simple

The default, future-proof strategy: if the index name in Hibernate Search is myIndex, this strategy will create an index named myindex-000001, an alias for write operations named myindex-write, and an alias for read operations named myindex-read.

no-alias

A strategy without index aliases, mostly useful on legacy clusters: if the index name in Hibernate Search is myIndex, this strategy will create an index named myindex, and will not use any alias.

Instead of setting this configuration property, you can simply annotate your custom IndexLayoutStrategy implementation with @SearchExtension and leave the configuration property unset: Hibernate Search will use the annotated implementation automatically. See this section for more information.

If this configuration property is set, it takes precedence over any @SearchExtension annotation.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_LAYOUT_STRATEGY

Show more

string

Path to a file in the classpath holding custom index settings to be included in the index definition when creating an Elasticsearch index.

The provided settings will be merged with those generated by Hibernate Search, including analyzer definitions. When analysis is configured both through an analysis configurer and these custom settings, the behavior is undefined; it should not be relied upon.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_SCHEMA_MANAGEMENT_SETTINGS_FILE

Show more

string

Path to a file in the classpath holding a custom index mapping to be included in the index definition when creating an Elasticsearch index.

The file does not need to (and generally shouldn’t) contain the full mapping: Hibernate Search will automatically inject missing properties (index fields) in the given mapping.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_SCHEMA_MANAGEMENT_MAPPING_FILE

Show more

string

One or more bean references to the component(s) used to configure full text analysis (e.g. analyzers, normalizers).

The referenced beans must implement ElasticsearchAnalysisConfigurer.

See Setting up the analyzers for more information.

Instead of setting this configuration property, you can simply annotate your custom ElasticsearchAnalysisConfigurer implementations with @SearchExtension and leave the configuration property unset: Hibernate Search will use the annotated implementation automatically. See this section for more information.

If this configuration property is set, it takes precedence over any @SearchExtension annotation.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_ANALYSIS_CONFIGURER

Show more

list of string

list of string

localhost:9200

http, https

http

string

string

Duration

1S

Duration

30S

The timeout when executing a request to an Elasticsearch server.

This includes the time needed to wait for a connection to be available, send the request and read the response.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_REQUEST_TIMEOUT

Show more

Duration

int

20

int

10

boolean

false

Duration

10S

The size of the thread pool assigned to the backend.

Note that number is per backend, not per index. Adding more indexes will not add more threads.

As all operations happening in this thread-pool are non-blocking, raising its size above the number of processor cores available to the JVM will not bring noticeable performance benefit. The only reason to alter this setting would be to reduce the number of threads; for example, in an application with a single index with a single indexing queue, running on a machine with 64 processor cores, you might want to bring down the number of threads.

Defaults to the number of processor cores available to the JVM on startup.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_THREAD_POOL_SIZE

Show more

int

boolean

false

Whether Hibernate Search should check the version of the Elasticsearch cluster on startup.

Set to false if the Elasticsearch cluster may not be available on startup.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_VERSION_CHECK_ENABLED

Show more

boolean

true

green, yellow, red

yellow

Duration

10S

The number of indexing queues assigned to each index.

Higher values will lead to more connections being used in parallel, which may lead to higher indexing throughput, but incurs a risk of overloading Elasticsearch, i.e. of overflowing its HTTP request buffers and tripping circuit breakers, leading to Elasticsearch giving up on some request and resulting in indexing failures.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXING_QUEUE_COUNT

Show more

int

10

The size of indexing queues.

Lower values may lead to lower memory usage, especially if there are many queues, but values that are too low will reduce the likeliness of reaching the max bulk size and increase the likeliness of application threads blocking because the queue is full, which may lead to lower indexing throughput.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXING_QUEUE_SIZE

Show more

int

1000

The maximum size of bulk requests created when processing indexing queues.

Higher values will lead to more documents being sent in each HTTP request sent to Elasticsearch, which may lead to higher indexing throughput, but incurs a risk of overloading Elasticsearch, i.e. of overflowing its HTTP request buffers and tripping circuit breakers, leading to Elasticsearch giving up on some request and resulting in indexing failures.

Note that raising this number above the queue size has no effect, as bulks cannot include more requests than are contained in the queue.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXING_MAX_BULK_SIZE

Show more

int

100

Per-index configuration overrides

デフォルト

Path to a file in the classpath holding custom index settings to be included in the index definition when creating an Elasticsearch index.

The provided settings will be merged with those generated by Hibernate Search, including analyzer definitions. When analysis is configured both through an analysis configurer and these custom settings, the behavior is undefined; it should not be relied upon.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXES__INDEX_NAME__SCHEMA_MANAGEMENT_SETTINGS_FILE

Show more

string

Path to a file in the classpath holding a custom index mapping to be included in the index definition when creating an Elasticsearch index.

The file does not need to (and generally shouldn’t) contain the full mapping: Hibernate Search will automatically inject missing properties (index fields) in the given mapping.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXES__INDEX_NAME__SCHEMA_MANAGEMENT_MAPPING_FILE

Show more

string

One or more bean references to the component(s) used to configure full text analysis (e.g. analyzers, normalizers).

The referenced beans must implement ElasticsearchAnalysisConfigurer.

See Setting up the analyzers for more information.

Instead of setting this configuration property, you can simply annotate your custom ElasticsearchAnalysisConfigurer implementations with @SearchExtension and leave the configuration property unset: Hibernate Search will use the annotated implementation automatically. See this section for more information.

If this configuration property is set, it takes precedence over any @SearchExtension annotation.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXES__INDEX_NAME__ANALYSIS_CONFIGURER

Show more

list of string

green, yellow, red

yellow

Duration

10S

The number of indexing queues assigned to each index.

Higher values will lead to more connections being used in parallel, which may lead to higher indexing throughput, but incurs a risk of overloading Elasticsearch, i.e. of overflowing its HTTP request buffers and tripping circuit breakers, leading to Elasticsearch giving up on some request and resulting in indexing failures.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXES__INDEX_NAME__INDEXING_QUEUE_COUNT

Show more

int

10

The size of indexing queues.

Lower values may lead to lower memory usage, especially if there are many queues, but values that are too low will reduce the likeliness of reaching the max bulk size and increase the likeliness of application threads blocking because the queue is full, which may lead to lower indexing throughput.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXES__INDEX_NAME__INDEXING_QUEUE_SIZE

Show more

int

1000

The maximum size of bulk requests created when processing indexing queues.

Higher values will lead to more documents being sent in each HTTP request sent to Elasticsearch, which may lead to higher indexing throughput, but incurs a risk of overloading Elasticsearch, i.e. of overflowing its HTTP request buffers and tripping circuit breakers, leading to Elasticsearch giving up on some request and resulting in indexing failures.

Note that raising this number above the queue size has no effect, as bulks cannot include more requests than are contained in the queue.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_ELASTICSEARCH_INDEXES__INDEX_NAME__INDEXING_MAX_BULK_SIZE

Show more

int

100

期間フォーマットについて

To write duration values, use the standard java.time.Duration format. See the Duration#parse() Java API documentation for more information.

数字で始まる簡略化した書式を使うこともできます:

  • 数値のみの場合は、秒単位の時間を表します。

  • 数値の後に ms が続く場合は、ミリ秒単位の時間を表します。

その他の場合は、簡略化されたフォーマットが解析のために java.time.Duration フォーマットに変換されます:

  • 数値の後に hms が続く場合は、その前に PT が付けられます。

  • 数値の後に d が続く場合は、その前に P が付けられます。

Bean参照について

First, be aware that referencing beans in configuration properties is optional and, in fact, discouraged: you can achieve the same results by annotating your beans with @SearchExtension. See this section for more information.

If you really do want to reference beans using a string value in configuration properties know that string is parsed; here are the most common formats:

  • bean: の後に @Named CDI Beanの名前が続きます。例えば bean:myBean .

  • class: の後にクラスの完全修飾名を付けて、CDI Beanの場合は CDI を通して、そうでない場合はパブリックで引数なしのコンストラクタを通してインスタンス化されます。例えば class:com.mycompany.MyClass .

  • An arbitrary string referencing a built-in implementation. Available values are detailed in the documentation of each configuration property, such as async/read-sync/write-sync/sync for quarkus.hibernate-search-orm.indexing.plan.synchronization.strategy.

Other formats are also accepted, but are only useful for advanced use cases. See this section of Hibernate Search’s reference documentation for more information.

アウトボックスポーリングとの連携の設定

これらの設定プロパティには、追加のエクステンションが必要です。 アウトボックスポーリングによる調整 を参照してください。

ビルド時に固定される構成プロパティ - 他のすべての構成プロパティは、実行時にオーバーライド可能

Configuration property

タイプ

デフォルト

Whether the event processor is enabled, i.e. whether events will be processed to perform automatic reindexing on this instance of the application.

This can be set to false to disable event processing on some application nodes, for example to dedicate some nodes to HTTP request processing and other nodes to event processing.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_ENABLED

Show more

boolean

true

The total number of shards that will form a partition of the entity change events to process.

By default, sharding is dynamic and setting this property is not necessary.

If you want to control explicitly the number and assignment of shards, you must configure static sharding and then setting this property as well as the assigned shards (see shards.assigned) is necessary.

See this section of the reference documentation for more information about event processor sharding.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_SHARDS_TOTAL_COUNT

Show more

int

Among shards that will form a partition of the entity change events, the shards that will be processed by this application instance.

By default, sharding is dynamic and setting this property is not necessary.

If you want to control explicitly the number and assignment of shards, you must configure static sharding and then setting this property as well as the total shard count is necessary.

Shards are referred to by an index in the range [0, total_count - 1] (see shards.total-count). A given application node must be assigned at least one shard but may be assigned multiple shards by setting shards.assigned to a comma-separated list, e.g. 0,3.

See this section of the reference documentation for more information about event processor sharding.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_SHARDS_ASSIGNED

Show more

list of int

How long to wait for another query to the outbox events table after a query didn’t return any event.

Lower values will reduce the time it takes for a change to be reflected in the index, but will increase the stress on the database when there are no new events.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_POLLING_INTERVAL

Show more

Duration

0.100S

How long the event processor can poll for events before it must perform a "pulse", updating and checking registrations in the agents table.

The pulse interval must be set to a value between the polling interval and one third (1/3) of the expiration interval.

Low values (closer to the polling interval) mean less time wasted not processing events when a node joins or leaves the cluster, and reduced risk of wasting time not processing events because an event processor is incorrectly considered disconnected, but more stress on the database because of more frequent checks of the list of agents.

High values (closer to the expiration interval) mean more time wasted not processing events when a node joins or leaves the cluster, and increased risk of wasting time not processing events because an event processor is incorrectly considered disconnected, but less stress on the database because of less frequent checks of the list of agents.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_PULSE_INTERVAL

Show more

Duration

2S

How long an event processor "pulse" remains valid before considering the processor disconnected and forcibly removing it from the cluster.

The expiration interval must be set to a value at least 3 times larger than the pulse interval.

Low values (closer to the pulse interval) mean less time wasted not processing events when a node abruptly leaves the cluster due to a crash or network failure, but increased risk of wasting time not processing events because an event processor is incorrectly considered disconnected.

High values (much larger than the pulse interval) mean more time wasted not processing events when a node abruptly leaves the cluster due to a crash or network failure, but reduced risk of wasting time not processing events because an event processor is incorrectly considered disconnected.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_PULSE_EXPIRATION

Show more

Duration

30S

How many outbox events, at most, are processed in a single transaction.

Higher values will reduce the number of transactions opened by the background process and may increase performance thanks to the first-level cache (persistence context), but will increase memory usage and in extreme cases may lead to OutOfMemoryErrors.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_BATCH_SIZE

Show more

int

50

The timeout for transactions processing outbox events.

When this property is not set, Hibernate Search will use whatever default transaction timeout is configured in the JTA transaction manager, which may be too low for batch processing and lead to transaction timeouts when processing batches of events. If this happens, set a higher transaction timeout for event processing using this property.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_TRANSACTION_TIMEOUT

Show more

Duration

How long the event processor must wait before re-processing an event after its previous processing failed.

Use the value 0S to reprocess failed events as soon as possible, with no delay.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_EVENT_PROCESSOR_RETRY_DELAY

Show more

Duration

30S

How long to wait for another query to the agent table when actively waiting for event processors to suspend themselves.

Low values will reduce the time it takes for the mass indexer agent to detect that event processors finally suspended themselves, but will increase the stress on the database while the mass indexer agent is actively waiting.

High values will increase the time it takes for the mass indexer agent to detect that event processors finally suspended themselves, but will reduce the stress on the database while the mass indexer agent is actively waiting.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_MASS_INDEXER_POLLING_INTERVAL

Show more

Duration

0.100S

How long the mass indexer can wait before it must perform a "pulse", updating and checking registrations in the agent table.

The pulse interval must be set to a value between the polling interval and one third (1/3) of the expiration interval.

Low values (closer to the polling interval) mean reduced risk of event processors starting to process events again during mass indexing because a mass indexer agent is incorrectly considered disconnected, but more stress on the database because of more frequent updates of the mass indexer agent’s entry in the agent table.

High values (closer to the expiration interval) mean increased risk of event processors starting to process events again during mass indexing because a mass indexer agent is incorrectly considered disconnected, but less stress on the database because of less frequent updates of the mass indexer agent’s entry in the agent table.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_MASS_INDEXER_PULSE_INTERVAL

Show more

Duration

2S

How long an event processor "pulse" remains valid before considering the processor disconnected and forcibly removing it from the cluster.

The expiration interval must be set to a value at least 3 times larger than the pulse interval.

Low values (closer to the pulse interval) mean less time wasted with event processors not processing events when a mass indexer agent terminates due to a crash, but increased risk of event processors starting to process events again during mass indexing because a mass indexer agent is incorrectly considered disconnected.

High values (much larger than the pulse interval) mean more time wasted with event processors not processing events when a mass indexer agent terminates due to a crash, but reduced risk of event processors starting to process events again during mass indexing because a mass indexer agent is incorrectly considered disconnected.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_MASS_INDEXER_PULSE_EXPIRATION

Show more

Duration

30S

Configuration for persistence units

タイプ

デフォルト

Configuration for the mapping of entities used for outbox-polling coordination

タイプ

デフォルト

The database catalog to use for the agent table.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_AGENT_CATALOG

Show more

string

Default catalog configured in Hibernate ORM

The schema catalog to use for the agent table.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_AGENT_SCHEMA

Show more

string

Default catalog configured in Hibernate ORM

The name of the agent table.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_AGENT_TABLE

Show more

string

HSEARCH_AGENT

The UUID generator strategy used for the agent table.

Available strategies:

  • auto (the default) is the same as random which uses UUID#randomUUID().

  • time is an IP based strategy consistent with IETF RFC 4122.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_AGENT_UUID_GEN_STRATEGY

Show more

auto, random, time

auto

The name of the Hibernate ORM basic type used for representing an UUID in the outbox event table.

Refer to this section of the Hibernate ORM documentation to see the possible UUID representations.

Defaults to the special value default, which will result into one of char/binary depending on the database kind.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_AGENT_UUID_TYPE

Show more

string

char/binary depending on the database kind

The database catalog to use for the outbox event table.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_OUTBOX_EVENT_CATALOG

Show more

string

Default catalog configured in Hibernate ORM

The schema catalog to use for the outbox event table.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_OUTBOX_EVENT_SCHEMA

Show more

string

Default schema configured in Hibernate ORM

The name of the outbox event table.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_OUTBOX_EVENT_TABLE

Show more

string

HSEARCH_OUTBOX_EVENT

The UUID generator strategy used for the outbox event table.

Available strategies:

  • auto (the default) is the same as random which uses UUID#randomUUID().

  • time is an IP based strategy consistent with IETF RFC 4122.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_OUTBOX_EVENT_UUID_GEN_STRATEGY

Show more

auto, random, time

auto

The name of the Hibernate ORM basic type used for representing an UUID in the outbox event table.

Refer to this section of the Hibernate ORM documentation to see the possible UUID representations.

Defaults to the special value default, which will result into one of char/binary depending on the database kind.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_ENTITY_MAPPING_OUTBOX_EVENT_UUID_TYPE

Show more

string

char/binary depending on the database kind

Per-tenant configuration overrides

タイプ

デフォルト

Whether the event processor is enabled, i.e. whether events will be processed to perform automatic reindexing on this instance of the application.

This can be set to false to disable event processing on some application nodes, for example to dedicate some nodes to HTTP request processing and other nodes to event processing.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_ENABLED

Show more

boolean

true

The total number of shards that will form a partition of the entity change events to process.

By default, sharding is dynamic and setting this property is not necessary.

If you want to control explicitly the number and assignment of shards, you must configure static sharding and then setting this property as well as the assigned shards (see shards.assigned) is necessary.

See this section of the reference documentation for more information about event processor sharding.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_SHARDS_TOTAL_COUNT

Show more

int

Among shards that will form a partition of the entity change events, the shards that will be processed by this application instance.

By default, sharding is dynamic and setting this property is not necessary.

If you want to control explicitly the number and assignment of shards, you must configure static sharding and then setting this property as well as the total shard count is necessary.

Shards are referred to by an index in the range [0, total_count - 1] (see shards.total-count). A given application node must be assigned at least one shard but may be assigned multiple shards by setting shards.assigned to a comma-separated list, e.g. 0,3.

See this section of the reference documentation for more information about event processor sharding.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_SHARDS_ASSIGNED

Show more

list of int

How long to wait for another query to the outbox events table after a query didn’t return any event.

Lower values will reduce the time it takes for a change to be reflected in the index, but will increase the stress on the database when there are no new events.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_POLLING_INTERVAL

Show more

Duration

0.100S

How long the event processor can poll for events before it must perform a "pulse", updating and checking registrations in the agents table.

The pulse interval must be set to a value between the polling interval and one third (1/3) of the expiration interval.

Low values (closer to the polling interval) mean less time wasted not processing events when a node joins or leaves the cluster, and reduced risk of wasting time not processing events because an event processor is incorrectly considered disconnected, but more stress on the database because of more frequent checks of the list of agents.

High values (closer to the expiration interval) mean more time wasted not processing events when a node joins or leaves the cluster, and increased risk of wasting time not processing events because an event processor is incorrectly considered disconnected, but less stress on the database because of less frequent checks of the list of agents.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_PULSE_INTERVAL

Show more

Duration

2S

How long an event processor "pulse" remains valid before considering the processor disconnected and forcibly removing it from the cluster.

The expiration interval must be set to a value at least 3 times larger than the pulse interval.

Low values (closer to the pulse interval) mean less time wasted not processing events when a node abruptly leaves the cluster due to a crash or network failure, but increased risk of wasting time not processing events because an event processor is incorrectly considered disconnected.

High values (much larger than the pulse interval) mean more time wasted not processing events when a node abruptly leaves the cluster due to a crash or network failure, but reduced risk of wasting time not processing events because an event processor is incorrectly considered disconnected.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_PULSE_EXPIRATION

Show more

Duration

30S

How many outbox events, at most, are processed in a single transaction.

Higher values will reduce the number of transactions opened by the background process and may increase performance thanks to the first-level cache (persistence context), but will increase memory usage and in extreme cases may lead to OutOfMemoryErrors.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_BATCH_SIZE

Show more

int

50

The timeout for transactions processing outbox events.

When this property is not set, Hibernate Search will use whatever default transaction timeout is configured in the JTA transaction manager, which may be too low for batch processing and lead to transaction timeouts when processing batches of events. If this happens, set a higher transaction timeout for event processing using this property.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_TRANSACTION_TIMEOUT

Show more

Duration

How long the event processor must wait before re-processing an event after its previous processing failed.

Use the value 0S to reprocess failed events as soon as possible, with no delay.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__EVENT_PROCESSOR_RETRY_DELAY

Show more

Duration

30S

How long to wait for another query to the agent table when actively waiting for event processors to suspend themselves.

Low values will reduce the time it takes for the mass indexer agent to detect that event processors finally suspended themselves, but will increase the stress on the database while the mass indexer agent is actively waiting.

High values will increase the time it takes for the mass indexer agent to detect that event processors finally suspended themselves, but will reduce the stress on the database while the mass indexer agent is actively waiting.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__MASS_INDEXER_POLLING_INTERVAL

Show more

Duration

0.100S

How long the mass indexer can wait before it must perform a "pulse", updating and checking registrations in the agent table.

The pulse interval must be set to a value between the polling interval and one third (1/3) of the expiration interval.

Low values (closer to the polling interval) mean reduced risk of event processors starting to process events again during mass indexing because a mass indexer agent is incorrectly considered disconnected, but more stress on the database because of more frequent updates of the mass indexer agent’s entry in the agent table.

High values (closer to the expiration interval) mean increased risk of event processors starting to process events again during mass indexing because a mass indexer agent is incorrectly considered disconnected, but less stress on the database because of less frequent updates of the mass indexer agent’s entry in the agent table.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__MASS_INDEXER_PULSE_INTERVAL

Show more

Duration

2S

How long an event processor "pulse" remains valid before considering the processor disconnected and forcibly removing it from the cluster.

The expiration interval must be set to a value at least 3 times larger than the pulse interval.

Low values (closer to the pulse interval) mean less time wasted with event processors not processing events when a mass indexer agent terminates due to a crash, but increased risk of event processors starting to process events again during mass indexing because a mass indexer agent is incorrectly considered disconnected.

High values (much larger than the pulse interval) mean more time wasted with event processors not processing events when a mass indexer agent terminates due to a crash, but reduced risk of event processors starting to process events again during mass indexing because a mass indexer agent is incorrectly considered disconnected.

Environment variable: QUARKUS_HIBERNATE_SEARCH_ORM_COORDINATION_TENANTS__TENANT_ID__MASS_INDEXER_PULSE_EXPIRATION

Show more

Duration

30S

期間フォーマットについて

To write duration values, use the standard java.time.Duration format. See the Duration#parse() Java API documentation for more information.

数字で始まる簡略化した書式を使うこともできます:

  • 数値のみの場合は、秒単位の時間を表します。

  • 数値の後に ms が続く場合は、ミリ秒単位の時間を表します。

その他の場合は、簡略化されたフォーマットが解析のために java.time.Duration フォーマットに変換されます:

  • 数値の後に hms が続く場合は、その前に PT が付けられます。

  • 数値の後に d が続く場合は、その前に P が付けられます。

関連コンテンツ