org.hibernate.search.jpa.FullTextQuery Java Examples
The following examples show how to use
org.hibernate.search.jpa.FullTextQuery.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ArtifactDaoImpl.java From artifact-listener with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public List<Artifact> searchByName(String searchTerm, ArtifactDeprecationStatus deprecation, Integer limit, Integer offset) { FullTextQuery query = getSearchByNameQuery(searchTerm, deprecation); // Sort List<SortField> sortFields = ImmutableList.<SortField>builder() .add(new SortField(Binding.artifact().group().getPath() + '.' + ArtifactGroup.GROUP_ID_SORT_FIELD_NAME, SortField.Type.STRING)) .add(new SortField(Artifact.ARTIFACT_ID_SORT_FIELD_NAME, SortField.Type.STRING)) .build(); query.setSort(new Sort(sortFields.toArray(new SortField[sortFields.size()]))); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } return (List<Artifact>) query.getResultList(); }
Example #2
Source File: HibernateSearchWithElasticsearchIT.java From hibernate-demos with Apache License 2.0 | 6 votes |
@Test public void queryOnMultipleFields() { EntityManager em = emf.createEntityManager(); inTransaction( em, tx -> { FullTextEntityManager ftem = Search.getFullTextEntityManager( em ); QueryBuilder qb = ftem.getSearchFactory() .buildQueryBuilder() .forEntity( VideoGame.class ) .get(); FullTextQuery query = ftem.createFullTextQuery( qb.keyword().onFields( "title", "description").matching( "samurai" ).createQuery(), VideoGame.class ); List<VideoGame> videoGames = query.getResultList(); assertThat( videoGames ).onProperty( "title" ).containsExactly( "Revenge of the Samurai", "Tanaka's return" ); } ); em.close(); }
Example #3
Source File: HibernateSearchWithElasticsearchIT.java From hibernate-demos with Apache License 2.0 | 6 votes |
@Test public void queryOnSingleField() { EntityManager em = emf.createEntityManager(); inTransaction( em, tx -> { FullTextEntityManager ftem = Search.getFullTextEntityManager( em ); QueryBuilder qb = ftem.getSearchFactory() .buildQueryBuilder() .forEntity( VideoGame.class ) .get(); FullTextQuery query = ftem.createFullTextQuery( qb.keyword().onField( "title" ).matching( "samurai" ).createQuery(), VideoGame.class ); List<VideoGame> videoGames = query.getResultList(); assertThat( videoGames ).onProperty( "title" ).containsExactly( "Revenge of the Samurai" ); } ); em.close(); }
Example #4
Source File: HibernateSearchWithElasticsearchIT.java From hibernate-demos with Apache License 2.0 | 6 votes |
@Test public void wildcardQuery() { EntityManager em = emf.createEntityManager(); inTransaction( em, tx -> { FullTextEntityManager ftem = Search.getFullTextEntityManager( em ); QueryBuilder qb = ftem.getSearchFactory() .buildQueryBuilder() .forEntity( VideoGame.class ) .get(); FullTextQuery query = ftem.createFullTextQuery( qb.keyword().wildcard().onFields( "title", "description").matching( "sam*" ).createQuery(), VideoGame.class ); List<VideoGame> videoGames = query.getResultList(); assertThat( videoGames ).onProperty( "title" ).containsExactly( "Revenge of the Samurai", "Tanaka's return" ); } ); em.close(); }
Example #5
Source File: HibernateSearchWithElasticsearchIT.java From hibernate-demos with Apache License 2.0 | 6 votes |
@Test public void rangeQuery() { EntityManager em = emf.createEntityManager(); inTransaction( em, tx -> { FullTextEntityManager ftem = Search.getFullTextEntityManager( em ); QueryBuilder qb = ftem.getSearchFactory() .buildQueryBuilder() .forEntity( VideoGame.class ) .get(); FullTextQuery query = ftem.createFullTextQuery( qb.range() .onField( "rating" ) .from( 2 ) .to( 9 ) .createQuery(), VideoGame.class ); List<VideoGame> videoGames = query.getResultList(); assertThat( videoGames ).onProperty( "title" ).containsOnly( "Revenge of the Samurai", "Ninja Castle" ); } ); em.close(); }
Example #6
Source File: HibernateSearchWithElasticsearchIT.java From hibernate-demos with Apache License 2.0 | 6 votes |
@Test public void queryString() { EntityManager em = emf.createEntityManager(); inTransaction( em, tx -> { FullTextEntityManager ftem = Search.getFullTextEntityManager( em ); QueryBuilder qb = ftem.getSearchFactory() .buildQueryBuilder() .forEntity( VideoGame.class ) .get(); FullTextQuery query = ftem.createFullTextQuery( ElasticsearchQueries.fromQueryString( "title:sam* OR description:sam*" ), VideoGame.class ); List<VideoGame> videoGames = query.getResultList(); assertThat( videoGames ).onProperty( "title" ).containsExactly( "Revenge of the Samurai", "Tanaka's return" ); } ); em.close(); }
Example #7
Source File: ProjectDaoImpl.java From artifact-listener with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public List<Project> searchByName(String searchTerm, Integer limit, Integer offset) { FullTextQuery query = getSearchByNameQuery(searchTerm); // Sort List<SortField> sortFields = ImmutableList.<SortField>builder() .add(new SortField(Project.NAME_SORT_FIELD_NAME, SortField.Type.STRING)) .build(); query.setSort(new Sort(sortFields.toArray(new SortField[sortFields.size()]))); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } return (List<Project>) query.getResultList(); }
Example #8
Source File: ProjectDaoImpl.java From artifact-listener with Apache License 2.0 | 6 votes |
private FullTextQuery getSearchByNameQuery(String searchTerm) { FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager()); QueryBuilder projectQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder() .forEntity(Project.class).get(); BooleanJunction<?> booleanJunction = projectQueryBuilder.bool(); if (StringUtils.hasText(searchTerm)) { booleanJunction.must(projectQueryBuilder .keyword() .fuzzy().withPrefixLength(1).withThreshold(0.8F) .onField(Binding.project().name().getPath()) .matching(searchTerm) .createQuery()); } else { booleanJunction.must(projectQueryBuilder.all().createQuery()); } return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), Project.class); }
Example #9
Source File: UserDaoImpl.java From artifact-listener with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public List<User> search(String searchTerm, Integer limit, Integer offset) { FullTextQuery query = getSearchQuery(searchTerm); query.setSort(new Sort(new SortField(Binding.user().userName().getPath(), SortField.Type.STRING))); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } return (List<User>) query.getResultList(); }
Example #10
Source File: UserDaoImpl.java From artifact-listener with Apache License 2.0 | 6 votes |
private FullTextQuery getSearchQuery(String searchTerm) { FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager()); QueryBuilder userQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder() .forEntity(User.class).get(); BooleanJunction<?> booleanJunction = userQueryBuilder.bool(); if (StringUtils.hasText(searchTerm)) { booleanJunction.must(userQueryBuilder .keyword() .fuzzy().withPrefixLength(1).withThreshold(0.8F) .onField(Binding.user().userName().getPath()) .andField(Binding.user().fullName().getPath()) .matching(searchTerm) .createQuery()); } else { booleanJunction.must(userQueryBuilder.all().createQuery()); } return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), User.class); }
Example #11
Source File: ArtifactDaoImpl.java From artifact-listener with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public List<Artifact> searchRecommended(String searchTerm, Integer limit, Integer offset) throws ServiceException { FullTextQuery query = getSearchRecommendedQuery(searchTerm); if (query == null) { return Lists.newArrayListWithExpectedSize(0); } // Sort List<SortField> sortFields = ImmutableList.<SortField>builder() .add(new SortField(Binding.artifact().followersCount().getPath(), SortField.Type.LONG, true)) .add(new SortField(Binding.artifact().group().getPath() + '.' + ArtifactGroup.GROUP_ID_SORT_FIELD_NAME, SortField.Type.STRING)) .add(new SortField(Artifact.ARTIFACT_ID_SORT_FIELD_NAME, SortField.Type.STRING)) .build(); query.setSort(new Sort(sortFields.toArray(new SortField[sortFields.size()]))); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } return (List<Artifact>) query.getResultList(); }
Example #12
Source File: ArticleRepositoryImpl.java From wallride with Apache License 2.0 | 6 votes |
@Override public Page<Article> search(ArticleSearchRequest request, Pageable pageable) { Session session = (Session) entityManager.getDelegate(); Criteria criteria = session.createCriteria(Article.class) .setFetchMode("cover", FetchMode.JOIN) .setFetchMode("user", FetchMode.JOIN) .setFetchMode("categories", FetchMode.JOIN) .setFetchMode("tags", FetchMode.JOIN) .setFetchMode("customFieldValues", FetchMode.JOIN) .setFetchMode("customFieldValues.customField", FetchMode.JOIN); FullTextQuery persistenceQuery = buildFullTextQuery(request, pageable, criteria); int resultSize = persistenceQuery.getResultSize(); List<Article> results = persistenceQuery.getResultList(); return new PageImpl<>(results, pageable, resultSize); }
Example #13
Source File: PageRepositoryImpl.java From wallride with Apache License 2.0 | 6 votes |
@Override public org.springframework.data.domain.Page<Page> search(PageSearchRequest request, Pageable pageable) { Session session = (Session) entityManager.getDelegate(); Criteria criteria = session.createCriteria(Page.class) .setFetchMode("cover", FetchMode.JOIN) .setFetchMode("author", FetchMode.JOIN) .setFetchMode("categories", FetchMode.JOIN) .setFetchMode("tags", FetchMode.JOIN) .setFetchMode("customFieldValues", FetchMode.JOIN) .setFetchMode("customFieldValues.customField", FetchMode.JOIN) .setFetchMode("parent", FetchMode.JOIN) .setFetchMode("children", FetchMode.JOIN); FullTextQuery persistenceQuery = buildFullTextQuery(request, pageable, criteria); int resultSize = persistenceQuery.getResultSize(); List<Page> results = persistenceQuery.getResultList(); return new PageImpl<>(results, pageable, resultSize); }
Example #14
Source File: HibernateSearchUtil.java From javaee-lab with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public <T> List<Serializable> findId(Class<T> clazz, SearchParameters sp, List<SingularAttribute<?, ?>> availableProperties) { //log.info("Searching {} with terms : {} with available Properties: {}", new Object[]{clazz.getSimpleName(), sp.getTerms(), availableProperties}); FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager); Query query = sp.getLuceneQueryBuilder().build(fullTextEntityManager, sp, availableProperties); if (query == null) { return null; } FullTextQuery ftq = fullTextEntityManager.createFullTextQuery( // query, clazz); ftq.setProjection("id"); if (sp.getMaxResults() > 0) { ftq.setMaxResults(sp.getMaxResults()); } List<Serializable> ids = newArrayList(); List<Object[]> resultList = ftq.getResultList(); for (Object[] result : resultList) { ids.add((Serializable) result[0]); } return ids; }
Example #15
Source File: HibernateSearchUtil.java From javaee-lab with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public <T> List<T> find(Class<T> clazz, SearchParameters sp, List<SingularAttribute<?, ?>> availableProperties) { // log.info("Searching {} with terms : {} with available Properties: {}", new Object[]{clazz.getSimpleName(), sp.getTerms(), availableProperties}); FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager); Query query = sp.getLuceneQueryBuilder().build(fullTextEntityManager, sp, availableProperties); if (query == null) { return null; } FullTextQuery ftq = fullTextEntityManager.createFullTextQuery( // query, clazz); if (sp.getMaxResults() > 0) { ftq.setMaxResults(sp.getMaxResults()); } return ftq.getResultList(); }
Example #16
Source File: SearchServiceBeanTest.java From development with Apache License 2.0 | 6 votes |
@Test public void searchSubscriptions() throws Exception { DataServiceBean bean = spy(new DataServiceBean()); SubscriptionSearchServiceBean ssb = spy( new SubscriptionSearchServiceBean()); doReturn(bean).when(ssb).getDm(); FullTextEntityManager ftem = mock(FullTextEntityManager.class, Mockito.RETURNS_DEEP_STUBS); doReturn(ftem).when(ssb).getFtem(); Subscription sub = new Subscription(); sub.setKey(1L); FullTextQuery fullTextQuery = mock(FullTextQuery.class); when(ftem.createFullTextQuery(any(BooleanQuery.class), any(Class.class))).thenReturn(fullTextQuery); doReturn(Arrays.asList(sub)).when(fullTextQuery).getResultList(); Collection<Long> result = ssb.searchSubscriptions("searchphrase"); assertTrue(result.contains(new Long(1L))); }
Example #17
Source File: HibernateSearch5InstrumentationTest.java From apm-agent-java with Apache License 2.0 | 6 votes |
@Test void performMultiResultLuceneIndexSearch() { FullTextEntityManager fullTextSession = Search.getFullTextEntityManager(entityManager); QueryBuilder builder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Dog.class).get(); BooleanJunction<BooleanJunction> bool = builder.bool(); bool.should(builder.keyword().wildcard().onField("name").matching("dog*").createQuery()); Query query = bool.createQuery(); FullTextQuery ftq = fullTextSession.createFullTextQuery(query, Dog.class); List<Dog> result = (List<Dog>) ftq.getResultList(); assertAll(() -> { assertThat(result.size()).isEqualTo(2); assertApmSpanInformation(reporter, "name:dog*", "list"); }); }
Example #18
Source File: ArtifactDaoImpl.java From artifact-listener with Apache License 2.0 | 5 votes |
private FullTextQuery getSearchByNameQuery(String searchTerm, ArtifactDeprecationStatus deprecation) { FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager()); QueryBuilder artifactQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder() .forEntity(Artifact.class).get(); BooleanJunction<?> booleanJunction = artifactQueryBuilder.bool(); if (deprecation != null) { booleanJunction.must(artifactQueryBuilder .keyword() .onField(Binding.artifact().deprecationStatus().getPath()) .matching(deprecation) .createQuery()); } if (StringUtils.hasText(searchTerm)) { booleanJunction.must(artifactQueryBuilder .keyword() .fuzzy().withPrefixLength(1).withThreshold(0.8F) .onField(Binding.artifact().artifactId().getPath()) .andField(Binding.artifact().group().groupId().getPath()) .matching(searchTerm) .createQuery()); } else { booleanJunction.must(artifactQueryBuilder.all().createQuery()); } return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), Artifact.class); }
Example #19
Source File: ArtifactDaoImpl.java From artifact-listener with Apache License 2.0 | 5 votes |
private FullTextQuery getSearchRecommendedQuery(String searchTerm) throws ServiceException { if (!StringUtils.hasText(searchTerm)) { return null; } FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager()); QueryBuilder artifactQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder() .forEntity(Artifact.class).get(); BooleanJunction<?> booleanJunction = artifactQueryBuilder.bool(); booleanJunction.must(artifactQueryBuilder .keyword() .onField(Binding.artifact().deprecationStatus().getPath()) .matching(ArtifactDeprecationStatus.NORMAL) .createQuery()); try { searchTerm = LuceneUtils.getSimilarityQuery(searchTerm, 2); String[] fields = new String[] { Binding.artifact().artifactId().getPath(), Binding.artifact().group().groupId().getPath() }; Analyzer analyzer = Search.getFullTextEntityManager(getEntityManager()).getSearchFactory().getAnalyzer(Artifact.class); MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer); parser.setDefaultOperator(MultiFieldQueryParser.AND_OPERATOR); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.add(parser.parse(searchTerm), BooleanClause.Occur.MUST); booleanJunction.must(booleanQuery); } catch (ParseException e) { throw new ServiceException(String.format("Error parsing request: %1$s", searchTerm), e); } return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), Artifact.class); }
Example #20
Source File: ArtifactDaoImpl.java From artifact-listener with Apache License 2.0 | 5 votes |
@Override public int countSearchRecommended(String searchTerm) throws ServiceException { FullTextQuery query = getSearchRecommendedQuery(searchTerm); if (query == null) { return 0; } return query.getResultSize(); }
Example #21
Source File: HikeQueryTest.java From hibernate-demos with Apache License 2.0 | 5 votes |
@Test public void canSearchUsingFullTextQuery() { EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); //Add full-text superpowers to any EntityManager: FullTextEntityManager ftem = Search.getFullTextEntityManager(entityManager); // Optionally use the QueryBuilder to simplify Query definition: QueryBuilder b = ftem.getSearchFactory().buildQueryBuilder().forEntity( Hike.class ).get(); // A lucene query to look for hike to the Carisbrooke castle: // Note that the query looks for "cariboke" instead of "Carisbrooke" Query lq = b.keyword().onField("description").matching("carisbroke castle").createQuery(); //Transform the Lucene Query in a JPA Query: FullTextQuery ftQuery = ftem.createFullTextQuery(lq, Hike.class); //This is a requirement when using Hibernate OGM instead of ORM: ftQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID ); // List matching hikes List<Hike> hikes = ftQuery.getResultList(); assertThat( hikes ).onProperty( "description" ).containsOnly( "Exploring Carisbrooke Castle" ); entityManager.getTransaction().commit(); entityManager.close(); }
Example #22
Source File: HibernateSearchWithElasticsearchIT.java From hibernate-demos with Apache License 2.0 | 5 votes |
@Test public void projectionWithTransformer() { EntityManager em = emf.createEntityManager(); inTransaction( em, tx -> { FullTextEntityManager ftem = Search.getFullTextEntityManager( em ); QueryBuilder qb = ftem.getSearchFactory() .buildQueryBuilder() .forEntity( VideoGame.class ) .get(); FullTextQuery query = ftem.createFullTextQuery( qb.keyword() .onField( "tags" ) .matching( "round-based" ) .createQuery(), VideoGame.class ) .setProjection( "title", "publisher.name", "release" ) .setResultTransformer( new BasicTransformerAdapter() { @Override public VideoGameDto transformTuple(Object[] tuple, String[] aliases) { return new VideoGameDto( (String) tuple[0], (String) tuple[1], (Date) tuple[2] ); } } ); VideoGameDto projection = (VideoGameDto) query.getSingleResult(); assertThat( projection.getTitle() ).isEqualTo( "Tanaka's return" ); assertThat( projection.getPublisherName() ).isEqualTo( "Samurai Games, Inc." ); assertThat( projection.getRelease() ).isEqualTo( new GregorianCalendar( 2011, 2, 13 ).getTime() ); } ); em.close(); }
Example #23
Source File: HibernateSearch5InstrumentationTest.java From apm-agent-java with Apache License 2.0 | 5 votes |
@Test void performLuceneIndexSearch() { FullTextEntityManager fullTextSession = Search.getFullTextEntityManager(entityManager); FullTextQuery ftq = fullTextSession.createFullTextQuery(createQueryForDog1(), Dog.class); List<Dog> result = (List<Dog>) ftq.getResultList(); assertAll(() -> { assertThat(result.size()).isEqualTo(1); assertThat(result.get(0).getName()).isEqualTo("dog1"); assertApmSpanInformation(reporter, "name:dog1", "list"); }); }
Example #24
Source File: CustomFieldRepositoryImpl.java From wallride with Apache License 2.0 | 5 votes |
@Override public List<Long> searchForId(CustomFieldSearchRequest request) { FullTextQuery persistenceQuery = buildFullTextQuery(request, Pageable.unpaged(), null); persistenceQuery.setProjection("id"); List<Object[]> results = persistenceQuery.getResultList(); List<Long> nos = results.stream().map(result -> (long) result[0]).collect(Collectors.toList()); return nos; }
Example #25
Source File: CustomFieldRepositoryImpl.java From wallride with Apache License 2.0 | 5 votes |
@Override public Page<CustomField> search(CustomFieldSearchRequest request, Pageable pageable) { Session session = (Session) entityManager.getDelegate(); Criteria criteria = session.createCriteria(CustomField.class) .setFetchMode("options", FetchMode.JOIN); FullTextQuery persistenceQuery = buildFullTextQuery(request, pageable, criteria); int resultSize = persistenceQuery.getResultSize(); List<CustomField> results = persistenceQuery.getResultList(); return new PageImpl<>(results, pageable, resultSize); }
Example #26
Source File: UserRepositoryImpl.java From wallride with Apache License 2.0 | 5 votes |
@Override public List<Long> searchForId(UserSearchRequest request) { FullTextQuery persistenceQuery = buildFullTextQuery(request, Pageable.unpaged(), null); persistenceQuery.setProjection("id"); List<Object[]> results = persistenceQuery.getResultList(); List<Long> nos = results.stream().map(result -> (long) result[0]).collect(Collectors.toList()); return nos; }
Example #27
Source File: UserRepositoryImpl.java From wallride with Apache License 2.0 | 5 votes |
@Override public Page<User> search(UserSearchRequest request, Pageable pageable) { Session session = (Session) entityManager.getDelegate(); Criteria criteria = session.createCriteria(User.class); FullTextQuery persistenceQuery = buildFullTextQuery(request, pageable, criteria); int resultSize = persistenceQuery.getResultSize(); List<User> results = persistenceQuery.getResultList(); return new PageImpl<>(results, pageable, resultSize); }
Example #28
Source File: ArticleRepositoryImpl.java From wallride with Apache License 2.0 | 5 votes |
@Override public List<Long> searchForId(ArticleSearchRequest request) { FullTextQuery persistenceQuery = buildFullTextQuery(request, Pageable.unpaged(), null); persistenceQuery.setProjection("id"); List<Object[]> results = persistenceQuery.getResultList(); List<Long> nos = results.stream().map(result -> (long) result[0]).collect(Collectors.toList()); return nos; }
Example #29
Source File: PageRepositoryImpl.java From wallride with Apache License 2.0 | 5 votes |
@Override public List<Long> searchForId(PageSearchRequest request) { FullTextQuery persistenceQuery = buildFullTextQuery(request, Pageable.unpaged(), null); persistenceQuery.setProjection("id"); List<Object[]> results = persistenceQuery.getResultList(); List<Long> nos = results.stream().map(result -> (long) result[0]).collect(Collectors.toList()); return nos; }
Example #30
Source File: BookDaoImpl.java From maven-framework-project with MIT License | 4 votes |
@Override public QueryResult<Book> query(String keyword, int start, int pagesize,Analyzer analyzer,String...field) throws Exception{ QueryResult<Book> queryResult=new QueryResult<Book>(); List<Book> books=new ArrayList<Book>(); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em); //使用Hibernate Search api查询 从多个字段匹配 name、description、authors.name //QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Book.class ).get(); //Query luceneQuery = qb.keyword().onFields(field).matching(keyword).createQuery(); //使用lucene api查询 从多个字段匹配 name、description、authors.name MultiFieldQueryParser queryParser=new MultiFieldQueryParser(Version.LUCENE_36,new String[]{"name","description","authors.name"}, analyzer); Query luceneQuery=queryParser.parse(keyword); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(luceneQuery); int searchresultsize = fullTextQuery.getResultSize(); queryResult.setSearchresultsize(searchresultsize); fullTextQuery.setFirstResult(start); fullTextQuery.setMaxResults(pagesize); //设置按id排序 fullTextQuery.setSort(new Sort(new SortField("id", SortField.INT ,true))); //高亮设置 SimpleHTMLFormatter formatter=new SimpleHTMLFormatter("<b><font color='red'>", "</font></b>"); QueryScorer queryScorer=new QueryScorer(luceneQuery); Highlighter highlighter=new Highlighter(formatter, queryScorer); @SuppressWarnings("unchecked") List<Book> tempresult = fullTextQuery.getResultList(); for (Book book : tempresult) { String highlighterString=null; try { //高亮name highlighterString=highlighter.getBestFragment(analyzer, "name", book.getName()); if(highlighterString!=null){ book.setName(highlighterString); } //高亮authors.name Set<Author> authors = book.getAuthors(); for (Author author : authors) { highlighterString=highlighter.getBestFragment(analyzer, "authors.name", author.getName()); if(highlighterString!=null){ author.setName(highlighterString); } } //高亮description highlighterString=highlighter.getBestFragment(analyzer, "description", book.getDescription()); if(highlighterString!=null){ book.setDescription(highlighterString); } } catch (Exception e) { } books.add(book); } queryResult.setSearchresult(books); return queryResult; }