當前位置: 首頁>>代碼示例>>Java>>正文


Java ParseException類代碼示例

本文整理匯總了Java中org.apache.lucene.queryparser.classic.ParseException的典型用法代碼示例。如果您正苦於以下問題:Java ParseException類的具體用法?Java ParseException怎麽用?Java ParseException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ParseException類屬於org.apache.lucene.queryparser.classic包,在下文中一共展示了ParseException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: search

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
/**
 * Searches the lucene store for a specific query
 *
 * @param <T>       What type of information are we searching
 * @param clazz     The class of the information we are searching
 * @param queryText The query text
 * @return list of entities
 * @throws ParseException the parse exception
 */
public final <T extends BaseEntity> List<Object[]> search(final Class<T> clazz, final String queryText) throws ParseException {
    final FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

    final SearchFactory searchFactory = fullTextEntityManager.getSearchFactory();

    final QueryParser parser = new MultiFieldQueryParser(getClassLuceneFields(clazz), searchFactory.getAnalyzer(clazz));

    final List<Query> parsedQueries = Arrays.stream(queryText.split("AND"))
            .map(e -> parseQuery(e, parser))
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

    final BooleanQuery.Builder bq = new BooleanQuery.Builder();
    parsedQueries.forEach(e -> bq.add(e, BooleanClause.Occur.MUST));

    final FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(bq.build(), clazz);
    jpaQuery.setProjection(ProjectionConstants.SCORE, ProjectionConstants.EXPLANATION, ProjectionConstants.THIS);

    return (List<Object[]>) jpaQuery.getResultList();
}
 
開發者ID:mhaddon,項目名稱:Sound.je,代碼行數:30,代碼來源:EntitySearch.java

示例2: search

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
/**
 * Given a search field to search,the name of the field to return results in
 * and a query string, return search results up to the limit.
 * 
 * @param searchfieldName
 * @param returnFieldName
 * @param queryStr
 * @param limit
 * @return search results (with confidences)
 * @throws ParseException
 * @throws IOException
 */
public HashMap<String[], Float> search(String searchfieldName,
		String[] returnFieldName, String queryStr, int limit)
		throws ParseException, IOException {
	if (queryStr == null || queryStr.length() == 0)
		return new HashMap<String[], Float>();
	final String clean = QueryParser.escape(queryStr);
	final Query q = new QueryParser(Version.LUCENE_40, searchfieldName,
			analyser).parse(clean);
	final TopScoreDocCollector collector = TopScoreDocCollector.create(
			limit, true);

	searcher.search(q, collector);
	final ScoreDoc[] hits = collector.topDocs().scoreDocs;
	final HashMap<String[], Float> results = new HashMap<String[], Float>();
	for (int i = 0; i < hits.length; ++i) {
		final int docId = hits[i].doc;
		final Document d = searcher.doc(docId);
		String[] rvalues = new String[returnFieldName.length];
		for(int j=0;j<rvalues.length;j++){
			rvalues[j]=d.get(returnFieldName[j]);
		}
		results.put(rvalues, hits[i].score);
	}
	return results;
}
 
開發者ID:openimaj,項目名稱:openimaj,代碼行數:38,代碼來源:QuickSearcher.java

示例3: findPosts

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
private List<Post> findPosts() {
	try {
		FullTextSession fullTextSession = getFullTextSession((Session) entityManager.getDelegate());
		Builder builder = new Builder();
		String[] fields = new String[] { "message.text", "topic.subject" };
		MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
		builder.add(parser.parse(POST_TEXT), MUST);
		builder.add(new TermQuery(new Term("topic.forum.id", "0")), MUST);
		builder.add(new TermQuery(new Term("topic.forum.category.id", "0")), MUST);
		builder.add(new WildcardQuery(new Term("poster.userId", "root")), MUST);
		addPostTimeQuery(builder);
		FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), Post.class);
		fullTextQuery.setSort(getSort());
		fullTextQuery.setFirstResult(0);
		fullTextQuery.setMaxResults(15);
		@SuppressWarnings("unchecked")
		List<Post> posts = fullTextQuery.list();
		return posts;
	} catch (ParseException e) {
		logger.severe("error");
		return null;
	}
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Java-EE-Development-with-WildFly,代碼行數:24,代碼來源:SearchTestCase.java

示例4: deleteIndexesByField

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
@Override
public void deleteIndexesByField(String field) {
    if (!isNullOrEmpty(field)) {
        try {
            Query query;
            QueryParser parser = new QueryParser(Version.LUCENE_4_9, field, analyzer);
            parser.setAllowLeadingWildcard(true);
            try {
                query = parser.parse("*");
            } catch (ParseException e) {
                throw new IndexingException(errorMessage(
                        "could not remove full-text index for value " + field, 0));
            }

            synchronized (this) {
                indexWriter.deleteDocuments(query);
                commit();
            }
        } catch (IOException ioe) {
            throw new IndexingException(errorMessage(
                    "could not remove full-text index for value " + field, 0));
        } catch (VirtualMachineError vme) {
            handleVirtualMachineError(vme);
        }
    }
}
 
開發者ID:dizitart,項目名稱:nitrite-database,代碼行數:27,代碼來源:LuceneService.java

示例5: synTokenQuery

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
private void synTokenQuery(String search, final int numbOfResults, final double minLuceneScore,
		Map<String, Float> result, IndexSearcher searcher) throws ParseException, IOException {

	QueryParser parser = new QueryParser(Version.LUCENE_46, "surfaceFormTokens",
			new StandardAnalyzer(Version.LUCENE_46));

	search = QueryParser.escape(search);

	Query q = parser.parse(search);
	/*
	 * Works only in String field!!
	 */
	// Query q = new FuzzyQuery(new Term("surfaceFormTokens",
	// QueryParser.escape(search)), 2);

	TopDocs top = searcher.search(q, numbOfResults);

	for (ScoreDoc doc : top.scoreDocs) {
		if (doc.score >= minLuceneScore) {
			final String key = searcher.doc(doc.doc).get("conceptID");
			if (result.getOrDefault(key, 0f) < doc.score) {
				result.put(key, doc.score);
			}
		}
	}
}
 
開發者ID:ag-sc,項目名稱:JLink,代碼行數:27,代碼來源:LuceneRetrieval.java

示例6: lookupEntries

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
public List<EntityLexicalEntry> lookupEntries(String query, SearchStrategy strategy, String ori_query) throws ParseException, IOException {
  if (strategy == null)
    throw new RuntimeException("No entity search strategy specified");
  switch (strategy) {
    case exact:
      if (exactSearcher == null) exactSearcher = new FbEntitySearcher(opts.exactMatchIndex, opts.numOfDocs, "exact");
      return lookupEntries(exactSearcher, query, ori_query);
    case inexact:
      if (inexactSearcher == null) inexactSearcher = new FbEntitySearcher(opts.inexactMatchIndex, opts.numOfDocs, "inexact");
      return lookupEntries(inexactSearcher, query, ori_query);
    case fbsearch:
      if (freebaseSearch == null) freebaseSearch = new FreebaseSearch();
      if (mid2idCache == null) mid2idCache = StringCacheUtils.create(opts.mid2idPath);
      return lookupFreebaseSearchEntities(query);
    default:
      throw new RuntimeException("Unknown entity search strategy: " + strategy);
  }
}
 
開發者ID:cgraywang,項目名稱:TextHIN,代碼行數:19,代碼來源:EntityLexicon.java

示例7: Search

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
/**
 * 查詢方法
 * @throws IOException 
 * @throws CorruptIndexException 
 * @throws ParseException 
 */
public List Search(String searchString,LuceneResultCollector luceneResultCollector) throws CorruptIndexException, IOException, ParseException{
	//方法一:
	
	System.out.println(this.indexSettings.getAnalyzer().getClass()+"----分詞選擇");
	QueryParser q = new QueryParser(Version.LUCENE_44, "summary", this.indexSettings.getAnalyzer());
	String search = new String(searchString.getBytes("ISO-8859-1"),"UTF-8"); 
	System.out.println(search+"----------搜索的詞語dd");
	Query query = q.parse(search);
	//方法二:
	/*
	Term t = new Term("title", searchString);
	TermQuery query = new TermQuery(t);
	*/
	System.out.println(query.toString()+"--------query.tostring");
	ScoreDoc[] docs = this.indexSearcher.search(query,100).scoreDocs;
	System.out.println("一共有:"+docs.length+"條記錄");
	List result = luceneResultCollector.collect(docs, this.indexSearcher);
	return result;
}
 
開發者ID:zhangjikai,項目名稱:sdudoc,代碼行數:26,代碼來源:LuceneIndexSearch.java

示例8: getQuery

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
@Override
public Query getQuery(Element e) throws ParserException {
  String text = DOMUtils.getText(e);
  try {
    Query q = null;
    if (unSafeParser != null) {
      //synchronize on unsafe parser
      synchronized (unSafeParser) {
        q = unSafeParser.parse(text);
      }
    } else {
      String fieldName = DOMUtils.getAttribute(e, "fieldName", defaultField);
      //Create new parser
      QueryParser parser = createQueryParser(fieldName, analyzer);
      q = parser.parse(text);
    }
    q.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
    return q;
  } catch (ParseException e1) {
    throw new ParserException(e1.getMessage());
  }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:23,代碼來源:UserInputQueryBuilder.java

示例9: parsePhraseElements

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
protected void parsePhraseElements(ComplexPhraseQueryParser qp) throws ParseException {
  // TODO ensure that field-sensitivity is preserved ie the query
  // string below is parsed as
  // field+":("+phrasedQueryStringContents+")"
  // but this will need code in rewrite to unwrap the first layer of
  // boolean query

  String oldDefaultParserField = qp.field;
  try {
    //temporarily set the QueryParser to be parsing the default field for this phrase e.g author:"fred* smith"
    qp.field = this.field;
    contents = qp.parse(phrasedQueryStringContents);
  }
  finally {
    qp.field = oldDefaultParserField;
  }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:18,代碼來源:ComplexPhraseQueryParser.java

示例10: search

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
public ArrayList<String> search(String searchQuery) throws IOException, ParseException {
	ArrayList<String> retList = new ArrayList<String>();
	searcher = new Searcher(indexDir);
	long startTime = System.currentTimeMillis();
	TopDocs hits = searcher.search(searchQuery);
	long endTime = System.currentTimeMillis();
	
	retList.add(hits.totalHits + " documents found. Time :" + (endTime - startTime));
	for (ScoreDoc scoreDoc : hits.scoreDocs) {
		Document doc = searcher.getDocument(scoreDoc);
		retList.add("FILE_PATH: " + doc.get(LuceneConstants.FILE_PATH));
		retList.add("FILE_NAME: " + doc.get(LuceneConstants.FILE_NAME));
	}
	searcher.close();
	return retList;
}
 
開發者ID:tedyli,項目名稱:Tedyli-Searcher,代碼行數:17,代碼來源:searcher.java

示例11: main

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
/**
 * Main entry point. 
 * 
 * @param args the command line arguments.
 * @throws IOException in case of I/O failure.
 * @throws ParseException in case of Query parse exception.
 */
public static void main(String[] args) throws IOException, ParseException {
	// 1. Creates a directory reference. This is where index datafiles will be created.
	Directory directory = FSDirectory.open(new File("/tmp").toPath());
	
	// 2. Creates an IndexWriter
	try (IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig())) {
		
		// 3. Add some data
		indexSomeData(writer);
		
		// 4. Search
		search(directory);			
		
		writer.deleteAll();
	} 
}
 
開發者ID:agazzarini,項目名稱:as-full-text-search-server,代碼行數:24,代碼來源:LuceneBasicFlowExample.java

示例12: search

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
/**
 * Search sample. 
 * 
 * @param directory the index directory.
 * @throws IOException in case of I/O failure.
 * @throws ParseException in case of Query parse exception.
 */	
public static void search(Directory directory) throws IOException, ParseException {
	IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(directory));
	
	Query query = new QueryParser("title", new StandardAnalyzer()).parse("title:Solr");
	TopDocs matches = searcher.search(query, 10);
	
	System.out.println("Search returned " + matches.totalHits + " matches.");
	Arrays.stream(matches.scoreDocs)
		.map(scoreDoc -> luceneDoc(scoreDoc, searcher))
		.forEach(doc -> {
			System.out.println("-------------------------------------");				
			System.out.println("ID:\t" + doc.get("id"));
			System.out.println("TITLE:\t" + doc.get("title"));
			System.out.println("AUTHOR:\t" + doc.get("author"));
			System.out.println("SCORE:\t" + doc.get("score"));
			
		});
}
 
開發者ID:agazzarini,項目名稱:as-full-text-search-server,代碼行數:26,代碼來源:LuceneBasicFlowExample.java

示例13: testSaveLoadVcfCompressedFile

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void testSaveLoadVcfCompressedFile() throws IOException, ClassNotFoundException, InterruptedException,
                                                   ParseException, VcfReadingException {
    VcfFile vcfFile = testSave(CLASSPATH_TEMPLATES_FELIS_CATUS_VCF_COMPRESSED);

    VcfFile file = vcfFileManager.loadVcfFile(vcfFile.getId());
    Assert.assertNotNull(file);

    testLoad(vcfFile, 1D, true);

    /*String featureId = "rs44098047";
    List<FeatureIndexEntry> entries2 = fileManager.searchLuceneIndex(vcfFile, featureId);
    Assert.assertFalse(entries2.isEmpty());
    entries2.forEach(e -> Assert.assertTrue(e.getFeatureId().startsWith(featureId)));*/
}
 
開發者ID:react-dev26,項目名稱:NGB-master,代碼行數:17,代碼來源:VcfManagerTest.java

示例14: testRegisterFile

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void testRegisterFile()
    throws IOException, ClassNotFoundException, InterruptedException, ParseException, NoSuchAlgorithmException,
           VcfReadingException {
    Resource resource = context.getResource(CLASSPATH_TEMPLATES_FELIS_CATUS_VCF);

    FeatureIndexedFileRegistrationRequest request = new FeatureIndexedFileRegistrationRequest();
    request.setReferenceId(referenceId);
    request.setPath(resource.getFile().getAbsolutePath());

    VcfFile vcfFile = vcfManager.registerVcfFile(request);
    Assert.assertNotNull(vcfFile);
    Assert.assertNotNull(vcfFile.getId());

    Track<Variation> trackResult = testLoad(vcfFile, 1D, true);
    Assert.assertFalse(trackResult.getBlocks().isEmpty());

    List<VcfFile> filesByReference = vcfFileManager.loadVcfFilesByReferenceId(referenceId);
    Assert.assertNotNull(filesByReference);
    Assert.assertFalse(filesByReference.isEmpty());
}
 
開發者ID:react-dev26,項目名稱:NGB-master,代碼行數:23,代碼來源:VcfManagerTest.java

示例15: parse

import org.apache.lucene.queryparser.classic.ParseException; //導入依賴的package包/類
@Override
public Query parse(QualityQuery qq) throws ParseException {

    //System.out.println("\n--------\n"+qq.getQueryID());

    if(useAugmentedVersion) {
        try {
            return getAugmentedTermQuery(qq);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }else{
        return getTermQuery(qq);
    }
}
 
開發者ID:sebastian-hofstaetter,項目名稱:ir-generalized-translation-models,代碼行數:17,代碼來源:SimilarityApiParser.java


注:本文中的org.apache.lucene.queryparser.classic.ParseException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。