Hibernate Serach 5.9全文检索快速入门

Hibernate Search是基于Lucene的全文检索框架,可以很好的整合Hibernate,实现快速检索实体类。我们今天主要来介绍Hibernate Serach的基础入门。

开发环境准备——使用Maven搭建开发环境

DEMO使用Spring Data JPA(1.10) + Hibernate Search(5.9)来实现。

以下为本次开发的pom.xml文件


    4.0.0
    com.itheima
    hibernatesearch-demo
    0.0.1-SNAPSHOT

    
        5.2.12.Final
        5.9.1.Final
        4.2.4.RELEASE
        1.8
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.0
                
                    ${jdk-version}
                    ${jdk-version}
                
            
        
    

    
        
            org.hibernate
            hibernate-core
            ${hibernate-version}
        

        
            org.hibernate
            hibernate-entitymanager
            ${hibernate-version}
        
        
            org.hibernate
            hibernate-search-orm
            ${hibernate-search-version}
        
        
            org.springframework
            spring-context-support
            ${spring-version}
        
        
            org.springframework
            spring-test
            ${spring-version}
        
        
            org.hibernate.javax.persistence
            hibernate-jpa-2.1-api
            1.0.0.Final
        
        
            org.springframework.data
            spring-data-jpa
            1.10.4.RELEASE
        
        
            mysql
            mysql-connector-java
            5.1.6
        
        
        
            cn.bestwu
            ik-analyzers
            5.1.0
        
        
            com.alibaba
            druid
            1.1.6
        
        
            junit
            junit
            4.12
        
        
            commons-lang
            commons-lang
            2.6
        
    

Spring配置文件

Spring整合了JPA以及Spring Data JPA的配置文件











    
    
    
    




    
    
    
    
        
            org.hibernate.dialect.MySQLDialect
            false
            false
            update
            
            filesystem
            
            G:/workspace/free_test/t26/index
        
    



    
    







数据库配置文件

jdbc.url=jdbc:mysql:///demo
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=000000

在实体类中开启全文检索

编写实体类

package com.itheima.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.FieldBridge;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.NumericField;
import org.hibernate.search.annotations.Store;
import org.wltea.analyzer.lucene.IKAnalyzer;

@Entity
@Table(name = "t_product")
// 使用@Indexed表示这个实体类需要创建索引
@Indexed
// 指定使用IK分词器
@Analyzer(impl=IKAnalyzer.class)
public class Product {
    // 默认使用@Id注解修饰的字段作为索引的唯一标识符
    @Id
    @GenericGenerator(name = "sysuuid", strategy = "uuid")
    @GeneratedValue(generator = "sysuuid")
    private String id;
    // 默认为字段建立索引、进行分词(分析)、不存储
    @Field(store=Store.YES)
    private String name; // 商品名称
    @Field(store=Store.YES)
    private String description; // 商品描述
    @Field(store=Store.YES)
    // 如果是数字字段,需要使用@NumericField进行修饰
    @NumericField(forField="price")
    private Double price; // 商品价格
    @Field(store=Store.YES)
    private String catelog; // 商品分类

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getCatelog() {
        return catelog;
    }

    public void setCatelog(String catelog) {
        this.catelog = catelog;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price
                + ", catelog=" + catelog + "]";
    }
}

编写DAO接口

package com.itheima.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.itheima.entity.Product;

public interface ProductRepository extends JpaRepository{

}

编写Service接口

package com.itheima.service;
import java.util.List;

import com.itheima.entity.Product;

public interface ProductService {
    void save(Product product);
    List fullTextQuery(String[] fields, String keyword);
    List rangeQuery(String fields, double from, double to);
}

编写Service实现

package com.itheima.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itheima.entity.Product;
import com.itheima.repository.ProductRepository;

@Service
@Transactional
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private EntityManager entityManager;

    @Override
    public void save(Product product) {
        productRepository.save(product);
    }

        /**
        * 根据关键字进行全文检索
        */
    @Override
    public List fullTextQuery(String[] fields, String keyword) {
        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

        QueryBuilder qb = fullTextEntityManager.getSearchFactory()
                .buildQueryBuilder().forEntity(Product.class).get();
        org.apache.lucene.search.Query luceneQuery = qb
            .keyword()
            .onFields(fields)
            .matching(keyword)
            .createQuery();

        javax.persistence.Query jpaQuery 
            = fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);

        return jpaQuery.getResultList();
    }

    /**
    * 根据数值范围进行检索
    */
    @Override
    public List rangeQuery(String field, double from, double to) {
        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

        QueryBuilder qb = fullTextEntityManager.getSearchFactory()
                .buildQueryBuilder().forEntity(Product.class).get();
        org.apache.lucene.search.Query luceneQuery = qb
            .range()
            .onField(field)
            .from(from)
            .to(to)
            .createQuery();

        javax.persistence.Query jpaQuery 
            = fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);

        return jpaQuery.getResultList();
    }
}

测试代码:

package com.itheima.service.test;
import java.util.List;
import javax.persistence.EntityManager;
import org.apache.commons.lang.math.RandomUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;
import com.itheima.entity.Product;
import com.itheima.service.ProductService;

// 整合Spring Junit
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class ProductServiceTest {

    @Autowired
    private ProductService productService;

    /**
    * 创建测试数据,Hiberante Search会自动创建索引
    */
    @Test
    public void saveTest01() {
        for(int i = 0; i < 100; ++i) {
            Product product = new Product();
            product.setCatelog("手机");
            product.setDescription("小米 红米5A 全网通版 3GB+32GB 香槟金 移动联通电信4G手机 双卡双待");
            product.setName("红米5A" + i);
            product.setPrice(RandomUtils.nextDouble() * 100 % 100);

            productService.save(product);
        }
    }

    @Test
    public void fullTextQueryTest01() {
        List list = productService.fullTextQuery("catelog,description,name".split(","), "移动");
        for (Object object : list) {
            System.out.println(object);
        }
    }

    @Test
    public void rangeQueryTest01() {
        List list = productService.rangeQuery("price", 10.0D, 20D);
        for (Object object : list) {
            System.out.println(object);
        }
    }
}