private List<Post> findPosts() { try { FullTextSession fullTextSession = getFullTextSession((Session) entityManager.getDelegate()); Builder builder = new Builder(); String[] fields = new String[] { "message.text", "topic.subject" }; MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer()); builder.add(parser.parse(POST_TEXT), MUST); builder.add(new TermQuery(new Term("topic.forum.id", "0")), MUST); builder.add(new TermQuery(new Term("topic.forum.category.id", "0")), MUST); builder.add(new WildcardQuery(new Term("poster.userId", "root")), MUST); addPostTimeQuery(builder); FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), Post.class); fullTextQuery.setSort(getSort()); fullTextQuery.setFirstResult(0); fullTextQuery.setMaxResults(15); @SuppressWarnings("unchecked") List<Post> posts = fullTextQuery.list(); return posts; } catch (ParseException e) { logger.severe("error"); return null; } }
@Override @SuppressWarnings("unchecked") public List<PostPO> searchByTag(Paging paigng, String tag) { FullTextSession fullTextSession = Search.getFullTextSession(super.session()); SearchFactory sf = fullTextSession.getSearchFactory(); QueryBuilder qb = sf.buildQueryBuilder().forEntity(PostPO.class).get(); org.apache.lucene.search.Query luceneQuery = qb.phrase().onField("tags").sentence(tag).createQuery(); FullTextQuery query = fullTextSession.createFullTextQuery(luceneQuery); query.setFirstResult(paigng.getFirstResult()); query.setMaxResults(paigng.getMaxResults()); Sort sort = new Sort(new SortField("id", SortField.Type.LONG, true)); query.setSort(sort); paigng.setTotalCount(query.getResultSize()); return query.list(); }
@SuppressWarnings("unchecked") public <T> List<T> executeSearchQuery( RestSearchKey key, Class<T> typeClass, FullTextSession fullTextEntityManager, QueryBuilder queryBuilder, Map<String, Query> crtsMap ) { FullTextQuery fullTextQuery = createFullTextQuery(typeClass, fullTextEntityManager, queryBuilder, crtsMap); if(key.hasOrders()){ hibernateSearchBuilder.defineOrder(key, fullTextQuery); } hibernateSearchBuilder.definePaging(key, fullTextQuery); return fullTextQuery.list(); }
private <T> FullTextQuery createFullTextQuery(Class<T> typeClass, FullTextSession fullTextSession, QueryBuilder queryBuilder, Map<String, Query> crtsMap) { BooleanJunction<?> booleanJunction = hibernateSearchBuilder.createFinalBooleanJunction( queryBuilder, crtsMap); FullTextQuery fullTextQuery = null; if(booleanJunction == null){ fullTextQuery = fullTextSession.createFullTextQuery(queryBuilder.all().createQuery(), typeClass); } else { fullTextQuery = fullTextSession.createFullTextQuery( booleanJunction.createQuery(), typeClass); } return fullTextQuery; }
@SuppressWarnings("unchecked") public SearchResult search(SearchParams params) throws ParseException { String buildQuery = params.buildQuery(); FullTextQuery query = this.createQuery(buildQuery); query.setFirstResult(params.getStart()); query.setMaxResults(params.getMaxResults()); query.setFetchSize(params.getMaxResults()); if (params.getSort() == SearchSort.DATE) { query.setSort(new Sort(new SortField("date", params.getSortType() == SearchSortType.DESC))); } else if (params.getSort() == SearchSort.RELEVANCE) { query.setSort(Sort.RELEVANCE); } return new SearchResult(query.list(), query.getResultSize()); }
@Override public <T> List<T> findAll(Class<T> clazz, Query luceneQuery, int firstResult, int maxResults, Sort sort, Criteria criteria) { if (isTraceEnabled) log.trace("엔티티 조회. clazz=[{}], luceneQuery=[{}], fitstResult=[{}], maxResults=[{}], sort=[{}], criteria=[{}]", clazz, luceneQuery, firstResult, maxResults, sort, criteria); if (luceneQuery == null) luceneQuery = getQueryBuilder(clazz).all().createQuery(); FullTextQuery ftq = getFullTextQuery(luceneQuery, clazz); HibernateTool.setPaging(ftq, firstResult, maxResults); if (sort != null) ftq.setSort(sort); if (criteria != null) ftq.setCriteriaQuery(criteria); return ftq.list(); }
@Override public <T> PaginatedList<T> getPage(Class<T> clazz, Query luceneQuery, int pageNo, int pageSize, Sort sort, Criteria criteria) { if (isDebugEnabled) log.debug("엔티티 조회. clazz=[{}], luceneQuery=[{}], pageNo=[{}], pageSize=[{}], sort=[{}], criteria=[{}]", clazz, luceneQuery, pageNo, pageSize, sort, criteria); if (luceneQuery == null) luceneQuery = getQueryBuilder(clazz).all().createQuery(); int itemCount = count(clazz, luceneQuery); FullTextQuery ftq = getFullTextQuery(luceneQuery, clazz); HibernateTool.setPaging(ftq, (pageNo - 1) * pageSize, pageSize); if (sort != null) ftq.setSort(sort); if (criteria != null) ftq.setCriteriaQuery(criteria); List<T> list = ftq.list(); return new PaginatedList<>(list, pageNo, pageSize, itemCount); }
@Override public <T> PaginatedList<T> getPage(Class<T> clazz, Query luceneQuery, int pageNo, int pageSize, Sort sort, Criteria criteria) { if (isDebugEnabled) log.debug("엔티티 조회. clazz=[{}], luceneQuery=[{}], pageNo=[{}], pageSize=[{}], sort=[{}], criteria=[{}]", clazz, luceneQuery, pageNo, pageSize, sort, criteria); if (luceneQuery == null) luceneQuery = getQueryBuilder(clazz).all().createQuery(); long itemCount = count(clazz, luceneQuery); FullTextQuery ftq = getFullTextQuery(luceneQuery, clazz); HibernateTool.setPaging(ftq, (pageNo - 1) * pageSize, pageSize); if (sort != null) ftq.setSort(sort); if (criteria != null) ftq.setCriteriaQuery(criteria); List<T> list = ftq.list(); return new PaginatedList<>(list, pageNo, pageSize, itemCount); }
@Test public void searchTest() throws Exception { FullTextQuery ftq = createMock(FullTextQuery.class); FullTextSession fts = createMock(FullTextSession.class); SearchFactory factory = createMock(SearchFactory.class); expect(fts.getSearchFactory()).andReturn(factory); expect(factory.getAnalyzer(Item.class)).andReturn(new StandardAnalyzer(Version.LUCENE_36)); expect(fts.createFullTextQuery(isA(Query.class), eq(Item.class))).andReturn(ftq); expect(ftq.setProjection("title")).andReturn(ftq); List<Object[]> results = new ArrayList<Object[]>(); results.add(new Object[] { "The Incredibles" }); expect(ftq.list()).andReturn(results); replay(factory); replay(ftq); replay(fts); }
@Test public void testFuzzyQuery() throws Exception { buildIndex(fts); try { String userInput = "title"; FuzzyQuery luceneQuery = new FuzzyQuery(new Term("title", userInput), 0.4f); log.debug("Query=" + luceneQuery.toString()); FullTextQuery ftq = fts.createFullTextQuery(luceneQuery, Dvd.class); List<Dvd> results = ftq.list(); Assertions.assertThat(results.size()).isEqualTo(5); // Assertions.assertThat(results.get(0).getTitle()).isEqualTo(titles[0]); for (Dvd dvd : results) { log.debug("Title=" + dvd.getTitle()); } } finally { for (Object element : fts.createQuery("from " + Dvd.class.getName()).list()) { fts.delete(element); } } }
@Test public void searchProduct() throws Exception { Transaction tx = fts.beginTransaction(); Query query = new TermQuery(new Term("description", "salesman")); log.debug("query=" + query.toString()); FullTextQuery ftq = fts.createFullTextQuery(query, Product.class); ftq.setProjection(FullTextQuery.DOCUMENT, FullTextQuery.SCORE, FullTextQuery.DOCUMENT_ID, FullTextQuery.EXPLANATION); List<Object[]> results = ftq.list(); tx.commit(); }
@Override public <T> List<T> find(Class<T> clazz, Query luceneQuery, int firstResult, int maxResults, Sort luceneSort, Criteria criteria) { if (isTraceEnabled) log.trace("엔티티 조회. clazz=[{}], luceneQuery=[{}], fitstResult=[{}], maxResults=[{}], sort=[{}], criteria=[{}]", clazz, luceneQuery, firstResult, maxResults, luceneSort, criteria); if (luceneQuery == null) luceneQuery = getQueryBuilder(clazz).all().createQuery(); FullTextQuery ftq = getFullTextQuery(luceneQuery, clazz); HibernateTool.setPaging(ftq, firstResult, maxResults); if (luceneSort != null) ftq.setSort(luceneSort); if (criteria != null) ftq.setCriteriaQuery(criteria); return ftq.list(); }
@Override public List<Object[]> findProjections(Class<?> clazz, Query luceneQuery, String[] fields, int firstResult, int maxResults, Sort luceneSort, Criteria criteria) { shouldNotBeNull(fields, "fields"); Guard.shouldBe(fields.length > 0, "조회할 필드 수가 있어야합니다."); if (isTraceEnabled) log.trace("Project 조회. clazz=[{}], luceneQuery=[{}], fields=[{}], firstResult=[{}], maxResults=[{}], luceneSort=[{}], criteria=[{}]", clazz, luceneQuery, StringTool.listToString(fields), firstResult, maxResults, luceneSort, criteria); if (luceneQuery == null) luceneQuery = getQueryBuilder(clazz).all().createQuery(); FullTextQuery ftq = getFullTextQuery(luceneQuery, clazz); HibernateTool.setPaging(ftq, firstResult, maxResults); ftq.setProjection(fields); if (luceneSort != null) ftq.setSort(luceneSort); if (criteria != null) ftq.setCriteriaQuery(criteria); return ftq.list(); }
@Override public <T> IPagedList<T> getPage(Class<T> clazz, Query luceneQuery, int pageNo, int pageSize, Sort luceneSort, Criteria criteria) { log.trace("엔티티 페이징 조회. clazz=[{}], luceneQuery=[{}], pageNo=[{}], pageSize=[{}], sort=[{}], criteria=[{}]", clazz, luceneQuery, pageNo, pageSize, luceneSort, criteria); long totalCount = count(clazz, luceneQuery); FullTextQuery ftq = this.getFullTextQuery(luceneQuery, clazz); HibernateTool.setPaging(ftq, (pageNo - 1) * pageSize, pageSize); if (luceneSort != null) ftq.setSort(luceneSort); if (criteria != null) ftq.setCriteriaQuery(criteria); // fetching strategy 같은 겻을 제공할 수 있다. return new PaginatedList<T>(ftq.list(), pageNo, pageSize, totalCount); }
/** * Performs a search in Lucene and puts the resulting product object ids in * a corresponding map. * * @param query * the Lucene query * @param fts * the Hibernate Search FullTextSession * @param map * the map for the search results * @throws HibernateException */ private void searchViaLucene(org.apache.lucene.search.Query query, FullTextSession fts, LinkedHashMap<Long, VOService> map) throws HibernateException { FullTextQuery ftQuery = fts.createFullTextQuery(query, Product.class); ftQuery.setProjection("key"); List<?> result = ftQuery.list(); if (result != null) { for (Object item : result) { map.put((Long) ((Object[]) item)[0], null); } } }
@Override @SuppressWarnings("unchecked") public List<Post> search(Paging paging, String q) throws Exception { FullTextSession fullTextSession = Search.getFullTextSession(super.session()); SearchFactory sf = fullTextSession.getSearchFactory(); QueryBuilder qb = sf.buildQueryBuilder().forEntity(PostPO.class).get(); org.apache.lucene.search.Query luceneQuery = qb.keyword().onFields("title","summary","tags").matching(q).createQuery(); FullTextQuery query = fullTextSession.createFullTextQuery(luceneQuery); query.setFirstResult(paging.getFirstResult()); query.setMaxResults(paging.getMaxResults()); StandardAnalyzer standardAnalyzer = new StandardAnalyzer(); SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span style='color:red;'>", "</span>"); QueryScorer queryScorer = new QueryScorer(luceneQuery); Highlighter highlighter = new Highlighter(formatter, queryScorer); List<PostPO> list = query.list(); List<Post> rets = new ArrayList<>(list.size()); for (PostPO po : list) { Post m = BeanMapUtils.copy(po, 0); // 处理高亮 String title = highlighter.getBestFragment(standardAnalyzer, "title", m.getTitle()); String summary = highlighter.getBestFragment(standardAnalyzer, "summary", m.getSummary()); if (StringUtils.isNotEmpty(title)) { m.setTitle(title); } if (StringUtils.isNotEmpty(summary)) { m.setSummary(summary); } rets.add(m); } paging.setTotalCount(query.getResultSize()); return rets; }
/** * Security is evaluated by Lucene, so query result are already pruned. This means that every node * should have its security (user and role) info stored in Lucene. This provides very quick search * but security modifications need to be recursively applied to reach every document node in the * repository. This may take several hours (or days) is big repositories. */ @SuppressWarnings("unchecked") private NodeResultSet runQueryLucene(FullTextSession ftSession, Query query, int offset, int limit) throws IOException, InvalidTokenOffsetsException, HibernateException { log.debug("runQueryLucene({}, {}, {}, {})", new Object[]{ftSession, query, offset, limit}); List<NodeQueryResult> results = new ArrayList<NodeQueryResult>(); NodeResultSet result = new NodeResultSet(); FullTextQuery ftq = ftSession.createFullTextQuery(query, NodeDocument.class, NodeFolder.class, NodeMail.class); ftq.setProjection(FullTextQuery.SCORE, FullTextQuery.THIS); ftq.enableFullTextFilter("readAccess"); QueryScorer scorer = new QueryScorer(query, NodeDocument.TEXT_FIELD); // Set limits ftq.setFirstResult(offset); ftq.setMaxResults(limit); // Highlight using a CSS style SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span class='highlight'>", "</span>"); Highlighter highlighter = new Highlighter(formatter, scorer); highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer, MAX_FRAGMENT_LEN)); for (Iterator<Object[]> it = ftq.iterate(); it.hasNext(); ) { Object[] qRes = it.next(); Float score = (Float) qRes[0]; NodeBase nBase = (NodeBase) qRes[1]; // Add result addResult(ftSession, results, highlighter, score, nBase); } result.setTotal(ftq.getResultSize()); result.setResults(results); log.debug("runQueryLucene: {}", result); return result; }
@SuppressWarnings("unchecked") @DataProvider public List<SearchResult> search(String searchText) throws Exception { FullTextSession fullTextSession = Search.getFullTextSession(exampleDao .getSession()); if (!indexRebuilded) { indexRebuilded = true; fullTextSession.createIndexer().startAndWait(); } MultiFieldQueryParser parser = new MultiFieldQueryParser( Version.LUCENE_31, new String[] { "label", "tags", "url", "summary" }, new StandardAnalyzer(Version.LUCENE_31)); org.apache.lucene.search.Query luceneQuery = parser.parse(searchText); FullTextQuery query = fullTextSession.createFullTextQuery(luceneQuery, Example.class); query.setFirstResult(0); query.setMaxResults(100); List<SearchResult> searchResults = new ArrayList<SearchResult>(); for (Example example : (List<Example>) query.list()) { SearchResult searchResult = new SearchResult(); PropertyUtils.copyProperties(searchResult, example); searchResults.add(searchResult); } return searchResults; }
public List<Float> scores( ){ List<Float> toReturn = new ArrayList<Float>( ); validateQuery( ); fullTextQuery.setProjection( FullTextQuery.SCORE ); for ( Object obj : fullTextQuery.list( ) ) { toReturn.add( ( Float ) ( (Object[] ) obj )[0] ); }; fullTextQuery.setProjection( FullTextQuery.THIS ); return toReturn; }
public List<String> explanations( ){ List<String> toReturn = new ArrayList<String>( ); validateQuery( ); fullTextQuery.setProjection( FullTextQuery.EXPLANATION ); for ( Object obj : fullTextQuery.list( ) ) { toReturn.add( ( (Explanation ) ( (Object[] ) obj )[0] ).toHtml( ) ); }; fullTextQuery.setProjection( FullTextQuery.THIS ); return toReturn; }
private FullTextQuery createQuery(String criteria) throws ParseException { // FIXME: Should not hardcode the analyzer QueryParser parser = new QueryParser("text", new StandardAnalyzer()); Query luceneQuery = parser.parse(criteria); return Search.createFullTextSession(session).createFullTextQuery(luceneQuery, Post.class); }
@Override public FullTextQuery getFullTextQuery(Query luceneQuery, Class<?>... entities) { FullTextQuery ftq = getFullTextSession().createFullTextQuery(luceneQuery, entities); /* hibernate-ogm 에서는 꼭 DatabaseRetrievalMethod.FIND_BY_ID 를 사용해야 합니다. */ ftq.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return ftq; }
@Override public <T> List<T> findAll(Class<T> clazz, Sort luceneSort) { if (isTraceEnabled) log.trace("엔티티[{}]의 모든 레코드를 조회합니다...", clazz); Query luceneQuery = getQueryBuilder(clazz).all().createQuery(); FullTextQuery ftq = getFullTextQuery(luceneQuery, clazz); if (luceneSort != null) ftq.setSort(luceneSort); return ftq.list(); }
@Override public List<Serializable> getAllIds(Class<?> clazz, Query luceneQuery, int firstResult, int maxResults, Sort sort, Criteria criteria) { List<Object[]> list = getProjections(clazz, luceneQuery, new String[] { FullTextQuery.ID }, firstResult, maxResults, sort, criteria); List<Serializable> ids = Lists.newArrayList(); for (Object[] fields : list) { ids.add((Serializable) fields[0]); } return ids; }
@Override public PaginatedList<Serializable> getIdPage(Class<?> clazz, Query luceneQuery, int pageNo, int pageSize, Sort sort, Criteria criteria) { int totalCount = count(clazz, luceneQuery); List<Object[]> list = getProjections(clazz, luceneQuery, new String[] { FullTextQuery.ID }, (pageNo - 1) * pageSize, pageSize, sort, criteria); List<Serializable> ids = Lists.newArrayList(); for (Object[] fields : list) { ids.add((Serializable) fields[0]); } return new PaginatedList<>(ids, pageNo, pageSize, totalCount); }
@Override public List<Serializable> getAllIds(Class<?> clazz, Query luceneQuery, int firstResult, int maxResults, Sort sort, Criteria criteria) { List<Object[]> list = getProjections(clazz, luceneQuery, new String[]{ FullTextQuery.ID }, firstResult, maxResults, sort, criteria); List<Serializable> ids = Lists.newArrayList(); for (Object[] fields : list) { ids.add((Serializable) fields[0]); } return ids; }
@Override public PaginatedList<Serializable> getIdPage(Class<?> clazz, Query luceneQuery, int pageNo, int pageSize, Sort sort, Criteria criteria) { long totalCount = count(clazz, luceneQuery); List<Object[]> list = getProjections(clazz, luceneQuery, new String[]{ FullTextQuery.ID }, (pageNo - 1) * pageSize, pageSize, sort, criteria); List<Serializable> ids = Lists.newArrayList(); for (Object[] fields : list) { ids.add((Serializable) fields[0]); } return new PaginatedList<>(ids, pageNo, pageSize, totalCount); }
/** * FullTextQuery 인스턴스를 생성합니다. * * @param fts FullTextSession instance. * @param luceneQuery the lucene query * @param clazz the clazz * @return the full text query */ public static FullTextQuery createFullTextQuery(FullTextSession fts, Query luceneQuery, Class<?> clazz) { FullTextQuery ftq = fts.createFullTextQuery(luceneQuery, clazz); // 기본값이 SKIP, QUERY 입니다. // ftq.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.QUERY); return ftq; }
@Test public void testTermQuery() throws Exception { buildIndex(fts); Transaction tx = fts.beginTransaction(); try { String userInput = "salesman"; Term term = new Term("description", userInput); TermQuery query = new TermQuery(term); log.debug("query: " + query.toString()); FullTextQuery ftq = fts.createFullTextQuery(query, Dvd.class); @SuppressWarnings("unchecked") List<Dvd> results = ftq.list(); Assertions.assertThat(results.size()).isEqualTo(descs.length); Assertions.assertThat(results.get(0).getDescription()).isEqualTo(descs[1]); for (Dvd dvd : results) { log.debug("Dev: " + dvd.getDescription()); } for (Object element : fts.createQuery("from " + Dvd.class.getName()).list()) { fts.delete(element); } } finally { tx.commit(); } }
@Test public void testKoreanFuzzyQuery() throws Exception { buildIndex(fts); try { // //TODO: 한글 분석기로는 FuzzyQuery가 제대로 작동하지 않는다. // String userInput = "포터"; FuzzyQuery luceneQuery = new FuzzyQuery(new Term("title", userInput), 0.4f); log.debug("Query=" + luceneQuery.toString()); FullTextQuery ftq = fts.createFullTextQuery(luceneQuery, Dvd.class); List<Dvd> results = ftq.list(); // Assertions.assertThat(results.size()).isEqualTo(3); // Assertions.assertThat(results.get(0).getTitle()).isEqualTo(titles[7]); for (Dvd dvd : results) { log.debug("Title=" + dvd.getTitle()); } } finally { for (Object element : fts.createQuery("from " + Dvd.class.getName()).list()) { fts.delete(element); } } }
@Test public void testPhaseQuery() throws Exception { buildIndex(fts); String userInput = "star trek"; StringTokenizer st = new StringTokenizer(userInput, " "); PhraseQuery query = new PhraseQuery(); while (st.hasMoreTokens()) { query.add(new Term("description", st.nextToken())); } log.debug("query=" + query.toString()); FullTextQuery ftq = fts.createFullTextQuery(query, Dvd.class); List<Dvd> results = ftq.list(); Assertions.assertThat(results.size()).isEqualTo(3); Assertions.assertThat(results.get(0).getDescription()).isEqualTo(descs[1]); for (Dvd dvd : results) { log.debug("Dvd=" + dvd); } for (Object element : fts.createQuery("from " + Dvd.class.getName()).list()) { fts.delete(element); } }
@Test public void testLuceneObjectsProjectionWithScroll() throws Exception { buildIndex(fts); Transaction tx = fts.beginTransaction(); QueryParser parser = new QueryParser(Version.LUCENE_36, "dept", new StandardAnalyzer(Version.LUCENE_36)); Query query = parser.parse("dept:ITech"); FullTextQuery ftq = fts.createFullTextQuery(query, Employee.class); ftq.setProjection("id", "lastname", "dept", FullTextQuery.THIS, FullTextQuery.SCORE, FullTextQuery.DOCUMENT, FullTextQuery.ID); ScrollableResults projections = ftq.scroll(); projections.beforeFirst(); projections.next(); Object[] projection = projections.get(); assertThat(projection[0]).isEqualTo(1000); assertThat(projection[1]).isEqualTo("Griffin"); assertThat(projection[2]).isEqualTo("ITech"); assertThat(projection[3].hashCode()).isEqualTo(fts.get(Employee.class, 1000).hashCode()); assertThat(projection[4]).isEqualTo(1.0F); assertThat(projection[5]).isInstanceOf(Document.class); assertThat(projection[6]).isEqualTo(1000); assertThat(projections.isFirst()).isTrue(); assertThat(((Employee) projection[3]).getId()).isEqualTo(1000); for (Object element : fts.createQuery("from " + Employee.class.getName()).list()) fts.delete(element); tx.commit(); }
@Override public FullTextQuery getFullTextQuery(Query luceneQuery, Class<?>... entities) { if (isTraceEnabled) log.trace("FullTextQuery를 생성합니다... luceneQuery=[{}], entities=[{}]", luceneQuery, StringTool.listToString(entities)); FullTextQuery ftq = getFullTextSession().createFullTextQuery(luceneQuery, entities); // 필수!!! object lookup 및 DB 조회 방법 설정 // ftq.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return ftq; }
@Override public IPagedList<Serializable> getIdPage(Class<?> clazz, Query luceneQuery, int pageNo, int pageSize, Sort luceneSort, Criteria criteria) { IPagedList<Object[]> list = getProjectionPage(clazz, luceneQuery, new String[] { FullTextQuery.ID }, pageNo, pageSize, luceneSort, criteria); List<Serializable> ids = Lists.newArrayList(); for (Object[] fields : list.getList()) { ids.add((Serializable) fields[0]); } return new PaginatedList<>(ids, pageNo, pageSize, list.getItemCount()); }
@Test public void hibernateSearchUsage() throws Exception { final Session session = openSession(); final FullTextSession fts = Search.getFullTextSession(session); Transaction transaction = fts.beginTransaction(); int itemCount = 10000; for (int i = 0; i < itemCount; i++) { Insurance insurance = new Insurance(); insurance.setName("Macif"); fts.persist(insurance); } transaction.commit(); fts.clear(); transaction = fts.beginTransaction(); final QueryBuilder b = fts.getSearchFactory() .buildQueryBuilder() .forEntity(Insurance.class) .get(); final Query lq = b.keyword().onField("name").matching("Macif").createQuery(); final FullTextQuery ftq = fts.createFullTextQuery(lq, Insurance.class); ftq.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); final List<Insurance> results = ftq.list(); Assertions.assertThat(results).hasSize(itemCount); for (Insurance o : results) fts.delete(o); transaction.commit(); fts.close(); }
/** * 全文检索 * @param page 分页对象 * @param query 关键字查询对象 * @param queryFilter 查询过滤对象 * @param sort 排序对象 * @return 分页对象 */ @SuppressWarnings("unchecked") public Page<T> search(Page<T> page, BooleanQuery query, BooleanQuery queryFilter, Sort sort){ // 按关键字查询 FullTextQuery fullTextQuery = getFullTextSession().createFullTextQuery(query, entityClass); // 过滤无效的内容 if(queryFilter != null){ fullTextQuery.setFilter(new CachingWrapperFilter(new QueryWrapperFilter(queryFilter))); } // 按时间排序 if(sort != null){ fullTextQuery.setSort(sort); } // 定义分页 page.setCount(fullTextQuery.getResultSize()); fullTextQuery.setFirstResult(page.getFirstResult()); fullTextQuery.setMaxResults(page.getMaxResults()); // 先从持久化上下文中查找对象,如果没有再从二级缓存中查找 fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SECOND_LEVEL_CACHE, DatabaseRetrievalMethod.QUERY); // 返回结果 page.setList(fullTextQuery.list()); return page; }