Java Code Examples for org.hibernate.search.jpa.FullTextEntityManager#createFullTextQuery()

The following examples show how to use org.hibernate.search.jpa.FullTextEntityManager#createFullTextQuery() . 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: HibernateSearchUtil.java    From javaee-lab with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: HibernateSearchUtil.java    From javaee-lab with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: OwnerDaoImpl.java    From javaee7-petclinic with GNU General Public License v2.0 6 votes vote down vote up
@Override
  public List<Owner> search(String searchterm) {
      FullTextEntityManager fullTextEntityManager =
              org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
      QueryBuilder qb = fullTextEntityManager.getSearchFactory()
              .buildQueryBuilder().forEntity( Owner.class ).get();
      org.apache.lucene.search.Query query = qb
              .keyword()
              .onFields("firstName", "lastName", "city", "pets.name")
              .matching(searchterm)
              .createQuery();
      // wrap Lucene query in a javax.persistence.Query
      javax.persistence.Query persistenceQuery =
              fullTextEntityManager.createFullTextQuery(query, Owner.class);
      // execute search
      @SuppressWarnings("unchecked")
List<Owner> result = persistenceQuery.getResultList();
      return  result;
  }
 
Example 5
Source File: VetDaoImpl.java    From javaee7-petclinic with GNU General Public License v2.0 6 votes vote down vote up
@Override
  public List<Vet> search(String searchterm){
      FullTextEntityManager fullTextEntityManager =
              org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
      QueryBuilder qb = fullTextEntityManager.getSearchFactory()
              .buildQueryBuilder().forEntity( Vet.class ).get();
      org.apache.lucene.search.Query query = qb
              .keyword()
              .onFields("firstName", "lastName")
              .matching(searchterm)
              .createQuery();
      // wrap Lucene query in a javax.persistence.Query
      javax.persistence.Query persistenceQuery =
              fullTextEntityManager.createFullTextQuery(query, Vet.class);
      // execute search
      @SuppressWarnings("unchecked")
List<Vet> result = persistenceQuery.getResultList();
      return  result;
  }
 
Example 6
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 7
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 8
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 9
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 10
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 11
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 12
Source File: SubscriptionSearchServiceBean.java    From development with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Collection<Long> searchSubscriptions(String searchPhrase)
        throws InvalidPhraseException, ObjectNotFoundException {
    ArgumentValidator.notEmptyString("searchPhrase", searchPhrase);

    FullTextEntityManager ftem = getFtem();

    List<Subscription> list;

    BooleanQuery booleanQuery = constructWildcardQuery(searchPhrase);

    javax.persistence.Query jpaQuery = ftem.createFullTextQuery(
            booleanQuery, Subscription.class);

    list = jpaQuery.getResultList();

    List<Long> result = new ArrayList<>();

    for (Subscription sub : list) {
        result.add(new Long(sub.getKey()));
    }

    return result;
}
 
Example 13
Source File: PostSearchServiceImpl.java    From mblog with GNU General Public License v3.0 4 votes vote down vote up
@Override
@PostStatusFilter
public Page<PostVO> search(Pageable pageable, String term) throws Exception {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder builder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Post.class).get();

    Query luceneQuery = builder
            .keyword()
            .fuzzy()
            .withEditDistanceUpTo(1)
            .withPrefixLength(1)
            .onFields("title", "summary", "tags")
            .matching(term).createQuery();

    FullTextQuery query = fullTextEntityManager.createFullTextQuery(luceneQuery, Post.class);
    query.setFirstResult((int) pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
    SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span style='color:red;'>", "</span>");
    QueryScorer scorer = new QueryScorer(luceneQuery);
    Highlighter highlighter = new Highlighter(formatter, scorer);

    List<Post> list = query.getResultList();
    List<PostVO> rets = list.stream().map(po -> {
        PostVO post = BeanMapUtils.copy(po);

        try {
            // 处理高亮
            String title = highlighter.getBestFragment(analyzer, "title", post.getTitle());
            String summary = highlighter.getBestFragment(analyzer, "summary", post.getSummary());

            if (StringUtils.isNotEmpty(title)) {
                post.setTitle(title);
            }
            if (StringUtils.isNotEmpty(summary)) {
                post.setSummary(summary);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return post;
    }).collect(Collectors.toList());
    buildUsers(rets);
    return new PageImpl<>(rets, pageable, query.getResultSize());
}
 
Example 14
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();
		
	}
 
Example 15
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 16
Source File: ProductSearchDao.java    From tutorials with MIT License 2 votes vote down vote up
private FullTextQuery getJpaQuery(org.apache.lucene.search.Query luceneQuery) {

        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

        return fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);
    }