org.hibernate.search.jpa.Search Java Examples

The following examples show how to use org.hibernate.search.jpa.Search. 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: HibernateSearch5InstrumentationTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: ArtifactDaoImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
@Override
public List<Artifact> searchAutocompleteWithoutProject(String searchPattern, Integer limit, Integer offset) throws ServiceException {
	String[] searchFields = new String[] {
			Binding.artifact().artifactId().getPath(),
			Binding.artifact().group().groupId().getPath()
	};
	
	QueryBuilder queryBuilder = Search.getFullTextEntityManager(getEntityManager()).getSearchFactory().buildQueryBuilder()
			.forEntity(Artifact.class).get();
	
	Query notDeprecatedQuery = queryBuilder.keyword().onField(Binding.artifact().deprecationStatus().getPath()).matching(ArtifactDeprecationStatus.NORMAL).createQuery();
	Query withoutProjectQuery = queryBuilder.keyword().onField(Binding.artifact().project().getPath()).matching(null).createQuery();

	BooleanJunction<?> booleanJunction = queryBuilder.bool()
			.must(notDeprecatedQuery)
			.must(withoutProjectQuery);
	
	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(); 
	Sort sort = new Sort(sortFields.toArray(new SortField[sortFields.size()]));
	return hibernateSearchService.searchAutocomplete(getObjectClass(), searchFields, searchPattern, booleanJunction.createQuery(), limit, offset, sort);
}
 
Example #3
Source File: ArtifactDaoImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
@Override
public List<Artifact> searchAutocomplete(String searchPattern, Integer limit, Integer offset) throws ServiceException {
	String[] searchFields = new String[] {
			Binding.artifact().artifactId().getPath(),
			Binding.artifact().group().groupId().getPath()
	};
	
	QueryBuilder queryBuilder = Search.getFullTextEntityManager(getEntityManager()).getSearchFactory().buildQueryBuilder()
			.forEntity(Artifact.class).get();
	
	Query luceneQuery = queryBuilder.keyword().onField(Binding.artifact().deprecationStatus().getPath()).matching(ArtifactDeprecationStatus.NORMAL).createQuery();
	
	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(); 
	Sort sort = new Sort(sortFields.toArray(new SortField[sortFields.size()]));
	return hibernateSearchService.searchAutocomplete(getObjectClass(), searchFields, searchPattern, luceneQuery, limit, offset, sort);
}
 
Example #4
Source File: UserDaoImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: ProjectDaoImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: HibernateSearchWithElasticsearchIT.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
@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: HibernateSearchWithElasticsearchIT.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: HibernateSearchWithElasticsearchIT.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: HibernateSearchWithElasticsearchIT.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: HibernateSearchWithElasticsearchIT.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: HibernateSearchWithElasticsearchIT.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void manualIndexing() {
	EntityManager em = emf.createEntityManager();

	FullTextEntityManager ftem = Search.getFullTextEntityManager( em );
	ftem.getTransaction().begin();

	VideoGame game = ftem.find( VideoGame.class, 311 );
	ftem.index( game );

	ftem.getTransaction().commit();
}
 
Example #12
Source File: ArtifactDaoImpl.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: ArtifactDaoImpl.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: HibernateSearch5InstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@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 #15
Source File: MagicCardsCollectionBean.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
public List<MagicCard> findByName(String name) {
	FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager( em );
	QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity( MagicCard.class ).get();

	Query query = queryBuilder.keyword().onField( "name" ).matching( name ).createQuery();
	return fullTextEntityManager.createFullTextQuery( query, MagicCard.class ).getResultList();
}
 
Example #16
Source File: RegistrationExecutor.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Member findWithEmail(EntityManager em, String email) {
	FullTextEntityManager ftem = Search.getFullTextEntityManager( em );
	QueryBuilder b = ftem.getSearchFactory().buildQueryBuilder().forEntity( Member.class ).get();
	Query lq = b.keyword().wildcard().onField( "email" ).matching( email ).createQuery();
	Object uniqueResult = ftem.createFullTextQuery( lq ).getSingleResult();
	return (Member) uniqueResult;
}
 
Example #17
Source File: HibernateSearchIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testD_whenAdditionalTestDataInserted_thenIndexUpdatedAutomatically() {

    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    int indexSize = fullTextEntityManager.getSearchFactory()
        .getStatistics()
        .getNumberOfIndexedEntities(Product.class.getName());

    assertEquals(products.size(), indexSize);
}
 
Example #18
Source File: HibernateSearchIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testB_whenIndexInitialized_thenCorrectIndexSize() throws InterruptedException {

    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    fullTextEntityManager.createIndexer()
        .startAndWait();
    int indexSize = fullTextEntityManager.getSearchFactory()
        .getStatistics()
        .getNumberOfIndexedEntities(Product.class.getName());

    assertEquals(products.size() - 1, indexSize);
}
 
Example #19
Source File: ProductSearchDao.java    From tutorials with MIT License 5 votes vote down vote up
private QueryBuilder getQueryBuilder() {

        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

        return fullTextEntityManager.getSearchFactory()
            .buildQueryBuilder()
            .forEntity(Product.class)
            .get();
    }
 
Example #20
Source File: HikeQueryTest.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@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 #21
Source File: HibernateSearchWithElasticsearchIT.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: IndexHelper.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
public void checkIndexOnStartup() {
	//log.info("Observed event {1} from Thread {0}", Thread.currentThread().getName(), App.INIT_SUCCESS);

	// See if we need to rebuild the index during startup ...
	FullTextEntityManager ftEm = Search.getFullTextEntityManager(entityManager);
	SearchFactory searchFactory = ftEm.getSearchFactory();
	ReaderProvider readerProvider = searchFactory.getReaderProvider();
	IndexReader reader = readerProvider.openReader(searchFactory.getDirectoryProviders(NodeDocumentVersion.class)[0]);
	int maxDoc = 0;

	try {
		maxDoc = reader.maxDoc();
	} finally {
		readerProvider.closeReader(reader);
	}

	if (maxDoc == 0) {
		log.warn("No objects indexed ... rebuilding Lucene search index from database ...");
		long _exit = 0L;
		long _entr = System.currentTimeMillis();

		try {
			int docs = doRebuildIndex();
			_exit = System.currentTimeMillis();
			log.info("Took " + (_exit - _entr)
					+ " (ms) to re-build the index containing " + docs
					+ " documents.");
		} catch (Exception exc) {
			if (exc instanceof RuntimeException) {
				throw (RuntimeException) exc;
			} else {
				throw new RuntimeException(exc);
			}
		}

		// build the spell checker index off of the HS index.
		buildSpellCheckerIndex(searchFactory);
	}
}
 
Example #23
Source File: IndexManger.java    From maven-framework-project with MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	//重建索引
	FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
	
	fullTextEntityManager.createIndexer().startAndWait();
}
 
Example #24
Source File: CustomFieldRepositoryImpl.java    From wallride with Apache License 2.0 4 votes vote down vote up
public FullTextQuery buildFullTextQuery(CustomFieldSearchRequest request, Pageable pageable, Criteria criteria) {
	FullTextEntityManager fullTextEntityManager =  Search.getFullTextEntityManager(entityManager);
	QueryBuilder qb = fullTextEntityManager.getSearchFactory()
			.buildQueryBuilder()
			.forEntity(CustomField.class)
			.get();
	
	@SuppressWarnings("rawtypes")
	BooleanJunction<BooleanJunction> junction = qb.bool();
	junction.must(qb.all().createQuery());

	if (StringUtils.hasText(request.getKeyword())) {
		Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
		String[] fields = new String[] {
				"name", "code", "description"
		};
		MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
		parser.setDefaultOperator(QueryParser.Operator.AND);
		Query query = null;
		try {
			query = parser.parse(request.getKeyword());
		}
		catch (ParseException e1) {
			try {
				query = parser.parse(QueryParser.escape(request.getKeyword()));
			}
			catch (ParseException e2) {
				throw new RuntimeException(e2);
			}
		}
		junction.must(query);
	}

	if (StringUtils.hasText(request.getLanguage())) {
		junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
	}

	Query searchQuery = junction.createQuery();
	
	Sort sort = new Sort(new SortField("idx", SortField.Type.INT));

	FullTextQuery persistenceQuery = fullTextEntityManager
			.createFullTextQuery(searchQuery, CustomField.class)
			.setCriteriaQuery(criteria)
			.setSort(sort);
	if (pageable.isPaged()) {
		persistenceQuery.setFirstResult((int) pageable.getOffset());
		persistenceQuery.setMaxResults(pageable.getPageSize());
	}
	return persistenceQuery;
}
 
Example #25
Source File: SearchIndexUtils.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void rebuildSearchIndex() throws InterruptedException {
	FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager());
	fullTextEntityManager.createIndexer().startAndWait();
}
 
Example #26
Source File: CategoryRepositoryImpl.java    From wallride with Apache License 2.0 4 votes vote down vote up
@Override
public Page<Category> search(CategorySearchRequest request, Pageable pageable) {
	FullTextEntityManager fullTextEntityManager =  Search.getFullTextEntityManager(entityManager);
	QueryBuilder qb = fullTextEntityManager.getSearchFactory()
			.buildQueryBuilder()
			.forEntity(Category.class)
			.get();
	
	@SuppressWarnings("rawtypes")
	BooleanJunction<BooleanJunction> junction = qb.bool();
	junction.must(qb.all().createQuery());

	if (StringUtils.hasText(request.getKeyword())) {
		Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
		String[] fields = new String[] {
				"name"
		};
		MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
		parser.setDefaultOperator(QueryParser.Operator.AND);
		Query query = null;
		try {
			query = parser.parse(request.getKeyword());
		}
		catch (ParseException e1) {
			try {
				query = parser.parse(QueryParser.escape(request.getKeyword()));
			}
			catch (ParseException e2) {
				throw new RuntimeException(e2);
			}
		}
		junction.must(query);
	}

	if (StringUtils.hasText(request.getLanguage())) {
		junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
	}

	Query searchQuery = junction.createQuery();
	
	Session session = (Session) entityManager.getDelegate();
	Criteria criteria = session.createCriteria(Category.class);

	Sort sort = new Sort(new SortField("sortName", SortField.Type.STRING));

	FullTextQuery persistenceQuery = fullTextEntityManager
			.createFullTextQuery(searchQuery, Category.class)
			.setCriteriaQuery(criteria)
			.setSort(sort);
	if (pageable.isPaged()) {
		persistenceQuery.setFirstResult((int) pageable.getOffset());
		persistenceQuery.setMaxResults(pageable.getPageSize());
	}

	int resultSize = persistenceQuery.getResultSize();

	@SuppressWarnings("unchecked")
	List<Category> results = persistenceQuery.getResultList();
	return new PageImpl<>(results, pageable, resultSize);
}
 
Example #27
Source File: UserRepositoryImpl.java    From wallride with Apache License 2.0 4 votes vote down vote up
private FullTextQuery buildFullTextQuery(UserSearchRequest request, Pageable pageable, Criteria criteria) {
		FullTextEntityManager fullTextEntityManager =  Search.getFullTextEntityManager(entityManager);
		QueryBuilder qb = fullTextEntityManager.getSearchFactory()
				.buildQueryBuilder()
				.forEntity(User.class)
				.get();

		@SuppressWarnings("rawtypes")
		BooleanJunction<BooleanJunction> junction = qb.bool();
		junction.must(qb.all().createQuery());

		if (StringUtils.hasText(request.getKeyword())) {
			Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
			String[] fields = new String[] {
					"loginId",
					"name.firstName", "name.lastName",
			};
			MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
			parser.setDefaultOperator(QueryParser.Operator.AND);
			Query query = null;
			try {
				query = parser.parse(request.getKeyword());
			}
			catch (ParseException e1) {
				try {
					query = parser.parse(QueryParser.escape(request.getKeyword()));
				}
				catch (ParseException e2) {
					throw new RuntimeException(e2);
				}
			}
			junction.must(query);
		}

		if (!CollectionUtils.isEmpty(request.getRoles())) {
			for (User.Role role : request.getRoles()) {
				junction.must(qb.keyword().onField("roles").matching(role).createQuery());
			}
		}

		Query searchQuery = junction.createQuery();

		Sort sort = new Sort(new SortField("sortId", SortField.Type.LONG, false));

		FullTextQuery persistenceQuery = fullTextEntityManager
				.createFullTextQuery(searchQuery, User.class)
				.setCriteriaQuery(criteria)
//				.setProjection("id")
				.setSort(sort);
		if (pageable.isPaged()) {
			persistenceQuery.setFirstResult((int) pageable.getOffset());
			persistenceQuery.setMaxResults(pageable.getPageSize());
		}
		return persistenceQuery;
	}
 
Example #28
Source File: TagRepositoryImpl.java    From wallride with Apache License 2.0 4 votes vote down vote up
@Override
public Page<Tag> search(TagSearchRequest request, Pageable pageable) {
	FullTextEntityManager fullTextEntityManager =  Search.getFullTextEntityManager(entityManager);
	QueryBuilder qb = fullTextEntityManager.getSearchFactory()
			.buildQueryBuilder()
			.forEntity(Tag.class)
			.get();
	
	@SuppressWarnings("rawtypes")
	BooleanJunction<BooleanJunction> junction = qb.bool();
	junction.must(qb.all().createQuery());

	if (StringUtils.hasText(request.getKeyword())) {
		Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
		String[] fields = new String[] {
				"name"
		};
		MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
		parser.setDefaultOperator(QueryParser.Operator.AND);
		Query query = null;
		try {
			query = parser.parse(request.getKeyword());
		}
		catch (ParseException e1) {
			try {
				query = parser.parse(QueryParser.escape(request.getKeyword()));
			}
			catch (ParseException e2) {
				throw new RuntimeException(e2);
			}
		}
		junction.must(query);
	}

	if (StringUtils.hasText(request.getLanguage())) {
		junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
	}

	Query searchQuery = junction.createQuery();
	
	Session session = (Session) entityManager.getDelegate();
	Criteria criteria = session.createCriteria(Tag.class);

	Sort sort = new Sort(new SortField("sortName", SortField.Type.STRING));

	FullTextQuery persistenceQuery = fullTextEntityManager
			.createFullTextQuery(searchQuery, Tag.class)
			.setCriteriaQuery(criteria)
			.setSort(sort);
	persistenceQuery.setFirstResult((int) pageable.getOffset());
	persistenceQuery.setMaxResults(pageable.getPageSize());

	int resultSize = persistenceQuery.getResultSize();

	@SuppressWarnings("unchecked")
	List<Tag> results = persistenceQuery.getResultList();
	return new PageImpl<>(results, pageable, resultSize);
}
 
Example #29
Source File: BookDaoImpl.java    From maven-framework-project with MIT License 4 votes vote down vote up
@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;
}
 
Example #30
Source File: SearchManager.java    From maven-framework-project with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception{
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		EntityManagerFactory entityManagerFactory = applicationContext.getBean("entityManagerFactory",EntityManagerFactory.class);
		FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManagerFactory.createEntityManager());
		
		//使用Hibernate Search api查询 从多个字段匹配 name、description、authors.name
//		QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Book.class ).get();
//		Query luceneQuery = qb.keyword().onFields("name","description","authors.name").matching("移动互联网").createQuery();
		
		//使用lucene api查询 从多个字段匹配 name、description、authors.name
		//使用庖丁分词器
		MultiFieldQueryParser queryParser=new MultiFieldQueryParser(Version.LUCENE_36, new String[]{"name","description","authors.name"}, new PaodingAnalyzer());
		Query luceneQuery=queryParser.parse("实战");
		
		FullTextQuery fullTextQuery =fullTextEntityManager.createFullTextQuery(luceneQuery, Book.class);
		//设置每页显示多少条
		fullTextQuery.setMaxResults(5);
		//设置当前页
		fullTextQuery.setFirstResult(0);
		
		//高亮设置
		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> resultList = fullTextQuery.getResultList();
		
		for (Book book : resultList) {
			String highlighterString=null;
			Analyzer analyzer=new PaodingAnalyzer();
			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) {
			}
			
		}
		
		fullTextEntityManager.close();
		entityManagerFactory.close();
		
	}