Chapter 1. Getting started

简介: <div> <div style="font-family:Tahoma; orphans:2; widows:2; font-size:14px"> <h2 style="color:rgb(74,93,117); line-height:24px; margin-top:30px; font-family:'Lucida Grande',Geneva,Verdana,Arial,s
首先是配置开发环境:

主要记录一下和Hibernate Search 相关的配置,Spring 和 JPA的配置请查看相关文章。

Hibernate Search 的配置相当简单,主要涉及三个方面:(本文是基于jpa的)

1、配置Hibernate Search,修改JPA配置文件:persistence.xml

<?xml version="1.0" encoding="utf-8"?>
    <persistence ...>
      <persistence-unit ...>    
          <properties>
            ...
            <!-- hibernate search -->
            <property name="hibernate.search.default.directory_provider" value="filesystem"/>
            <property name="hibernate.search.default.indexBase" value="索引文件存储位置"/>
        </properties>
      </persistence-unit>
    </persistence>

属性hibernate.search.default.directory_provider告诉hibernate使用哪个DirectoryProvider实现。在Apache Lucene中有一个概念Directory来保存Index Files。Hibernate通过DirectoryProvider来初始化和配置一个Lucene Directory实例。在本例中,我们使用一个能把Index Files保存在file system中的DirectoryProvider。当Index Files保存在file system中时,我们可以通过Luke工具实时查看Lucene索引文件。除了DirectoryProvider外,还需要告诉hibernate索引文件保存在哪个具体的目录中,这通过hibernate.search.default.indexBase属性来配置。

2、添加相应的jar依赖

hibernate-search-4.1.1.Final\dist:
hibernate-search-engine-4.1.1.Final.jar
hibernate-search-orm-4.1.1.Final.jar

hibernate-search-4.1.1.Final\dist\lib\required: 
antlr-2.7.7.jar
avro-1.5.1.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.3.Final.jar
jackson-core-asl-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
lucene-core-3.5.0.jar
paranamer-2.3.jar
slf4j-api-1.6.1.jar
snappy-java-1.0.1-rc3.jar

3、为实体添加hibernate search 相关annotation

只需要以上三步,hibernate search就已经配置完成了,接下来要开始实体相关annotation的说明了。




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<Author> authors = new HashSet<Author>();

  public Book() {  }     // standard getters/setters follow here  ... }
package example;...@Entitypublic class Author {

  @Id  @GeneratedValue  private Integer id;

  @Field
  private String name;

  public Author() {  }    // standard getters/setters follow here  ...}
新建2个实体类
  • @Indexed标注需要索引的实体
  • 如果有@Id标志,则不需要显示声明@DocumentId,因为lucene就不需要生成唯一标志来区分索引。
  • @Fileld标明为需要搜索的属性。默认@Filed的参数是index=Index.YESanalyze=Analyze.YES andstore=Store.NO,即进行索引,分词,不保存具体内容到索引。 Note :无论store=Store.NO还是store=Store.YES都不会影响最终的搜索能力。store.YES的作用是可以在搜索后可以直接从索引中获取域的完整值。在hibernate中,如果store=Store.NO,搜索结果中,域的值是通过数据库中获取,如果store=Store.YES,域的值是直接从索引文档中获取。
  • 由于lucene都是基于String进行索引 (Lucene2.9后支持数值索引),所以hibernate search使用@Bridge标签来转换数据类型,比如@DateBridge,时间数据转换
  • 由于lucene索引是平整的数据结构(flat data structure),无法识别对象关联关系@ManyToMany,@*ToOne@Embedded and@ElementCollection,hibernate search,为了让上面的书的作者能被识别,使用@IndexedEmbedded标签

1.4. Indexing

hibernate search会透明的索引所有有标注过的实体类,不管是更新还是删除,都通过hibernate core自动进行。
但是如果数据库中已经有数据,则需手动初始化你的索引。如下 (see also  Section 6.3, “Rebuilding the whole index” ):
  1. //使用Hibernate Session初始化索引  
  2. FullTextSession fullTextSession = Search.getFullTextSession(session);  
  3. fullTextSession.createIndexer().startAndWait();  
 
Java代码  
  1. //使用JPA初始化索引  
  2. EntityManager em = entityManagerFactory.createEntityManager();  
  3. FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);  
  4. fullTextEntityManager.createIndexer().startAndWait();  
上述操作之后,就可以在索引目录中看到新生成的索引.利用luke查看索引,可以更好的了解lucene是如何工作的。

通过Hibernate Search query DSL,

Hibernate Session创建和运行搜索

Java代码  
  1. FullTextSession fullTextSession = Search.getFullTextSession(session);  
  2. Transaction tx = fullTextSession.beginTransaction();  
  3. // create native Lucene query unsing the query DSL  
  4. // alternatively you can write the Lucene query using the Lucene query parser  
  5. // or the Lucene programmatic API. The Hibernate Search DSL is recommended though  
  6. QueryBuilder qb = fullTextSession.getSearchFactory()  
  7.     .buildQueryBuilder().forEntity( Book.class ).get();  
  8. org.apache.lucene.search.Query query = qb  
  9.   .keyword()  
  10.   .onFields("title""subtitle""authors.name""publicationDate")  
  11.   .matching("Java rocks!")  
  12.  .createQuery();  
  13. // wrap Lucene query in a org.hibernate.Query  
  14. org.hibernate.Query hibQuery =   
  15.     fullTextSession.createFullTextQuery(query, Book.class);  
  16. // execute search  
  17. List result = hibQuery.list();  
  18.     
  19. tx.commit();  
  20. session.close();  
 

通过JPA创建和运行搜索

Java代码  
  1. EntityManager em = entityManagerFactory.createEntityManager();  
  2. FullTextEntityManager fullTextEntityManager =   
  3.     org.hibernate.search.jpa.Search.getFullTextEntityManager(em);  
  4. em.getTransaction().begin();  
  5. // create native Lucene query unsing the query DSL  
  6. // alternatively you can write the Lucene query using the Lucene query parser  
  7. // or the Lucene programmatic API. The Hibernate Search DSL is recommended though  
  8. QueryBuilder qb = fullTextSession.getSearchFactory()  
  9.     .buildQueryBuilder().forEntity( Book.class ).get();  
  10. org.apache.lucene.search.Query query = qb  
  11.   .keyword()  
  12.   .onFields("title""subtitle""authors.name""publicationDate")  
  13.   .matching("Java rocks!");  
  14.   .createQuery();  
  15. // wrap Lucene query in a javax.persistence.Query  
  16. javax.persistence.Query persistenceQuery =   
  17.     fullTextEntityManager.createFullTextQuery(query, Book.class);  
  18. // execute search  
  19. List result = persistenceQuery.getResultList();  
  20. em.getTransaction().commit();  
  21. em.close();   

1.6. Analyzer


  • 在配置文件中设置 默认分词器hibernate.search.analyzer

  • 用标注的方式在实体上设置分词器 @Analyzer .

  • 用标注的方式在field域上设置分词器 @Analyzer .

我们也可以利用@AnalyzerDef自定义分词器,接下来的例子将结合Solr分词器以及factories,更多的
可使用factory类详见Solr文档, Solr Wiki.
下面的例子使用StandardTokenizerFactory,以及2个filter factories,LowerCaseFilterFactory andSnowballPorterFilterFactory.标准的分词器通过会标点符号和连接符进行分词,以便保持email和主机名的
完整。lowercase filter将所有字母转化为小写,最后由snowball filter进行截词

通常来说,使用Solr必须先声明分词器以及过滤器.

Example 1.11. Using @AnalyzerDef and the Solr framework to define and use an analyzer
@Entity@Indexed
@AnalyzerDef(name = "customanalyzer",
  tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
  filters = {
    @TokenFilterDef(factory = LowerCaseFilterFactory.class),
    @TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = {
      @Parameter(name = "language", value = "English")
    })
  })
public class Book {

  @Id  @GeneratedValue  @DocumentId  private Integer id;    @Field  @Analyzer(definition = "customanalyzer")
  private String title;    @Field  @Analyzer(definition = "customanalyzer")
  private String subtitle; 

  @IndexedEmbedded  @ManyToMany   private Set<Author> authors = new HashSet<Author>();
  @Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)  @DateBridge(resolution = Resolution.DAY)  private Date publicationDate;    public Book() {  }     // standard getters/setters follow here  ... }
使用 @AnalyzerDef只是定义了一个分析器,你仍然需要使用通过标注@Analyzer来使用它,就像上面的例子,customanalyzer
被应用在title和subtitle属性上。analyzer的定义是全局性的,一旦定义之后就可以在所有实体上使用。



第一章结束,排版很蛋疼,这也就是我为什么不喜欢在论坛上发帖- -。
目录
相关文章
|
存储 缓存 Shell
BackTrader 中文文档(二)(3)
BackTrader 中文文档(二)
771 0
|
文字识别 Python
Halcon 学习笔记五:几何定位+仿射变换+测量
Halcon 学习笔记五:几何定位+仿射变换+测量
2422 0
|
7天前
|
人工智能 自然语言处理 文字识别
阿里云百炼Qwen3.7-Max简介:能力、优势、支持订阅计划参考
Qwen3.7-Max是阿里云百炼面向智能体时代推出的新一代旗舰模型,对标GPT-5.5、Claude Opus 4.7等闭源旗舰。该模型支持百万级token上下文窗口,具备顶级推理能力、多模态搜索与视觉理解增强、流式输出低延迟响应等核心优势,覆盖编程、办公、长周期自主执行等复杂场景。同时支持OpenAI接口兼容,便于系统快速迁移。用户可通过Token Plan团队或节省计划等订阅方式灵活调用,适合企业级高要求场景使用。
3461 15
阿里云百炼Qwen3.7-Max简介:能力、优势、支持订阅计划参考
|
15天前
|
人工智能 开发工具 iOS开发
Claude Code 新手完全上手指南:安装、国产模型配置与常用命令全解
Claude Code 是一款运行在终端环境中的 AI 编程助手,能够直接在命令行中完成代码生成、项目分析、文件修改、命令执行、Git 管理等开发全流程工作。它最大的特点是**任务驱动、终端原生、轻量高效、多模型兼容**,无需图形界面、不依赖 IDE 插件,能够深度融入开发者日常工作流。
3558 12
|
9天前
|
人工智能 自然语言处理 供应链
|
18天前
|
Shell API 开发工具
Claude Code 快速上手指南(新手友好版)
AI编程工具卷疯啦!Claude Code凭借任务驱动+终端原生的特性,成了开发者的效率搭子。本文从安装、登录、切换国产模型到常用命令,手把手带新手快速上手,全程避坑,30分钟独立用起来。
3675 25
|
11天前
|
人工智能 Linux BI
国内用 Claude Code 终于不用翻墙了:一行命令搞定,自动接 DeepSeek
JeecgBoot AI专题研究 一键脚本:Claude Code + JeecgBoot Skills + DeepSeek 全平台接入 一行命令装好 Claude Code + JeecgBoot Skills + DeepSeek 接入,无需翻墙使用 Claude Code,支持 Wind
2914 7
国内用 Claude Code 终于不用翻墙了:一行命令搞定,自动接 DeepSeek
|
9天前
|
人工智能 自然语言处理 安全
Claude Code 全攻略:命令大全+三种模式+记忆体系+实战工作流完整手册
Claude Code 是当前最流行的终端级 AI 编程助手,能够直接在命令行中完成代码生成、项目理解、文件修改、命令执行、错误修复等全流程开发工作。它不依赖图形界面、不占用额外资源,却能深度理解项目结构,自动生成规范代码,大幅提升研发效率。
1407 3