使用hibernate在lucene中进行多字段查询搜索

时间:2014-02-10 05:57:49

标签: lucene hibernate-search

我是Lucene的新手,我正在为员工类进行hibernate搜索两个字段,字段为 emp_name emp_address ,但使用的是这段代码

Session session = HibernateUtil.getSessionFactory().openSession();
        FullTextSession fullTextSession = Search.getFullTextSession(session);
        SearchFactory searchFactory = fullTextSession.getSearchFactory();
        String testString = "\"karthick\" AND \"tn\"";
        //String testString = '+'+"karthick AND tn";
        System.out.println(testString);
        String[] fields={"emp_name","emp_address"};
        /* Creating the Lucene Query */
        FullTextSession fSession = Search.getFullTextSession(session);
        fSession.beginTransaction();
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
        QueryBuilder mythQB = searchFactory.buildQueryBuilder().forEntity( EmpVo.class ).get();
        Query luceneQuery = mythQB.keyword().onFields("emp_name","emp_address").matching(testString).createQuery();
        org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery( luceneQuery );
        List<EmpVo> result = fullTextQuery.list();
        for (EmpVo employee : result) {
            System.out.println(employee.getEmp_name()+"------"+employee.getEmp_telno()+"------"+employee.getEmp_address());
        }

我只需要获得employee name karthick and employee address tn的结果,但是 对我来说,我得到了这样的结果

karthick------137594------tn
guna------134679------tn
chandra------246810------tn

1 个答案:

答案 0 :(得分:0)

我在查询解析器中使用以下语法找到了解决方案

String tst = "emp_name:\"karthick\" AND emp_address:\"tn\"";
        Query lucenceQuery = new QueryParser(Version.LUCENE_35, null, analyzer).parse(tst);
        List<EmpVo> employees = fSession.createFullTextQuery(lucenceQuery, EmpVo.class).list();