Java Code Examples for org.hibernate.search.jpa.FullTextQuery#setFirstResult()

The following examples show how to use org.hibernate.search.jpa.FullTextQuery#setFirstResult() . 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: ProjectDaoImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: UserDaoImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: ArtifactDaoImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: ArtifactDaoImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
@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 5
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 6
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 7
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 8
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 9
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 10
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 11
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;
}