### Start server-provisioning.xml Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Starts the server-provisioning.xml file required by the Maven plugin. This file defines the feature packs to include in the custom WildFly server. ```xml ``` -------------------------------- ### Query options example with `boostedTo`, `ignoreAnalyzer`, and `withConstantScore` Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Example using query options: `boostedTo`, `ignoreAnalyzer`, and `withConstantScore` on fields and query types. ```java Query luceneQuery = mythQB .bool() .should( mythQB.keyword().onField("description").matching("urban").createQuery() ) .should( mythQB .keyword() .onField("name") .boostedTo(3) .ignoreAnalyzer() .matching("urban").createQuery() ) .must( mythQB .range() .boostedTo(5).withConstantScore() .onField("starred").above(4).createQuery() ) .createQuery(); ``` -------------------------------- ### Start CacheManager from configuration file Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Optional parameter to start a new CacheManager from an Infinispan configuration file. If both this and cachemanager_jndiname are defined, JNDI has priority. ```properties hibernate.search.infinispan.configuration_resourcename = [infinispan configuration filename] ``` -------------------------------- ### Full example of combining fulltext queries Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Full example combining fulltext queries with nested `bool`, `must`, `should`, `not`, and `all().except()` to demonstrate practical usage. ```java //look for popular modern myths that are not urban Date twentiethCentury = ...; Query luceneQuery = mythQB .bool() .must( mythQB.keyword().onField("description").matching("urban").createQuery() ) .not() .must( mythQB.range().onField("starred").above(4).createQuery() ) .must( mythQB .range() .onField("creationDate") .above(twentiethCentury) .createQuery() ) .createQuery(); //look for popular myths that are preferably urban Query luceneQuery = mythQB .bool() .should( mythQB.keyword().onField("description").matching("urban").createQuery() ) .must( mythQB.range().onField("starred").above(4).createQuery() ) .createQuery(); //look for all myths except religious ones Query luceneQuery = mythQB .all() .except( monthQb .keyword() .onField( "description_stem" ) .matching( "religion" ) .createQuery() ) .createQuery(); ``` -------------------------------- ### DSL example with Coordinates Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Pass a Coordinates instance to the spatial DSL instead of separate latitude and longitude values. The example uses Point.fromDegrees to create the coordinates. ```java Coordinates coordinates = Point.fromDegrees(24d, 31.5d); Query query = builder .spatial() .within( 51, Unit.KM ) .ofCoordinates( coordinates ) .createQuery(); ``` -------------------------------- ### Different ways of using @Boost - Java example Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Example 43 shows different ways of using the @Boost annotation for static index time boosting. It demonstrates class-level and property-level boosting with @Boost and the boost attribute of @Field. Note that index-time boosting is deprecated and query-time boosting is recommended. ```java @Entity @Indexed @Boost(1.7f) public class Essay { ... @Id @DocumentId public Long getId() { return id; } @Field(name="Abstract", store=Store.YES, boost=@Boost(2f)) @Boost(1.5f) public String getSummary() { return summary; } @Lob @Field(boost=@Boost(1.2f)) public String getText() { return text; } @Field public String getISBN() { return isbn; } ``` -------------------------------- ### Example performance option configuration for Animal index shard Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Example performance configuration for the second shard of the Animal index. Sets max_merge_docs to 10, merge_factor to 20, ram_buffer_size to 64MB, and max_buffered_docs to Lucene default. Other values use defaults defined in Lucene. ```properties hibernate.search.Animals.2.indexwriter.max_merge_docs = 10 hibernate.search.Animals.2.indexwriter.merge_factor = 20 hibernate.search.Animals.2.indexwriter.max_buffered_docs = default hibernate.search.default.indexwriter.max_merge_docs = 100 hibernate.search.default.indexwriter.ram_buffer_size = 64 ``` -------------------------------- ### Start JSR-352 mass-indexing job with MassIndexingJob Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Use the JSR-352 mass-indexing job by building job parameters with MassIndexingJob.parameters() and starting the job via BatchRuntime.getJobOperator().start(). Requires a batch runtime (e.g., JBeret) for execution. ```java Properties jobProps = MassIndexingJob .parameters() .forEntity( MyEntity.class ) .build(); long executionId = BatchRuntime .getJobOperator() .start( MassIndexingJob.NAME, jobProps ); ``` -------------------------------- ### Custom MassIndexerFactory example Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Custom MassIndexerFactory implementation and its configuration property. The factory class must implement org.hibernate.search.spi.MassIndexerFactory and be set via the hibernate.search.massindexer.factoryclass property. ```java package org.myproject import org.hibernate.search.spi.MassIndexerFactory // ... public class CustomIndexerFactory implements MassIndexerFactory { public void initialize(Properties properties) { } public MassIndexer createMassIndexer(...) { return new CustomIndexer(); } } ``` ```properties hibernate.search.massindexer.factoryclass = org.myproject.CustomIndexerFactory ``` -------------------------------- ### Tuning indexing performance - Java class snippet Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Placeholder snippet showing the start of a Java class with fields omitted, used in the context of tuning indexing performance. ```java // ... other fields omitted ``` ``` -------------------------------- ### Basic Hibernate Search configuration properties Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Add these properties to hibernate.properties, hibernate.cfg.xml, or persistence.xml to configure Hibernate Search. The directory_provider property selects the DirectoryProvider (filesystem in this example), and indexBase sets the base directory for all indexes. ```xml ... ... ``` -------------------------------- ### Using ClassLoaderService to load a custom bridge Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Shows how to use the BridgeProviderContext's ServiceManager to get the ClassLoaderService and load a custom bridge class by name. ```java ClassLoaderService classLoaderService = serviceManager.getClassLoaderService(); CustomBridge cb = classLoaderService.classForName( "com.package.CustomBridge" ); ``` -------------------------------- ### Using the @DynamicBoost Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Applies dynamic boost factors using the @DynamicBoost annotation. The entity-level boost uses CustomBoostStrategy, and the field-level boost uses CustomFieldBoostStrategy. This is the annotation-based equivalent of the programmatic model example. ```java @Entity @Indexed @DynamicBoost(impl = CustomBoostStrategy.class) public class DynamicBoostedDescriptionLibrary { @Id @GeneratedValue @DocumentId private int id; private float dynScore; @Field(store = Store.YES) @DynamicBoost(impl = CustomFieldBoostStrategy.class) private String name; public DynamicBoostedDescriptionLibrary() { dynScore = 1.0f; } // ... } ``` -------------------------------- ### Configure LockFactory with locking_strategy Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Set the Lucene LockFactory for each index. Use `simple`, `native`, `single`, or `none`, or a fully qualified class name implementing `org.hibernate.search.store.LockFactoryProvider`. The example sets different strategies for the default index, the `Animals` index, and the `Books` index. ```properties hibernate.search.default.locking_strategy = simple hibernate.search.Animals.locking_strategy = native hibernate.search.Books.locking_strategy = org.custom.components.MyLockingFactory ``` -------------------------------- ### Coffee entity with field annotations for More Like This Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Example Coffee entity showing which fields are considered for More Like This queries. Fields with term vectors or stored values are included; id and internalDescription are excluded. ```java @Entity @Indexed public class Coffee { @Id @GeneratedValue public Integer getId() { return id; } @Field(termVector = TermVector.NO, store = Store.YES) public String getName() { return name; } @Field(termVector = TermVector.YES) public String getSummary() { return summary; } @Column(length = 2000) @Field(termVector = TermVector.YES) public String getDescription() { return description; } public int getIntensity() { return intensity; } // Not stored nor term vector, i.e. cannot be used for More Like This @Field public String getInternalDescription() { return internalDescription; } // ... } ``` -------------------------------- ### Distance projection example Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Projects the distance from the query center onto each result. Use FullTextQuery.setProjection with FullTextQuery.SPATIAL_DISTANCE and call FullTextQuery.setSpatialParameters with the latitude, longitude, and spatial field name. Using coordinates different from the query center will produce unexpected results. ```java double centerLatitude = 24.0d; double centerLongitude= 32.0d; QueryBuilder builder = fullTextSession.getSearchFactory() .buildQueryBuilder().forEntity(POI.class).get(); org.apache.lucene.search.Query luceneQuery = builder .spatial() .onField("location") .within(100, Unit.KM) .ofLatitude(centerLatitude) .andLongitude(centerLongitude) .createQuery(); FullTextQuery hibQuery = fullTextSession.createFullTextQuery(luceneQuery, POI.class); hibQuery.setProjection(FullTextQuery.SPATIAL_DISTANCE, FullTextQuery.THIS); hibQuery.setSpatialParameters(centerLatitude, centerLongitude, "location"); List results = hibQuery.list(); ``` -------------------------------- ### Search with JPA Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Builds a Lucene query with the Hibernate Search DSL, wraps it in a javax.persistence.Query, and executes it against Book entities using the JPA API. The example searches title, subtitle, and authors.name fields for "Java rocks!", then commits and closes the EntityManager. ```java EntityManager em = entityManagerFactory.createEntityManager(); FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(em); em.getTransaction().begin(); // create native Lucene query using the query DSL // alternatively you can write the Lucene query using the Lucene query parser // or the Lucene programmatic API. The Hibernate Search DSL is recommended though QueryBuilder qb = fullTextEntityManager.getSearchFactory() .buildQueryBuilder().forEntity(Book.class).get(); org.apache.lucene.search.Query query = qb .keyword() .onFields("title", "subtitle", "authors.name") .matching("Java rocks!") .createQuery(); // wrap Lucene query in a javax.persistence.Query javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Book.class); // execute search List result = persistenceQuery.getResultList(); em.getTransaction().commit(); em.close(); ``` -------------------------------- ### Using @ClassBridge Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Defines class bridges on an entity using the @ClassBridge annotation. This is the annotation-based equivalent of the programmatic API example. The example shows two class bridges with parameters. ```java @Entity @Indexed @ClassBridge(name="branchnetwork", store= Store.YES, impl = CatDeptsFieldsClassBridge.class, params = @Parameter( name="sepChar", value=" " ) ), @ClassBridge(name="equiptype", store= Store.YES, impl = EquipmentType.class, params = {@Parameter( name="C", value="Cisco" ), @Parameter( name="D", value="D-Link" ), @Parameter( name="K", value="Kingston" ), @Parameter( name="3", value="3Com" ) }) public class Departments { // ... } ``` -------------------------------- ### Example entity for faceting (Cd) Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Entity used in the faceting examples. Fields annotated with @Facet must be non-analyzed; the snippet shows @Field(analyze = Analyze.NO) on price, releaseYear, and label. Note the typo @Field, on the name field as it appears in the source. ```java @Entity @Indexed public class Cd { @Id @GeneratedValue private int id; @Field, private String name; @Field(analyze = Analyze.NO) @Facet private int price; @Field(analyze = Analyze.NO) @DateBridge(resolution = Resolution.YEAR) @Facet private Date releaseYear; @Field(analyze = Analyze.NO) @Facet private String label; // setter/getter // ... ``` -------------------------------- ### Loading a custom OptimizerStrategy Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Loads a custom OptimizerStrategy by setting the optimizer.implementation property to the fully qualified class name. The implementation must implement org.hibernate.search.store.optimization.OptimizerStrategy, be public, and have a public no-argument constructor. The keyword 'default' selects the Hibernate Search default implementation; all properties after the '.optimizer' key separator are passed to the implementation's initialize method at start. ```properties hibernate.search.default.optimizer.implementation = com.acme.worlddomination.SmartOptimizer hibernate.search.default.optimizer.SomeOption = CustomConfigurationValue hibernate.search.humans.optimizer.implementation = default ``` -------------------------------- ### Example entities after adding Hibernate Search annotations Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Example entities after adding Hibernate Search annotations. The Book entity uses @Indexed, @Field with explicit parameters, @DateBridge for the publication date, and @IndexedEmbedded for the authors association. The Author entity uses @Field on the name field. These annotations configure indexing, analysis, and storage behavior for the Lucene index. ```java package example; ... @Entity @Indexed public class Book { @Id @GeneratedValue private Integer id; @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) private String title; @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) private String subtitle; @Field(index = Index.YES, analyze=Analyze.NO, store = Store.YES) @DateBridge(resolution = Resolution.DAY) private Date publicationDate; @IndexedEmbedded @ManyToMany private Set authors = new HashSet(); public Book() { } // standard getters/setters follow here ... } ``` ```java @Entity public class Author { @Id @GeneratedValue private Integer id; @Field private String name; public Author() { } // standard getters/setters follow here ... } ``` -------------------------------- ### Provision WildFly with Hibernate Search feature packs Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Defines the feature packs for provisioning a WildFly server with Hibernate Search ORM integration and an updated version of every required module. Add optional feature packs by including additional markup with their coordinates. ```xml ``` -------------------------------- ### Implement Discriminator interface Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Starts the implementation of the Discriminator interface used by @AnalyzerDiscriminator to choose the analyzer at runtime. ```java public class LanguageDiscriminator implements Discriminator { ``` -------------------------------- ### Enable Infinispan directory provider Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Enables the Infinispan directory provider for a cluster-replicated index. Replace [default|] with the index name or use 'default' for all indexes. ```properties hibernate.search.[default|].directory_provider = infinispan ``` -------------------------------- ### Service file for BridgeProvider Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Service file named META-INF/services/org.hibernate.search.bridge.spi.BridgeProvider that must contain the fully qualified class name(s) of BridgeProvider implementations. Uses the classic Service Loader discovery mechanism. ```text com.acme.myapps.hibernatesearch.CurrencyBridgeProvider ``` -------------------------------- ### Add manifest dependency on Apache Tika module Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Manifest header to add to your application so it depends on the custom Apache Tika module defined in the previous example. ```text Dependencies: org.apache.tika:1.4 ``` -------------------------------- ### Configure wildfly-server-provisioning-maven-plugin Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Maven plugin configuration to provision a custom WildFly server with updated Hibernate Search modules. Place this in your pom.xml; it references a server-provisioning.xml file and creates a server named wildfly-with-updated-hibernate-search. ```xml org.wildfly.build wildfly-server-provisioning-maven-plugin 1.2.6.Final server-provisioning build compile server-provisioning.xml wildfly-with-updated-hibernate-search ``` -------------------------------- ### Override JGroups configuration file Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Overrides the JGroups configuration file used by Infinispan. The example uses jgroups-ec2.xml, a pre-configured stack for Amazon EC2 networks. ```properties hibernate.search.infinispan.configuration.transport_override_resourcename = jgroups-ec2.xml ``` -------------------------------- ### Configure async reader strategy Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Configures the async reader strategy with a refresh period of 8000 milliseconds. The strategy can be scoped to the default index or a specific index. ```properties hibernate.search.[default|].reader.strategy = async hibernate.search.[default|].reader.async_refresh_period_ms = 8000 ``` -------------------------------- ### Author entity before Hibernate Search annotations Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Example Author entity before adding Hibernate Search annotations. It is a standard JPA entity with an id and name field. ```java package example; ... @Entity public class Author { @Id @GeneratedValue private Integer id; private String name; public Author() {} // standard getters/setters follow ... } ``` -------------------------------- ### Range queries with range().from().to() and below() Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Use range queries to search for values within given boundaries (included or not) or below/above a boundary. The first example searches for 0 <= starred < 3 using from().to().excludeLimit(). The second searches for myths strictly BC using below().excludeLimit(). ```java //look for 0 <= starred < 3 Query luceneQuery = mythQB .range() .onField("starred") .from(0).to(3).excludeLimit() .createQuery(); //look for myths strictly BC Date beforeChrist = ...; Query luceneQuery = mythQB .range() .onField("creationDate") .below(beforeChrist).excludeLimit() .createQuery(); ``` -------------------------------- ### Using @IndexedEmbedded Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Annotation-based equivalent of the programmatic embedded entity definition, using @IndexedEmbedded with the prefix "catalog.items". This is the alternative to the programmatic API shown in the previous example. ```java @Entity @Indexed public class ProductCatalog { @Id @GeneratedValue @DocumentId(name="id") public Long getCatalogId() {...} @Field public String getTitle() {...} @Field public String getDescription(); @OneToMany(fetch = FetchType.LAZY) @IndexColumn(name = "list_position") @Cascade(org.hibernate.annotations.CascadeType.ALL) @IndexedEmbedded(prefix="catalog.items") public List getItems() {...} // ... } ``` -------------------------------- ### Configuring directory providers with hibernate.search properties Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Configures directory providers for Hibernate Search indexes. The default provider is set to filesystem with a base directory, and per-index overrides are shown for the Rules and Actions indexes. ```properties hibernate.search.default.directory_provider = filesystem hibernate.search.default.indexBase = /usr/lucene/indexes hibernate.search.Rules.directory_provider = local-heap hibernate.search.Actions.directory_provider = com.acme.hibernate.CustomDirectoryProvider ``` -------------------------------- ### Indexing fields using annotation Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Annotation-based equivalent of the programmatic field definition, using @Field, @SortableField, @AnalyzerDef, and @NormalizerDef. This is the alternative to the programmatic API shown in the previous example. ```java @Entity @Indexed @AnalyzerDef(name = "en", tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class), filters = { @TokenFilterDef(factory = LowerCaseFilterFactory.class), @TokenFilterDef(factory = EnglishPorterFilterFactory.class) }) @NormalizerDef(name = "lowercase", filters = { @TokenFilterDef(factory = ASCIIFoldingFilterFactory.class), @TokenFilterDef(factory = LowerCaseFilterFactory.class) } ) public class Address { @Id @GeneratedValue @DocumentId(name="id") private Long getAddressId() {...}; @Field(store=Store.YES, analyzer=@Analyzer(definition="en")) @Field(name="address_data", analyzer=@Analyzer(definition="en")) @Field(name="address_sort", normalizer=@Normalizer(definition="lowercase")) @SortableField(forField="address_sort") public String getAddress1() {...} // ... } ``` -------------------------------- ### Configure custom ReaderProvider strategy Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Sets a custom implementation of org.hibernate.search.indexes.spi.ReaderProvider as the reader strategy. Replace 'my.corp.myapp.CustomReaderProvider' with the actual class name. ```properties hibernate.search.[default|].reader.strategy = my.corp.myapp.CustomReaderProvider ``` -------------------------------- ### Simple Query String query on multiple fields with boosts Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Searches multiple fields with different boosts: 'name' boosted to 5f, and 'history' and 'description' boosted to 2f. Uses AND as default operator. ```java Query luceneQuery = mythQB .simpleQueryString() .onField("name") .boostedTo(5f) .andFields("history", "description") .boostedTo(2f) .withAndAsDefaultOperator() .matching("storm tree") .createQuery(); ``` -------------------------------- ### Explicit @FieldBridge no longer needed Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Example 59. Shows that an explicit @FieldBridge is no longer needed when a BridgeProvider is registered. The CurrencyFieldBridge is applied automatically to any indexed property of type Currency. ```java @Entity @Indexed public class User { @Field public Currency getDefaultCurrency(); // ... } @Entity @Indexed public class Account { @Field public Currency getCurrency(); // ... } //CurrencyFieldBridge is applied automatically everywhere Currency is found on an indexed property ``` -------------------------------- ### Use a mapping factory with @Factory and persistence.xml Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Define a factory class with a no-arg constructor and a method annotated with @Factory that returns a SearchMapping. Configure the fully qualified class name via the hibernate.search.model_mapping property in the persistence unit. ```java public class MyAppSearchMappingFactory { @Factory public SearchMapping getSearchMapping() { SearchMapping mapping = new SearchMapping(); mapping .analyzerDef( "ngram", StandardTokenizerFactory.class ) .filter( LowerCaseFilterFactory.class ) .filter( NGramFilterFactory.class ) .param( "minGramSize", "3" ) .param( "maxGramSize", "3" ); return mapping; } } ``` ```xml ... ``` -------------------------------- ### Book entity before Hibernate Search annotations Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Example Book entity before adding Hibernate Search annotations. It is a standard JPA entity with fields for id, title, subtitle, authors, and publicationDate. ```java package example; ... @Entity public class Book { @Id @GeneratedValue private Integer id; private String title; private String subtitle; @ManyToMany private Set authors = new HashSet(); private Date publicationDate; public Book() {} // standard getters/setters follow ... } ``` -------------------------------- ### Get analyzer from SearchFactory Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Retrieves a named analyzer from the SearchFactory for use when building queries. Fields in queries should be analyzed with the same analyzer used to index the field so that the same tokens are reused between query and indexing. ```java Analyzer analyzer = fullTextSession.getSearchFactory().getAnalyzer("customanalyzer"); ``` -------------------------------- ### Maven dependencies for Hibernate Search using Infinispan Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Add these Maven dependencies to use the Infinispan directory provider with Hibernate Search. The infinispan-directory-provider artifact is maintained by the Infinispan team; the version shown is the latest known compatible at publication time. ```xml org.hibernate hibernate-search-orm 5.10.13.Final org.infinispan infinispan-directory-provider 9.2.2.Final ``` -------------------------------- ### Simple Query String query with phrase Source: https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single Uses a phrase query to match the exact phrase 'storm and tree' in any of the specified fields. ```java Query luceneQuery = mythQB .simpleQueryString() .onFields("name", "history", "description") .matching("\"storm and tree\"") .createQuery(); ```