当前位置: 首页>>代码示例>>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;未经允许,请勿转载。