全文检索之Spring Hibernate search 注解实现

1.maven项目pom.xml加入依赖

 <dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-search-orm</artifactId>

<version>5.5.0.Final</version>

 </dependency>

 <dependency>

<groupId>org.apache.lucene</groupId>

<artifactId>lucene-queryparser</artifactId>

<version>5.3.0</version>

 </dependency>

<!--中文分词器>

 <dependency>

<groupId>org.apache.lucene</groupId>

<artifactId>lucene-analyzers-smartcn</artifactId>

<version>5.3.0</version>

 </dependency>

2.application.xml中添加配置

 <property name="hibernateProperties">

<props>

//文件系统

<prop key="hibernate.search.default.directory_provider">filesystem</prop>

//索引存储目录

<prop key="hibernate.search.default.indexBase">e:/index</prop>

</props>

 </property>

3.domain(bean)中实体类配置

类上注解

 注释@Indexed将实体类标记为需要通过Hibernate Search进行索引的实体。

 注释@Analyzer(impl=SmartChineseAnalyzer.class),我配置了中文分词器,默认是StandardAnalyzer.calss

类中属性注解

  Hibernate Search需要将实体标识符存储在每个实体的索引中。默认情况下,它将使用标记为@Id的字段,但您可以使用@DocumentId(仅限高级用户)覆盖此字段。

  注释@Field用于实体类属性上,其中参数的默认值为index = Index.YESanalyze = Analyze.YESstore = Store.NO

  Lucene索引主要是基于字符串的,还有一些额外的数字类型支持。有关更多详情,请参阅Bridges

关联实体的索引

  @IndexedEmbedded注释用于索引关联实体,如通常通过@ManyToMany@OneToOne@ManyToOne@Embedded@ElementCollection定义的实体,有关详细信息,请参   阅嵌入式和关联对象。

4.注解实体类例子

@Entity
@Table(name = "t_task")
@Indexed
@Analyzer(impl=SmartChineseAnalyzer.class)
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@DocumentId
private Long id;

@Column(name="c_taskname")
@Field
private String taskName;//任务名称
@Column(name="c_address")
private String address;//工作地点
@Column(name = "c_content")
@Field
private String content;// 任务内容

5.全文检索索引初始化

  /*全文搜索索引初始化*/
public void initFullTextIndex() throws Exception{
FullTextSession fullTextSession = Search.getFullTextSession(currentSession());
fullTextSession.createIndexer().startAndWait();
}

6.全文检索查询

/*全文搜索*/
public List fullTextSearch(){
FullTextSession fullTextSession = Search.getFullTextSession(currentSession());
Transaction tx = fullTextSession.beginTransaction();
QueryBuilder qb = fullTextSession.getSearchFactory() .buildQueryBuilder().forEntity(entityType).get();
org.apache.lucene.search.Query query = qb .keyword() .onFields("taskName", "content") .matching("
扫黄") .createQuery();
org.hibernate.Query hibQuery =  fullTextSession.createFullTextQuery(query, entityType);
List result = hibQuery.list();
return result;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值