Java Code Examples for org.apache.lucene.queryParser.MultiFieldQueryParser#parse()

The following examples show how to use org.apache.lucene.queryParser.MultiFieldQueryParser#parse() . 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: BaseDao.java    From projectforge-webapp with GNU General Public License v3.0 7 votes vote down vote up
private org.apache.lucene.search.Query createFullTextQuery(final String[] searchFields, final QueryFilter queryFilter,
    final String searchString)
{
  final MultiFieldQueryParser parser = new MultiFieldQueryParser(LUCENE_VERSION, searchFields, new ClassicAnalyzer(Version.LUCENE_31));
  parser.setAllowLeadingWildcard(true);
  org.apache.lucene.search.Query query = null;
  try {
    query = parser.parse(searchString);
  } catch (final org.apache.lucene.queryParser.ParseException ex) {
    final String errorMsg = "Lucene error message: "
        + ex.getMessage()
        + " (for "
        + this.getClass().getSimpleName()
        + ": "
        + searchString
        + ").";
    if (queryFilter != null) {
      queryFilter.setErrorMessage(errorMsg);
    }
    log.info(errorMsg);
    return null;
  }
  return query;
}
 
Example 2
Source File: CourseServiceImpl.java    From TinyMooc with Apache License 2.0 5 votes vote down vote up
public List<Course> getCourses(String query) {
    try {
        List<Course> qlist = new ArrayList<Course>();
        IndexSearcher indexSearcher = new IndexSearcher(INDEXPATH);
        long begin = new Date().getTime();
        //下面的是进行title,content 两个范围内进行收索. SHOULD 表示OR
        BooleanClause.Occur[] clauses = {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD};
        Query queryOBJ = MultiFieldQueryParser.parse(query, new String[]{"courseIntro", "courseTitle"}, clauses, new StandardAnalyzer());//parser.parse(query);
        Filter filter = null;
        //################# 搜索相似度最高的记录 ###################
        TopDocs topDocs = indexSearcher.search(queryOBJ, filter, 1000);
        Course course = null;

        //输出结果
        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
            Document targetDoc = indexSearcher.doc(scoreDoc.doc);
            course = new Course();
            String courseIntro = targetDoc.get("courseIntro");
            String courseTitle = targetDoc.get("courseTitle");
            String courseId = targetDoc.get("courseId");
            TokenStream contentTokenStream = analyzer.tokenStream("courseIntro", new StringReader(courseIntro));
            TokenStream titleTokenStream = analyzer.tokenStream("courseTitle", new StringReader(courseTitle));
            course.setCourseIntro(courseIntro);
            course.setCourseTitle(courseTitle);
            course.setCourseId(courseId);
            course.setType(targetDoc.get("type"));
            course.setCourseState(targetDoc.get("courseState"));
            qlist.add(course);
        }
        indexSearcher.close();
        return qlist;
    } catch (Exception e) {
        logger.error("getCourses error.");
        return null;
    }
}
 
Example 3
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");
		SessionFactory sessionFactory = applicationContext.getBean("hibernate4sessionFactory",SessionFactory.class);
		FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.openSession());
		
		//使用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 =fullTextSession.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.list();
		System.out.println("共查找到["+resultList.size()+"]条记录");
		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) {
			}
			
			System.out.println("书名:"+book.getName()+"\n描述:"+book.getDescription()+"\n出版日期:"+book.getPublicationDate());
			System.out.println("----------------------------------------------------------");
		}
		
		fullTextSession.close();
		sessionFactory.close();
		
	}
 
Example 4
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>();
	
	FullTextSession fullTextSession = Search.getFullTextSession(getSession());
	
	//使用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 = fullTextSession.createFullTextQuery(luceneQuery);
	int searchresultsize = fullTextQuery.getResultSize();
	queryResult.setSearchresultsize(searchresultsize);
	System.out.println("共查找到["+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.list();
	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);
		
		
		System.out.println("书名:"+book.getName()+"\n描述:"+book.getDescription()+"\n出版日期:"+book.getPublicationDate());
		System.out.println("----------------------------------------------------------");
	}
	
	queryResult.setSearchresult(books);
	
	return queryResult;
}
 
Example 5
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 6
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;
}