Hibernate ORMとElasticsearch/OpenSearchでHibernate Searchを使用
Hibernate ORMベースのアプリケーションを持ってますか?フル機能の全文検索をユーザーに提供したいですか?あなたは正しいドキュメントを読んでいます。
このガイドでは、Hibernate Search を使用して、エンティティを Elasticsearch または OpenSearch クラスタに瞬時に同期させる方法を学びます。また、Hibernate Search API を使用して Elasticsearch または OpenSearch クラスタにクエリを実行する方法についても説明します。
Hibernate ORM エンティティーではないエンティティーをインデックス化する必要がある場合は、こちらの専用ガイド を参照してください。 |
前提条件
このガイドを完成させるには、以下が必要です:
-
ざっと 20 minutes
-
IDE
-
JDK 17+がインストールされ、
JAVA_HOME
が適切に設定されていること -
Apache Maven 3.9.9
-
動作するコンテナランタイム(Docker, Podman)
-
使用したい場合は、 Quarkus CLI
-
ネイティブ実行可能ファイルをビルドしたい場合、MandrelまたはGraalVM(あるいはネイティブなコンテナビルドを使用する場合はDocker)をインストールし、 適切に設定していること
アーキテクチャ
このガイドに記載されているアプリケーションは、(シンプルな) 図書館を管理することができます:あなたは、著者とその本を管理します。
エンティティはPostgreSQLデータベースに格納され、Elasticsearchクラスターにインデックスされます。
ソリューション
次の章で紹介する手順に沿って、ステップを踏んでアプリを作成することをお勧めします。ただし、完成した例にそのまま進んでも構いません。
Gitレポジトリをクローンするか git clone https://github.com/quarkusio/quarkus-quickstarts.git
、 アーカイブ をダウンロードします。
解決策は、 hibernate-search-orm-elasticsearch-quickstart
ディレクトリー に配置されています。
提供されるソリューションには、テストやテストのインフラストラクチャなど、いくつかの追加要素が含まれています。 |
Mavenプロジェクトの作成
まず、新しいプロジェクトが必要です。以下のコマンドで新規プロジェクトを作成します:
Windowsユーザーの場合:
-
cmdを使用する場合、(バックスラッシュ
\
を使用せず、すべてを同じ行に書かないでください)。 -
Powershellを使用する場合は、
-D
パラメータを二重引用符で囲んでください。例:"-DprojectArtifactId=hibernate-search-orm-elasticsearch-quickstart"
このコマンドは、以下のエクステンションをインポートするMaven構造体を生成します:
-
Hibernate ORM with Panache,
-
PostgreSQL JDBCドライバー,
-
Hibernate Search + Elasticsearch,
-
Quarkus REST (旧称 RESTEasy Reactive) と Jackson
すでにQuarkusプロジェクトが設定されている場合は、プロジェクトのベースディレクトリーで以下のコマンドを実行することで、プロジェクトに hibernate-search-orm-elasticsearch
エクステンションを追加することができます。
quarkus extension add hibernate-search-orm-elasticsearch
./mvnw quarkus:add-extension -Dextensions='hibernate-search-orm-elasticsearch'
./gradlew addExtension --extensions='hibernate-search-orm-elasticsearch'
これにより、 pom.xml
に以下が追加されます:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-search-orm-elasticsearch</artifactId>
</dependency>
implementation("io.quarkus:quarkus-hibernate-search-orm-elasticsearch")
ただのエンティティの作成
まず、 model
サブパッケージに Hibernate ORM エンティティ Book
と Author
を作成しましょう。
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 | @FullTextField は Book と同様のものを使用しますが、アナライザーが異なることに気がつくでしょう - これについては後で説明します。 |
2 | このように、同じプロパティに複数のフィールドを定義することができます。ここでは、固有の名前を持つ @KeywordField を定義しています。主な違いは、キーワードフィールドはトークン化されません(文字列は1つのトークンとして保持される)が、正規化(すなわちフィルタリング)することができるということです。これについては後で説明します。このフィールドは Author のソートに使用することを意図しているため、ソート可能であるとマークされています。 |
3 | @IndexedEmbedded の目的は、 Book のフィールドを Author のインデックスに含めることです。この場合はデフォルトの設定を使用します。つまり、関連する Book エンティティーのすべてのフィールドがインデックスに含まれます (つまり title フィールドも含まれます)。 @IndexedEmbedded の優れた点は双方向の関係により Book のいずれかが更新された場合も Author のインデックスを自動的に再作成できることです。 @IndexedEmbedded は、ネストされたドキュメントもサポートしていますが (structure = NESTED 属性を使用) ここでは必要ありません。また、すべてのフィールドを親インデックスに組み込む必要がない場合は、 includePaths /excludePaths 属性を使用して含めるフィールドを指定できます。 |
アナライザーとノーマライザー
はじめに
アナライズは全文検索の大きな部分を占めています。インデックス作成や検索クエリ構築の際に、テキストがどのように処理されるかを定義します。
アナライザーの役割は、テキストをトークン(~単語)に分割し、フィルターをかけることです(例えば、すべて小文字にしたり、アクセントを削除したり)。
ノーマライザーは入力を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インデックスに(デフォルトで)デフォルトの永続化ユニットを使用するように指示します。
アノテーションは、特定の永続ユニット ( |
2 | これは、スペースで単語を分離し、ASCII以外の文字をASCIIの対応する文字で置換し(したがって、アクセントを除去し)、すべてを小文字にするシンプルなアナライザーです。これは、例では著者名に使用されています。 |
3 | これはもう少し積極的で、ステミングも含まれています。インデックス化された入力に mysteries が含まれていても、 mystery を検索して結果を得ることができます。人名に対しては確かに強引すぎますが、書籍のタイトルに対しては完璧です。 |
4 | ここではソートに使われるノーマライザーを紹介します。最初のアナライザーと非常によく似ていますが、1つだけのトークンが欲しいので、単語をトークン化しないことを除けば同じです。 |
また、何らかの理由で
|
アナライザーの設定の詳細は、 参照ドキュメントのこちらのセクション を参照してください。
RESTサービスに全文検索機能を追加
既存の LibraryResource
に、 SearchSession
をインジェクションするだけです:
@Inject
SearchSession searchSession; (1)
1 | Hibernate Search セッションをインジェクションします。このセッションは内部で EntityManager に依存しています。複数の永続化ユニットを持つアプリケーションではCDI修飾子 @io.quarkus.hibernate.orm.PersistenceUnit を使用して正しいユニットを選択することができます: CDI統合 を参照してください。 |
そして魔法が始まります。
エンティティーにアノテーションを追加すると、全文検索が利用できるようになります。
以下のメソッド (およびいくつかの import
) を追加するだけで、Hibernate Search DSL を使用してインデックスをクエリーできるようになります。
@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 | 重要なポイント: これらのメソッドには、トランザクションコンテキストが必要です。 |
2 | パラメーター名の繰り返しを避けるために org.jboss.resteasy.annotations.jaxrs.QueryParam アノテーションを使用します。 |
3 | Author を検索していることを示しています。 |
4 | 述語を作成します。パターンが空の場合は matchAll() 述語を使用します。 |
5 | 有効なパターンがあれば、パターンにマッチする firstName 、 lastName 、 books.title フィールドに対する simpleQueryString() 述語を作成します。 |
6 | 結果のソート順を定義します。ここでは、姓でソートし、次に名でソートしています。ソートには作成した特定のフィールドを使用していることに注意してください。 |
7 | size で指定した数の一致度が高いものをフェッチします。デフォルトでは 20 です。もちろんページングもサポートしています。 |
Hibernate Search DSLはElasticsearchの述語(match、range、nested、phrase、spatial…)の重要なサブセットをサポートしています。オートコンプリートを使ってDSLをご自由にお試しください。 それでも十分でない場合は、いつでも JSONを直接使う述語の定義 にフォールバックできます。 |
データの自動初期化
このデモの目的のために、初期データセットをインポートしてみましょう。
次の内容で src/main/resources/import.sql
ファイルを作成しましょう (後で設定で参照します。
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;
上記のデータは Hibernate Search の知識なしでデータベースに注入されるため、Hibernate ORM 操作を通じて行われる今後の更新 (全文インデックスに自動的に同期される) とは異なり、インデックス化されません。
既存の LibraryResource
に、初期データをインデックス化するための以下のコンテンツ (およびいくつかの import
) を追加します。
データベースにデータを手動でインポートしない場合、これは必要ありません。 大量インデクサーはインデックス設定を変更し (いくつかフィールドの追加、アナライザーの設定変更など)、新しい設定を既存データに適用する必要がある場合にのみ使用します。 |
@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 | Hibernate Search SearchMapping を注入します。
これは内部的には EntityManagerFactory に依存しています。
複数の永続ユニットを持つアプリケーションでは、CDI 修飾子 @io.quarkus.hibernate.orm.PersistenceUnit を使用して、適切に選択できます。詳細は CDI統合 を参照してください。 |
2 | アプリケーションの起動時に実行されるメソッドを追加します。 |
3 | Object を拡張するすべてのインデックス付きエンティティータイプ、つまりすべてのインデックス付きエンティティータイプ (Author および Book ) をターゲットとする "search scope" を作成します。 |
4 | Hibernate Search の大量インデクサーのインスタンスを作成します。これにより、大量のデータを効率的にインデックス化できます (パフォーマンスを向上させるために微調整できます)。 |
5 | 大量インデクサーを起動し、完了するまで待ちます。 |
アプリケーションの設定
いつものように、Quarkusの設定ファイル( application.properties
)ですべての設定を行うことができます。
以下の内容の src/main/resources/import.sql
ファイルを作成してみましょう:
quarkus.datasource.db-kind=postgresql (1)
quarkus.hibernate-orm.sql-load-script=import.sql (2)
quarkus.hibernate-search-orm.elasticsearch.version=8 (3)
quarkus.hibernate-search-orm.indexing.plan.synchronization.strategy=sync (4)
%prod.quarkus.datasource.jdbc.url=jdbc:postgresql://localhost/quarkus_test
%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 (5)
1 | それでは、PostgreSQLのデータソースを作成してみましょう。 |
2 | 起動時にいくつかの初期データをロードします (データの自動初期化 参照)。 |
3 | 使用するElasticsearchのバージョンをHibernate Searchに伝える必要があります。Elasticsearchのバージョンによってマッピング構文に大きな違いがあるので重要です。マッピングは起動時間を短縮するためにビルド時に作成されるので、Hibernate Searchはクラスタに接続してバージョンを自動的に検出することができません。なお、OpenSearchの場合は、バージョンの前に opensearch: を付ける必要があります; OpenSearch対応を参照してください。 |
4 | これは、エンティティが検索可能になるのを待ってから書き込みが完了したとみなすことを意味します。本番環境では、デフォルトの write-sync の方がパフォーマンスが高くなります。テスト時にはエンティティがすぐに検索可能になる必要があるため sync を使用することが特に重要です。 |
5 | 開発およびテストでは、Dev Services に依存します。これは、Quarkus が PostgreSQL データベースと Elasticsearch クラスタを自動的に開始することを意味します。しかし、本番モードでは、PostgreSQL データベースと Elasticsearch クラスターを手動で起動する必要があります。そのため、この接続情報を prod プロファイル (%prod. プレフィックス) で Quarkus に提供します。 |
Dev Services に依存していることから、データベースと Elasticsearch スキーマは、
( 何らかの理由でDev Servicesを利用できない場合は以下のプロパティを設定することで、同様の動作をさせることができます:
|
Hibernate Search ORM エクステンションの設定に関する詳細は、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
./mvnw install -Dnative
./gradlew build -Dquarkus.native.enabled=true
ネイティブ実行可能ファイルのコンパイルと同様に、この操作は大量のメモリーを消費します。 ネイティブ実行可能ファイルをビルドしている間は2つのコンテナーを停止して、ビルドが終わったら再度起動した方が安全かもしれません。 |
ネイティブ実行可能ファイルを実行することは、 ./target/hibernate-search-orm-elasticsearch-quickstart-1.0.0-SNAPSHOT-runner
を実行することと同じくらい簡単です。
その後、ブラウザで http://localhost:8080/
を開きアプリケーションを使用します。
起動がいつもより少し遅いのは、起動時に毎回データベーススキーマとElasticsearchマッピングを落として再作成しているのが原因です。また、いくつかのデータを注入し、マスインデクサーを実行しています。 実際のアプリケーションでは、これは明らかに、起動時に毎回行うものではありません。 |
開発サービス (設定不要のデータストア)
Quarkus は、設定なしでさまざまなコンテナーを起動できる 開発サービス と呼ばれる機能をサポートしています。
Elasticsearch の場合、このサポートはデフォルトの Elasticsearch 接続にも及んでいます。
つまり、 quarkus.hibernate-search-orm.elasticsearch.hosts
を設定していない場合は、
Quarkus はテストの実行時または dev モード で Elasticsearch コンテナーを自動的に起動し、
接続を自動的に設定します。
アプリケーションの本番環境版を実行する場合、Elasticsearch接続は通常通り設定する必要があります。したがって、 application.properties
に本番環境版のデータベース設定を含め、Dev Servicesを引き続き使用したい場合は、 %prod.
プロファイルを使用してElasticsearch設定を定義することをお勧めします。
Dev Services for Elasticsearchは現時点では複数のクラスタを同時に起動することができず、デフォルトの永続化ユニットのデフォルトのバックエンドでのみ動作します:名前付き永続化ユニットや名前付きバックエンドはDev Services for Elasticsearchを利用することができません。 |
詳細については、 Dev Services for Elasticsearch ガイド をご覧ください。
プログラムによるマッピング
何らかの理由で Hibernate Search アノテーションをエンティティーに追加できない場合は、
代わりにプログラムでマッピングを適用することができます。
プログラムによるマッピングは、 ProgrammaticMappingConfigurationContext
を通じて設定され、
マッピング Configurer (HibernateOrmSearchMappingConfigurer
) を介して公開されます。
マッピング Configurer ( |
以下は、プログラムによるマッピングを適用するマッピング Configurer の例です。
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 | Configurer の実装に @SearchExtension 修飾子のアノテーションを付け、
デフォルトの永続ユニットで Hibernate Search Standalone によって使用されるように Quarkus に指示します。
アノテーションは、特定の永続ユニット ( |
2 | プログラムによるマッピングコンテキストにアクセスします。 |
3 | SomeIndexedEntity エンティティーのマッピングステップを作成します。 |
4 | SomeIndexedEntity エンティティーをインデックスが作成されたと定義します。 |
5 | SomeIndexedEntity エンティティーに使用するインデックス名を指定します。 |
6 | ドキュメント ID プロパティーを定義します。 |
7 | text プロパティーのフルテキスト検索フィールドを定義します。 |
または、何らかの理由で mapping configurer に
|
OpenSearch対応
Hibernate Searchは Elasticsearchと OpenSearchの両方に対応していますが、デフォルトではElasticsearchクラスタとの連携を前提としています。
代わりに Hibernate Search を OpenSearch クラスターで動作させるには、
設定されたバージョンに opensearch:
を接頭辞として付けます。
以下に例を示します。
quarkus.hibernate-search-orm.elasticsearch.version=opensearch:2.16
その他の設定オプションやAPIはElasticsearchの場合と全く同じです。
Elasticsearch の互換性のあるディストリビューションとバージョンの詳細は、 Hibernate Search の参照ドキュメントのこちらのセクション を参照してください。
複数の永続化ユニット
複数の永続化ユニットを設定
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統合
エントリーポイントの注入
CDI を使用して、Hibernate Search のメインエントリーポイント SearchSession
と SearchMapping
をインジェクションすることができます:
@Inject
SearchSession searchSession;
これは、デフォルトの永続化ユニットの SearchSession
をインジェクションします。
名前付き永続化ユニット(この例では users
)の SearchSession
を注入するには、修飾子を追加するだけです。
@Inject
@PersistenceUnit("users") (1)
SearchSession searchSession;
1 | これは @io.quarkus.hibernate.orm.PersistenceUnit アノテーションです。 |
全く同じメカニズムを使って、名前付き永続化ユニットの SearchMapping
をインジェクションすることができます:
@Inject
@PersistenceUnit("users")
SearchMapping searchMapping;
カスタムコンポーネントのプラグイン
Hibernate Search with Hibernate ORM の Quarkus エクステンションは自動的に
@SearchExtension
アノテーションが付けられたコンポーネントを Hibernate Search に注入します。
アノテーションは、注入されるコンポーネントのタイプに適切な場合、オプションで特定の永続ユニット (@SearchExtension(persistenceUnit = "nameOfYourPU")
)、
バックエンド(@SearchExtension(backend = "nameOfYourBackend")
)、インデックス (@SearchExtension(index = "nameOfYourIndex")
)、またはその組み合わせ
(@SearchExtension(persistenceUnit = "nameOfYourPU", backend = "nameOfYourBackend", index = "nameOfYourIndex")
) をターゲットにすることができます。
この機能は、次のコンポーネントタイプで使用できます。
org.hibernate.search.engine.reporting.FailureHandler
-
バックグラウンドプロセスで発生した障害が通知されるコンポーネント (主にインデックス操作)。
スコープ: 永続性ユニットごとに 1 つ。
詳細は、参照ドキュメントのこちらのセクション を参照してください。
org.hibernate.search.mapper.orm.mapping.HibernateOrmSearchMappingConfigurer
-
特にプログラムによって Hibernate Search マッピングを設定するために使用されるコンポーネント。
スコープ: 永続性ユニットごとに 1 つ以上。
詳細は、this section of this guide を参照してください。
org.hibernate.search.mapper.pojo.work.IndexingPlanSynchronizationStrategy
-
アプリケーションスレッドとインデックスの作成を同期する方法を設定するために使用されるコンポーネント。
スコープ: 永続性ユニットごとに 1 つ。
quarkus.hibernate-search-orm.indexing.plan.synchronization.strategy
を介して組み込み実装に設定することもできます。詳細は、参照ドキュメントのこちらのセクション を参照してください。
org.hibernate.search.backend.elasticsearch.analysis.ElasticsearchAnalysisConfigurer
-
フルテキスト分析 (アナライザー、ノーマライザーなど) を設定するために使用されるコンポーネント。
スコープ: バックエンドごとに 1 つ以上。
詳細は、this section of this guide を参照してください。
org.hibernate.search.backend.elasticsearch.index.layout.IndexLayoutStrategy
-
Elasticsearch レイアウト (インデックス名、インデックスエイリアスなど) を設定するために使用されるコンポーネント。
スコープ: バックエンドごとに 1 つ。
quarkus.hibernate-search-orm.elasticsearch.layout.strategy
を介して組み込み実装に設定することもできます。詳細は、参照ドキュメントのこちらのセクション を参照してください。
オフライン起動
デフォルトではHibernate Search は起動時に Elasticsearch クラスタにいくつかのリクエストを送信します。Hibernate Searchの起動時にElasticsearchクラスタが稼働していない場合は起動失敗の原因となります。
これに対処するためには起動時にリクエストを送信しないようにHibernate Searchを設定します:
-
設定プロパティー
quarkus.hibernate-search-orm.elasticsearch.version-check.enabled
をfalse
に設定して、 起動時の Elasticsearch バージョンチェックを無効にします。 -
設定プロパティー
quarkus.hibernate-search-orm.schema-management.strategy
をnone
に設定して、 起動時にスキーマ管理を無効にします。
もちろん、この構成でも、Elasticsearchクラスタにアクセスできるようになるまでは、Hibernate Searchはインデックスを作成したり、検索クエリを実行したりすることはできません。
詳細は、参照ドキュメントのこちらのセクション を参照してください。 |
アウトボックスポーリングによる調整
アウトボックスポーリングによる調整は、プレビューとみなされます。 プレビュー版 では、後方互換性やエコシステムでの存在は保証されていません。具体的な改善のためには、設定やAPI、あるいはストレージのフォーマットを変更する必要があるかもしれませんが、 安定化 に向けた計画は進行中です。ご意見・ご感想は、 メーリングリストや GitHubのイシュートラッカーでお寄せください。 |
Hibernate Search や Elasticsearch を分散型アプリケーションで使用することは技術的には可能ですが、デフォルトでは いくつかの制限 があります。
これらはHibernate Searchがデフォルトではスレッドやアプリケーションノード間の調整を行わないことによる制限です。
このような制限をなくすために、outbox-polling
調整ストラテジーを使用 できます。このストラテジーは、データベースに outbox テーブルを作成してエンティティ変更イベントをプッシュし、バックグラウンドでイベントを処理し、自動インデックスを作成します。
outbox-polling
調整ストラテジーを有効にするには、追加のエクステンションが必要です:
quarkus extension add hibernate-search-orm-outbox-polling
./mvnw quarkus:add-extension -Dextensions='hibernate-search-orm-outbox-polling'
./gradlew addExtension --extensions='hibernate-search-orm-outbox-polling'
エクステンションが存在する場合、 quarkus.hibernate-search-orm.coordination.strategy
を outbox-polling
に設定して、 outbox-polling
ストラテジーを明示的に選択する必要があります。
最後に、Hibernate Searchによって追加されたHibernate ORMエンティティ(アウトボックスとエージェントを表す)が、データベース内に対応するテーブル/シーケンスを持っていることを確認する必要があります:
-
アプリケーションを始めたばかりで、 Hibernate ORMにデータベーススキーマを生成させるつもりであれば、心配ありません。Hibernate Searchが必要とするエンティティは、生成されたスキーマに含まれます。
-
そうでない場合は、手動でスキーマを変更して、必要なテーブル/シーケンスを追加する 必要があります。
上記の作業が完了したら、アウトボックスを使ったHibernate Searchを使用する準備が整いました。コードを変更せず、アプリケーションを起動するだけで大丈夫です。複数のアプリケーションが同じデータベースに接続されていることを自動的に検出し、それに応じてインデックスの更新が調整されます。
Hibernate Searchは、 しかし重要な違いが1つあります。インデックスの更新は必然的に非同期で行われ、 いつかは 行われることが保証されますが、すぐには行われません。 これは、 この動作は、Elasticsearchの Near real-time searchと一致しており、連携が無効な場合でもHibernate Searchを使用する場合は推奨されています。 |
Hibernate Search の調整の詳細は、 リファレンスドキュメントのこのセクション を参照してください。
調整に関連する設定オプションの詳細については、 アウトボックスポーリングとの連携の設定 を参照してください。
AWSのリクエストの署名
Amazonが管理するElasticsearchサービスを使用する必要がある場合、リクエストの署名を含む独自の認証方法を必要になります。
Hibernate SearchでAWSリクエストの署名を有効にするには、専用のエクステンションをプロジェクトに追加して設定します。
詳細は Hibernate Search ORM + Elasticsearch AWS エクステンションのドキュメント を参照してください。
管理エンドポイント
Hibernate Search の管理エンドポイントは、プレビュー機能とされています。 プレビュー版 では、後方互換性やエコシステムでの存在は保証されていません。具体的な改善のためには、設定やAPI、あるいはストレージのフォーマットを変更する必要があるかもしれませんが、 安定化 に向けた計画は進行中です。ご意見・ご感想は、 メーリングリストや GitHubのイシュートラッカーでお寄せください。 |
Hibernate Search エクステンションは、管理インターフェイス を通じてデータを再インデックスするための HTTP エンドポイントを提供します。 デフォルトでは、このエンドポイントは使用できません。以下に示すように、設定プロパティーを通じて有効にできます。
quarkus.management.enabled=true (1)
quarkus.hibernate-search-orm.management.enabled=true (2)
1 | 管理インターフェイス を有効にします。 |
2 | Hibernate Search 固有の管理エンドポイントを有効にします。 |
管理エンドポイントが有効になると、 /q/hibernate-search/reindex
経由でデータのインデックスの再作成が可能になります。ここで、 /q
はデフォルトの管理ルートパスで、
/hibernate-search
はデフォルトの Hibernate Search ルート管理パスになります。
以下に示すように、(/hibernate-search
) は設定プロパティーを介して変更できます。
quarkus.hibernate-search-orm.management.root-path=custom-root-path (1)
1 | Hibernate Search の管理エンドポイントにカスタムの custom-root-path パスを使用します。
デフォルトの管理ルートパスが使用される場合は、インデックスが再作成されたパスは /q/custom-root-path/reindex になります。 |
このエンドポイントは、 application/json
コンテンツタイプのみの POST
リクエストを受け入れます。
空のリクエストボディーが送信された場合、インデックス化されたすべてのエンティティーは再度インデックス化されます。
エンティティーのサブセットのみを再インデックス化する必要がある場合、または
基礎となる大量インデクサーのカスタム設定が必要な場合、
以下のようにこの情報をリクエストボディーを介して渡すことができます。
{
"filter": {
"types": ["EntityName1", "EntityName2", "EntityName3", ...], (1)
},
"massIndexer":{
"typesToIndexInParallel": 1, (2)
}
}
1 | インデックスを再作成する必要があるエンティティー名の配列。指定されていないか空の場合は、すべてのエンティティータイプのインデックスが再作成されます。 |
2 | インデックスを並列に作成するエンティティータイプの数を設定します。 |
使用可能なフィルターと利用可能な一括インデクサー設定の完全なリストを以下の例に示します。
{
"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 | インデックスの再作成範囲を制限できるフィルターオブジェクト。 |
2 | インデックスを再作成する必要があるエンティティー名の配列。指定されていないか空の場合は、すべてのエンティティータイプのインデックスが再作成されます。 |
3 | マルチテナンシーの場合のテナント ID の配列。指定されていないか空の場合、すべてのテナントのインデックスが再作成されます。 |
4 | 一括インデクサー設定オブジェクト。 |
5 | インデックスを並列に作成するエンティティータイプの数を設定します。 |
6 | ルートエンティティーをロードするために使用されるスレッドの数の設定。 |
7 | ルートエンティティーをロードするために使用されるバッチサイズの設定。 |
8 | データロードタスクのキャッシュ対話モードの設定。 |
9 | インデックスの作成後に各インデックスが 1 つのセグメントにマージされるかどうか。 |
10 | インデックスの作成直前に、最初のインデックスのパージ後に各インデックスが 1 つのセグメントにマージされるかどうか。 |
11 | インデックスの作成前に、インデックスとそのスキーマ (存在する場合) を削除して再作成するかどうか。 |
12 | インデックスの作成前に、すべてのエンティティーがインデックスから削除されるかどうか。 |
13 | プライマリーキーをロードする際に使用するフェッチサイズの指定 (インデックスを作成するオブジェクトの場合)。 |
14 | インデックスを再作成する ID とエンティティーをロードするためのトランザクションのタイムアウトの指定。
JSON 内のすべてのプロパティーはオプションであり、使用できるのは必要なものだけである点に注意してください。 |
一括インデクサーの設定に関する詳細は、 Hibernate Search リファレンスドキュメントの対応するセクション を参照してください。
インデックスの再作成要求を送信すると、バックグラウンドでインデックスの作成がトリガーされます。インデックスの一括作成の進行状況はアプリケーションログに表示されます。
テスト目的の場合、インデックスの作成がいつ終了したかを知ることは役に立つかもしれません。URL に wait_for=finished
クエリーパラメーターを追加すると、
管理エンドポイントが、インデックス作成の開始時と終了時を報告するチャンク化された応答を返します。
複数の永続ユニットを処理する場合、再度インデックス化する永続ユニットの名前は、
persistence_unit
クエリーパラメーター (/q/hibernate-search/reindex?persistence_unit=non-default-persistence-unit
) を通じて提供されます。
参考資料
Hibernate Search の詳細については、 Hibernate チームが公開している 多数の参照ドキュメント および その他の関連ドキュメント を参照してください。
FAQ
なぜElasticsearchだけなのか?
Hibernate SearchはLuceneバックエンドとElasticsearchバックエンドの両方をサポートしています。
Quarkus のコンテキストおよびスケーラブルなアプリケーションの構築において、Elasticsearch バックエンドの方適しています。 そこで、Elasticsearch バックエンドに重点を置いています。
現時点では Quarkus で Lucene バックエンドをサポートする予定はありません。 ただし、Quarkiverse (quarkiverse/quarkus-hibernate-search-extras#179) では、 このような実装の進捗状況が追跡されています。
Hibernate ORM を使用する Hibernate Search の設定リファレンス
主な構成
ビルド時に固定される設定プロパティ - 他のすべての設定プロパティは実行時にオーバーライド可能
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:
Environment variable: Show more |
boolean |
|
||||||||||||||||||||||||||||||||
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 See this section of the reference documentation for more information.
Environment variable: 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: Show more |
string |
|
||||||||||||||||||||||||||||||||
One or more bean references to the component(s) used to configure the Hibernate Search mapping, in particular programmatically. The referenced beans must implement See Programmatic mapping for an example on how mapping configurers can be used to apply programmatic mappings.
Environment variable: 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. Environment variable: Show more |
boolean |
|
||||||||||||||||||||||||||||||||
The schema management strategy, controlling how indexes and their schema are created, updated, validated or dropped on startup and shutdown. Available values:
See this section of the reference documentation for more information. Environment variable: Show more |
|
|
||||||||||||||||||||||||||||||||
The strategy to use when loading entities during the execution of a search query. Environment variable: Show more |
|
|
||||||||||||||||||||||||||||||||
The fetch size to use when loading entities during the execution of a search query. Environment variable: Show more |
int |
|
||||||||||||||||||||||||||||||||
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 Defines how complete indexing should be before resuming the application thread after a database transaction is committed.
Available values:
This property also accepts a bean reference
to a custom implementations of See this section of the reference documentation for more information.
Environment variable: Show more |
string |
|
||||||||||||||||||||||||||||||||
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: Show more |
list of string |
|||||||||||||||||||||||||||||||||
型 |
デフォルト |
|||||||||||||||||||||||||||||||||
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 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: Show more |
ElasticsearchVersion |
|||||||||||||||||||||||||||||||||
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. See this section of the reference documentation for more information. Environment variable: 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. See this section of the reference documentation for more information. Environment variable: 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 See Setting up the analyzers for more information.
Environment variable: Show more |
list of string |
|||||||||||||||||||||||||||||||||
The list of hosts of the Elasticsearch servers. Environment variable: Show more |
list of string |
|
||||||||||||||||||||||||||||||||
The protocol to use when contacting Elasticsearch servers. Set to "https" to enable SSL/TLS. Environment variable: Show more |
|
|
||||||||||||||||||||||||||||||||
The username used for authentication. Environment variable: Show more |
string |
|||||||||||||||||||||||||||||||||
The password used for authentication. Environment variable: Show more |
string |
|||||||||||||||||||||||||||||||||
The timeout when establishing a connection to an Elasticsearch server. Environment variable: Show more |
|
|||||||||||||||||||||||||||||||||
The timeout when reading responses from an Elasticsearch server. Environment variable: Show more |
|
|||||||||||||||||||||||||||||||||
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: Show more |
||||||||||||||||||||||||||||||||||
The maximum number of connections to all the Elasticsearch servers. Environment variable: Show more |
int |
|
||||||||||||||||||||||||||||||||
The maximum number of connections per Elasticsearch server. Environment variable: Show more |
int |
|
||||||||||||||||||||||||||||||||
Defines if automatic discovery is enabled. Environment variable: Show more |
boolean |
|
||||||||||||||||||||||||||||||||
Refresh interval of the node list. Environment variable: Show more |
|
|||||||||||||||||||||||||||||||||
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: Show more |
int |
|||||||||||||||||||||||||||||||||
Whether partial shard failures are ignored ( Environment variable: Show more |
boolean |
|
||||||||||||||||||||||||||||||||
Whether Hibernate Search should check the version of the Elasticsearch cluster on startup. Set to Environment variable: Show more |
boolean |
|
||||||||||||||||||||||||||||||||
The minimal Elasticsearch cluster status required on startup. Environment variable: Show more |
|
|
||||||||||||||||||||||||||||||||
How long we should wait for the status before failing the bootstrap. Environment variable: Show more |
|
|||||||||||||||||||||||||||||||||
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: Show more |
int |
|
||||||||||||||||||||||||||||||||
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: Show more |
int |
|
||||||||||||||||||||||||||||||||
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: Show more |
int |
|
||||||||||||||||||||||||||||||||
A bean reference to the component used to configure the Elasticsearch layout: index names, index aliases, … The referenced bean must implement Available built-in implementations:
See this section of the reference documentation for more information.
Environment variable: 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. See this section of the reference documentation for more information. Environment variable: 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. See this section of the reference documentation for more information. Environment variable: 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 See Setting up the analyzers for more information.
Environment variable: Show more |
list of string |
|||||||||||||||||||||||||||||||||
The minimal Elasticsearch cluster status required on startup. Environment variable: Show more |
|
|
||||||||||||||||||||||||||||||||
How long we should wait for the status before failing the bootstrap. Environment variable: Show more |
|
|||||||||||||||||||||||||||||||||
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: Show more |
int |
|
||||||||||||||||||||||||||||||||
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: Show more |
int |
|
||||||||||||||||||||||||||||||||
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: Show more |
int |
|
||||||||||||||||||||||||||||||||
型 |
デフォルト |
|||||||||||||||||||||||||||||||||
Root path for reindexing endpoints.
This value will be resolved as a path relative to Environment variable: Show more |
string |
|
||||||||||||||||||||||||||||||||
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 Environment variable: Show more |
boolean |
|
期間フォーマットについて
期間の値を書くには、標準の 数字で始まる簡略化した書式を使うこともできます:
その他の場合は、簡略化されたフォーマットが解析のために
|
Bean参照について
まず、設定プロパティーで Bean を参照することはオプションであり、実際には推奨されていないことに注意してください。
Bean に 設定プロパティーで文字列値を使用して Bean を参照したい場合は、 文字列が解析されることを確認します。最も一般的な形式は次のとおりです。
他の形式も認められていますが、高度なユースケースでのみ有用です。 詳細は、Hibernate Searchの参照ドキュメントのこちらのセクション を参照してください。 |
アウトボックスポーリングとの連携の設定
これらの設定プロパティには、追加のエクステンションが必要です。 アウトボックスポーリングによる調整 を参照してください。 |
ビルド時に固定される設定プロパティ - 他のすべての設定プロパティは、実行時にオーバーライド可能
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 See this section of the reference documentation for more information. Environment variable: Show more |
ブーリアン |
|
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 See this section of the reference documentation for more information about event processor sharding. Environment variable: 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 See this section of the reference documentation for more information about event processor sharding. Environment variable: 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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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 See this section of the reference documentation for more information. Environment variable: Show more |
int |
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
||
How long the event processor must wait before re-processing an event after its previous processing failed. Use the value See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
タイプ |
デフォルト |
|
Configuration for the mapping of entities used for outbox-polling coordination |
タイプ |
デフォルト |
The database catalog to use for the agent table. Environment variable: Show more |
string |
|
The schema catalog to use for the agent table. Environment variable: Show more |
string |
|
The name of the agent table. Environment variable: Show more |
string |
|
The UUID generator strategy used for the agent table. Available strategies:
Environment variable: Show more |
|
|
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 Environment variable: Show more |
string |
|
The database catalog to use for the outbox event table. Environment variable: Show more |
string |
|
The schema catalog to use for the outbox event table. Environment variable: Show more |
string |
|
The name of the outbox event table. Environment variable: Show more |
string |
|
The UUID generator strategy used for the outbox event table. Available strategies:
Environment variable: Show more |
|
|
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 Environment variable: Show more |
string |
|
タイプ |
デフォルト |
|
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 See this section of the reference documentation for more information. Environment variable: Show more |
ブーリアン |
|
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 See this section of the reference documentation for more information about event processor sharding. Environment variable: 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 See this section of the reference documentation for more information about event processor sharding. Environment variable: 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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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 See this section of the reference documentation for more information. Environment variable: Show more |
int |
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
||
How long the event processor must wait before re-processing an event after its previous processing failed. Use the value See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
|
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. See this section of the reference documentation for more information. Environment variable: Show more |
|
期間フォーマットについて
期間の値を書くには、標準の 数字で始まる簡略化した書式を使うこともできます:
その他の場合は、簡略化されたフォーマットが解析のために
|