Java Code Examples for org.apache.lucene.queryParser.ParseException

The following are top voted examples for showing how to use org.apache.lucene.queryParser.ParseException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: joai-project   File: FieldExpansionQueryParser.java   Source Code and License 6 votes vote down vote up
/**
 *  Gets the fieldQuery attribute of the FieldExpansionQueryParser object
 *
 * @param  field               The field being processed
 * @param  queryText           The text in the field
 * @return                     The fieldQuery value
 * @exception  ParseException  If error
 */
protected Query getFieldQuery(String field, String queryText)
	 throws ParseException {

	// prtln("getFieldQuery( field: '" + field + "', queryText: '" + queryText + "'");

	// If a VirtualSearchFieldMapper is available and has a mapping for this field, use it:
	if (virtualSearchFieldMapper != null) {
		Query q = virtualSearchFieldMapper.getQuery(field, queryText);
		if (q != null)
			return q;
	}

	// Extract and store the terms in the default field once only - used for boosting
	if (field.equals(expansionFields[0])) {
		String[] tmp = queryText.split("\\s+");
		for (int i = 0; i < tmp.length; i++)
			terms.add(tmp[i]);
	}

	// Then perform the normal field query
	return super.getFieldQuery(field, queryText);
}
 
Example 2
Project: Equella   File: ItemIndex.java   Source Code and License 6 votes vote down vote up
public Operator getDefaultOperator() throws ParseException
{
	Operator o;

	if( this.defaultOperator.equalsIgnoreCase("and") )
	{
		o = Operator.AND;
	}
	else if( this.defaultOperator.equalsIgnoreCase("OR") )
	{
		o = Operator.OR;
	}
	else
	{
		throw new ParseException("Invalid Default Operator (AND/OR)");
	}

	return o;
}
 
Example 3
Project: bibliome-java-utils   File: PubMedIndexSearcher.java   Source Code and License 6 votes vote down vote up
@Override
protected boolean processArgument(String arg) throws CLIOException {
	try {
		Analyzer analyzer = PubMedIndexUtils.getGlobalAnalyzer();
		QueryParser parser = new QueryParser(PubMedIndexUtils.LUCENE_VERSION, PubMedIndexField.ABSTRACT.fieldName, analyzer);
		parser.setDefaultOperator(QueryParser.AND_OPERATOR);
		parser.setLowercaseExpandedTerms(false);
		PubMedIndexUtils.log("parsing query: %s", arg);
		Query q = parser.parse(arg);
		PubMedIndexUtils.log("query: %s", q);
		addClause(q);
		return false;
	}
	catch (ParseException e) {
		throw new CLIOException(e);
	}
}
 
Example 4
Project: clearwsd   File: LuceneWrapper.java   Source Code and License 6 votes vote down vote up
public Map<String, Integer> search(String word, String field, int maxSearch) {
    if (indexSearcher == null) {
        initialize(index);
    }
    Map<String, Integer> verbFreqs = new HashMap<>();
    QueryParser queryParser = new QueryParser(Version.LUCENE_36, field, analyzer);
    try {
        Query query = queryParser.parse(word);
        TopDocs topDocs = indexSearcher.search(query, maxSearch);
        ScoreDoc[] doc = topDocs.scoreDocs;
        for (int i = 0; i < maxSearch && i < doc.length; ++i) {
            int documentId = doc[i].doc;
            Document document = indexSearcher.doc(documentId);
            String verb = document.get(VERB);
            String frequency = document.get(FREQ);
            verbFreqs.put(verb, Integer.parseInt(frequency));
        }
    } catch (ParseException | IOException e) {
        log.warn("Error searching Lucene index.", e);
    }
    return verbFreqs;
}
 
Example 5
Project: bisis-v4   File: Retriever.java   Source Code and License 6 votes vote down vote up
/**
  * Executes a select query.
  * @param query The Lucene query
  * @return An array of record IDs; an empty array if an error occured
* @throws IOException 
  */
 public int[] select(String query, String sortPrefix)  throws ParseException{
   try {
     WhitespaceAnalyzer sa= new WhitespaceAnalyzer();
     BooleanQuery.setMaxClauseCount(20000);//zbog heap-a
     QueryParser p = new QueryParser("KW", sa);
     p.setDefaultOperator(QueryParser.Operator.AND); //default operator je AND a ne OR kao sto je inace inicijalno
     Query q = p.parse(query);
     return select(q, sortPrefix);
   } catch (Exception ex) {
   	if (ex instanceof ParseException )
   		throw (ParseException)ex;
     log.warn(ex);
     return new int[0];
   }
 }
 
Example 6
Project: document-management-system   File: SearchDemo.java   Source Code and License 6 votes vote down vote up
/**
 * Search in documents
 */
private static void search(Directory index, Analyzer analyzer, String str) throws ParseException, CorruptIndexException,
		IOException {
	IndexReader reader = IndexReader.open(index);
	IndexSearcher searcher = new IndexSearcher(reader);
	TopScoreDocCollector collector = TopScoreDocCollector.create(NUM_HITS, true);
	//Query q = new QueryParser(Config.LUCENE_VERSION, DOC_FIELD, analyzer).parse(str);
	Query q = new WildcardQuery(new Term(DOC_FIELD, str));
	System.out.println("Query: " + q);

	searcher.search(q, collector);
	ScoreDoc[] hits = collector.topDocs().scoreDocs;

	System.out.println("Found " + hits.length + " hits.");

	for (int i = 0; i < hits.length; ++i) {
		int docId = hits[i].doc;
		Document d = searcher.doc(docId);
		System.out.println((i + 1) + ". " + d.get(DOC_FIELD));
	}

	searcher.close();
}
 
Example 7
Project: THUTag   File: KnnTagSuggest.java   Source Code and License 6 votes vote down vote up
public Query makeQueryFromKeywords(List<WeightString> keywords, int n)
throws ParseException {
  StringBuilder queryString = new StringBuilder();
  for (int i = 0; i < n && i < keywords.size(); i++) {
    if (i > 0)
      queryString.append(' ');
    queryString.append(keywords.get(i).text);
    queryString.append('^');
    queryString.append(String.format("%.2f",
        Math.log(keywords.get(i).weight + 1)));
  }
  if (queryString.length() == 0)
    queryString.append("a");
  Query q = queryParser.parse(queryString.toString());
  return q;
}
 
Example 8
Project: THUTag   File: ExpandRankKE.java   Source Code and License 6 votes vote down vote up
public Query makeQueryFromKeywords(List<WeightString> keywords, int n)
		throws ParseException {
	StringBuilder queryString = new StringBuilder();
	for (int i = 0; i < n && i < keywords.size(); i++) {
		if (i > 0)
			queryString.append(' ');
		queryString.append(keywords.get(i).text);
		queryString.append('^');
		queryString.append(String.format("%.2f", Math
				.log(keywords.get(i).weight + 1)));
	}
	if (queryString.length() == 0)
		queryString.append("a");
	Query q = queryParser.parse(queryString.toString());
	return q;
}
 
Example 9
Project: rrs   File: Searcher.java   Source Code and License 6 votes vote down vote up
public static void search(String indexDir, String q)
	throws IOException, ParseException {
	
	Directory dir = FSDirectory.open(new File(indexDir));
	IndexSearcher is = new IndexSearcher(dir);
	
	QueryParser parser = new QueryParser(Version.LUCENE_30, "contents", 
			new StandardAnalyzer(Version.LUCENE_30));
	Query query = parser.parse(q);
	
	long start = System.currentTimeMillis();
	TopDocs hits = is.search(query, 10);
	long end = System.currentTimeMillis();
	
	System.out.println(" document(s) (in " + (end - start) + " milliseconds) that matched query '" +
				q + "':" + ("Found " + hits.totalHits));
	
	for(ScoreDoc scoreDoc : hits.scoreDocs) {
		Document doc = is.doc(scoreDoc.doc);
		System.out.println(doc.get("fullpath"));
	}
	
	is.close();
}
 
Example 10
Project: dls-repository-stack   File: FieldExpansionQueryParser.java   Source Code and License 6 votes vote down vote up
/**
 *  Gets the fieldQuery attribute of the FieldExpansionQueryParser object
 *
 * @param  field               The field being processed
 * @param  queryText           The text in the field
 * @return                     The fieldQuery value
 * @exception  ParseException  If error
 */
protected Query getFieldQuery(String field, String queryText)
	 throws ParseException {

	// prtln("getFieldQuery( field: '" + field + "', queryText: '" + queryText + "'");

	// If a VirtualSearchFieldMapper is available and has a mapping for this field, use it:
	if (virtualSearchFieldMapper != null) {
		Query q = virtualSearchFieldMapper.getQuery(field, queryText);
		if (q != null)
			return q;
	}

	// Extract and store the terms in the default field once only - used for boosting
	if (field.equals(expansionFields[0])) {
		String[] tmp = queryText.split("\\s+");
		for (int i = 0; i < tmp.length; i++)
			terms.add(tmp[i]);
	}

	// Then perform the normal field query
	return super.getFieldQuery(field, queryText);
}
 
Example 11
Project: ephesoft   File: QueryParser.java   Source Code and License 6 votes vote down vote up
private Token jj_consume_token(int kind) throws ParseException {
	Token oldToken;
	if ((oldToken = token).next != null)
		token = token.next;
	else
		token = token.next = token_source.getNextToken();
	jj_ntk = -1;
	if (token.kind == kind) {
		jj_gen++;
		if (++jj_gc > 100) {
			jj_gc = 0;
			for (int i = 0; i < jj_2_rtns.length; i++) {
				JJCalls c = jj_2_rtns[i];
				while (c != null) {
					if (c.gen < jj_gen)
						c.first = null;
					c = c.next;
				}
			}
		}
		return token;
	}
	token = oldToken;
	jj_kind = kind;
	throw generateParseException();
}
 
Example 12
Project: SPADE   File: Graph.java   Source Code and License 6 votes vote down vote up
public List<Integer> listVertices(String expression) {
    try {
        List<Integer> results = new ArrayList<>();
        IndexReader reader = IndexReader.open(vertexIndex);
        IndexSearcher searcher = new IndexSearcher(reader);
        ScoreDoc[] hits = searcher.search(queryParser.parse(expression), MAX_QUERY_HITS).scoreDocs;

        for (int i = 0; i < hits.length; ++i) {
            int docId = hits[i].doc;
            Document foundDoc = searcher.doc(docId);
            results.add(Integer.parseInt(foundDoc.get(ID_STRING)));
        }

        searcher.close();
        reader.close();
        return results;
    } catch (IOException | ParseException | NumberFormatException exception) {
        logger.log(Level.WARNING, "Error while listing vertices. Returning empty array.", exception);
        return new ArrayList<>();
    }
}
 
Example 13
Project: jeecms6   File: LuceneContentSvcImpl.java   Source Code and License 6 votes vote down vote up
@Transactional(readOnly = true)
public Integer createIndex(Integer siteId, Integer channelId,
		Date startDate, Date endDate, Integer startId, Integer max,
		Directory dir) throws IOException, ParseException {
	boolean exist = IndexReader.indexExists(dir);
	IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(
			Version.LUCENE_30), !exist, IndexWriter.MaxFieldLength.LIMITED);
	try {
		if (exist) {
			LuceneContent.delete(siteId, channelId, startDate, endDate,
					writer);
		}
		Integer lastId = luceneContentDao.index(writer, siteId, channelId,
				startDate, endDate, startId, max);
		writer.optimize();
		return lastId;
	} finally {
		writer.close();
	}
}
 
Example 14
Project: jeecms6   File: LuceneContentSvcImpl.java   Source Code and License 6 votes vote down vote up
@Transactional(readOnly = true)
public Pagination searchPage(Directory dir, String queryString,String category,String workplace,
		Integer siteId, Integer channelId, Date startDate, Date endDate,
		int pageNo, int pageSize) throws CorruptIndexException,
		IOException, ParseException {
	Searcher searcher = new IndexSearcher(dir);
	try {
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
		Query query = LuceneContent.createQuery(queryString,category,workplace, siteId,
				channelId, startDate, endDate, analyzer);
		TopDocs docs = searcher.search(query, pageNo * pageSize);
		Pagination p = LuceneContent.getResultPage(searcher, docs, pageNo,
				pageSize);
		List<?> ids = p.getList();
		List<Content> contents = new ArrayList<Content>(ids.size());
		for (Object id : ids) {
			contents.add(contentMng.findById((Integer) id));
		}
		p.setList(contents);
		return p;
	} finally {
		searcher.close();
	}
}
 
Example 15
Project: webdsl   File: FieldConstraintFilter.java   Source Code and License 6 votes vote down vote up
@org.hibernate.search.annotations.Factory
public Filter buildFilter(){
	QueryParser qp = new QueryParser(Version.LUCENE_CURRENT,field, analyzer);
	Query q;
	try {
		if(allowLuceneSyntax)
			q = qp.parse(value);
		else
			q = qp.parse(QueryParser.escape(value));
	} catch (ParseException e) {
		org.webdsl.logging.Logger.error("Error while parsing query in field filter: ");
		org.webdsl.logging.Logger.error("EXCEPTION",e);
		q = new TermQuery(new Term(field, value));
	}
	Filter filter = new QueryWrapperFilter(q);
	filter = new CachingWrapperFilter( filter );
	return filter;
}
 
Example 16
Project: irplus   File: DefaultInstitutionalItemSearchService.java   Source Code and License 6 votes vote down vote up
/**
 * Set up the filters for collections - this is for searching within collections.
 * 
 * @param collection - to search within
 * @return - created filter
 * @throws ParseException
 */
private List<Filter> getCollectionFilters(InstitutionalCollection collection) throws ParseException
{
	List<Filter> filters = new LinkedList<Filter>();
	
       //isolate the collection root
	Term t = new Term("collection_root_id", NumericUtils.longToPrefixCoded(collection.getTreeRoot().getId()));
	Query subQuery = new TermQuery( t );
	filters.add(new QueryWrapperFilter(subQuery));
	
	
	//isolate the range of children
	subQuery = NumericRangeQuery.newLongRange("collection_left_value", collection.getLeftValue(), collection.getRightValue(), true, true);
	filters.add(new QueryWrapperFilter(subQuery));
    return filters;
}
 
Example 17
Project: irplus   File: DefaultResearcherSearchService.java   Source Code and License 6 votes vote down vote up
/**
 * Execute the sub query facets and return the search results
 * @throws ParseException 
 * @throws IOException 
 */
private List<Filter> getSubQueryFilters( List<FacetFilter> filters, 
		IndexSearcher searcher) throws ParseException, IOException
{
	List<Filter> luceneFilters = new LinkedList<Filter>();
	
	for(FacetFilter filter : filters)
	{	
		if(log.isDebugEnabled())
		{
			log.debug("adding filter for field " + filter.getField() + " and query " + filter.getQuery());
		}
	    QueryParser subQueryParser = new QueryParser(Version.LUCENE_35, filter.getField(), analyzer);
	    subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
	    String fixedQuery = SearchHelper.prepareFacetSearchString(filter.getQuery(), false);
	    fixedQuery = "\"" + fixedQuery + "\"";
	    Query subQuery = subQueryParser.parse(fixedQuery);
	    if(log.isDebugEnabled())
		{
			log.debug("sub query ing getSubQueryFilters is " + fixedQuery);
		}
	    luceneFilters.add(new QueryWrapperFilter(subQuery));
	}
	
	return luceneFilters;
}
 
Example 18
Project: irplus   File: DefaultInstitutionalItemIndexServiceTest.java   Source Code and License 6 votes vote down vote up
/**
 * Executes the query returning the number of hits.
 * 
 * @param field - field to search on
 * @param queryString - query string
 * @param dir - lucene index to search
 * 
 * @return - number of hits
 * 
 * @throws CorruptIndexException
 * @throws IOException
 * @throws ParseException
 */
private int executeQuery(String field, String queryString, Directory dir)
		throws CorruptIndexException, IOException, ParseException {
	
	IndexReader reader = IndexReader.open(dir, true);
	IndexSearcher searcher = new IndexSearcher(reader);
	QueryParser parser = new QueryParser(Version.LUCENE_35, field, new StandardAnalyzer(Version.LUCENE_35));
	Query q1 = parser.parse(queryString);
	TopDocs hits = searcher.search(q1, 1000);
	int hitCount = hits.totalHits;

	searcher.close();
	reader.close();

	return hitCount;
}
 
Example 19
Project: irplus   File: DefaultExcelTextExtractorTest.java   Source Code and License 6 votes vote down vote up
/**
 * Executes the query returning the number of hits.
 * 
 * @param field - field to search on
 * @param queryString - query string
 * @param dir - lucene index to search
 * 
 * @return - number of hits
 * 
 * @throws CorruptIndexException
 * @throws IOException
 * @throws ParseException
 */
private int executeQuery(String field, String queryString, Directory dir)
		throws CorruptIndexException, IOException, ParseException {
	
	
	IndexReader reader = IndexReader.open(dir, true);
	IndexSearcher searcher = new IndexSearcher(reader);
	QueryParser parser = new QueryParser(Version.LUCENE_35, field, new StandardWithACIIFoldingFilter());
	Query q1 = parser.parse(queryString);

	TopDocs hits = searcher.search(q1, 1000);
	int hitCount = hits.totalHits;

	searcher.close();

	return hitCount;
}
 
Example 20
Project: irplus   File: DefaultPlainTextTextExtractorTest.java   Source Code and License 6 votes vote down vote up
private int executeQuery(String field, String queryString, Directory dir) throws 
CorruptIndexException, IOException, ParseException
{
	
	IndexReader reader = IndexReader.open(dir, true);
	IndexSearcher searcher = new IndexSearcher(reader);
	QueryParser parser = new QueryParser(Version.LUCENE_35, field, new StandardWithACIIFoldingFilter() );
	Query q1 = parser.parse(queryString);
	TopDocs hits= searcher.search(q1, 1000);
	int hitCount = hits.totalHits;
	
	
	searcher.close();
	
	return  hitCount;
}
 
Example 21
Project: irplus   File: DefaultPowerPointXmlTextExtractorTest.java   Source Code and License 6 votes vote down vote up
/**
 * Executes the query returning the number of hits.
 * 
 * @param field - field to search on
 * @param queryString - query string
 * @param dir - lucene index to search
 * 
 * @return - number of hits
 * 
 * @throws CorruptIndexException
 * @throws IOException
 * @throws ParseException
 */
private int executeQuery(String field, String queryString, Directory dir)
		throws CorruptIndexException, IOException, ParseException {
	
	
	IndexReader reader = IndexReader.open(dir, true);
	IndexSearcher searcher = new IndexSearcher(reader);
	QueryParser parser = new QueryParser(Version.LUCENE_35, field, new StandardWithACIIFoldingFilter());
	Query q1 = parser.parse(queryString);

	TopDocs hits = searcher.search(q1, 1000);
	int hitCount = hits.totalHits;

	searcher.close();

	return hitCount;
}
 
Example 22
Project: irplus   File: DefaultPowerPointTextExtractorTest.java   Source Code and License 6 votes vote down vote up
/**
 * Executes the query returning the number of hits.
 * 
 * @param field - field to search on
 * @param queryString - query string
 * @param dir - lucene index to search
 * 
 * @return - number of hits
 * 
 * @throws CorruptIndexException
 * @throws IOException
 * @throws ParseException
 */
private int executeQuery(String field, String queryString, Directory dir)
		throws CorruptIndexException, IOException, ParseException {
	
	IndexReader reader = IndexReader.open(dir, true);
	IndexSearcher searcher = new IndexSearcher(reader);
	QueryParser parser = new QueryParser(Version.LUCENE_35, field, new StandardWithACIIFoldingFilter());
	Query q1 = parser.parse(queryString);

	TopDocs hits = searcher.search(q1, 1000);
	int hitCount = hits.totalHits;

	searcher.close();

	return hitCount;
}
 
Example 23
Project: JForum   File: SearchRepository.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public SearchResult search(SearchParams params) throws ParseException {
	String buildQuery = params.buildQuery();
	FullTextQuery query = this.createQuery(buildQuery);

	query.setFirstResult(params.getStart());
	query.setMaxResults(params.getMaxResults());
	query.setFetchSize(params.getMaxResults());

	if (params.getSort() == SearchSort.DATE) {
		query.setSort(new Sort(new SortField("date", params.getSortType() == SearchSortType.DESC)));
	}
	else if (params.getSort() == SearchSort.RELEVANCE) {
		query.setSort(Sort.RELEVANCE);
	}

	return new SearchResult(query.list(), query.getResultSize());
}
 
Example 24
Project: xodus   File: ExodusLuceneWithPatriciaTests.java   Source Code and License 6 votes vote down vote up
@Test
public void addSearchPhrase() throws IOException, ParseException {
    addSearchMatch();
    TopDocs docs = indexSearcher.search(getQuery(DESCRIPTION, "\"Long-term Cooperation Agreement\""), Integer.MAX_VALUE);
    Assert.assertEquals(1, docs.totalHits);
    docs = indexSearcher.search(getQuery(DESCRIPTION, "\"could now start selling\""), Integer.MAX_VALUE);
    Assert.assertEquals(1, docs.totalHits);
    docs = indexSearcher.search(getQuery(DESCRIPTION, "\"On 10 October 2003\""), Integer.MAX_VALUE);
    Assert.assertEquals(1, docs.totalHits);
    docs = indexSearcher.search(getQuery(DESCRIPTION, "\"[8]\""), Integer.MAX_VALUE);
    Assert.assertEquals(1, docs.totalHits);
    docs = indexSearcher.search(getQuery(DESCRIPTION, "\"on the plane\""), Integer.MAX_VALUE);
    Assert.assertEquals(1, docs.totalHits);
    docs = indexSearcher.search(getQuery(DESCRIPTION, "\"development of the\""), Integer.MAX_VALUE);
    Assert.assertEquals(1, docs.totalHits);
}
 
Example 25
Project: community-edition-old   File: AlfrescoSolrDataModel.java   Source Code and License 6 votes vote down vote up
/**
 * @param field
 * @param part1
 * @param part2
 * @param minInclusive
 * @param maxInclusive
 * @return
 */
public Query getRangeQuery(SchemaField field, String part1, String part2, boolean minInclusive, boolean maxInclusive)
{
    SolrLuceneAnalyser defaultAnalyser = new SolrLuceneAnalyser(getDictionaryService(CMISStrictDictionaryService.DEFAULT), getMLAnalysisMode(), alfrescoDataType.getDefaultAnalyzer(), this);
    SolrQueryParser parser = new SolrQueryParser("TEXT", defaultAnalyser);
    parser.setDefaultOperator(Operator.AND);
    parser.setNamespacePrefixResolver(namespaceDAO);
    parser.setDictionaryService(getDictionaryService(CMISStrictDictionaryService.DEFAULT));
    parser.setTenantService(tenantService);
    parser.setSearchParameters(null);
    parser.setDefaultSearchMLAnalysisMode(getMLAnalysisMode());
    parser.setIndexReader(null);
    parser.setAllowLeadingWildcard(true);

    try
    {
        return parser.getRangeQuery(field.getName(), part1, part2, minInclusive, maxInclusive, AnalysisMode.DEFAULT, LuceneFunction.FIELD);
    }
    catch (ParseException e)
    {
        throw new AlfrescoRuntimeException("Parse error building range query", e);
    }
}
 
Example 26
Project: community-edition-old   File: AlfrescoSolrDataModel.java   Source Code and License 6 votes vote down vote up
public Query getCMISQuery(CMISQueryMode mode, Pair<SearchParameters, Boolean> searchParametersAndFilter, IndexReader indexReader, org.alfresco.repo.search.impl.querymodel.Query queryModelQuery, CmisVersion cmisVersion, String alternativeDictionary)
        throws ParseException
{
    SearchParameters searchParameters = searchParametersAndFilter.getFirst();
    Boolean isFilter = searchParametersAndFilter.getSecond();
    
    BaseTypeId[] validScopes = (mode == CMISQueryMode.CMS_STRICT) ? CmisFunctionEvaluationContext.STRICT_SCOPES : CmisFunctionEvaluationContext.ALFRESCO_SCOPES;
    CmisFunctionEvaluationContext functionContext = getCMISFunctionEvaluationContext(mode, cmisVersion, alternativeDictionary);

    Set<String> selectorGroup = queryModelQuery.getSource().getSelectorGroups(functionContext).get(0);

    LuceneQueryBuilderContext<Query, Sort, ParseException> luceneContext = getLuceneQueryBuilderContext(searchParameters, indexReader, alternativeDictionary);
    @SuppressWarnings("unchecked")
    LuceneQueryBuilder<Query, Sort, ParseException> builder = (LuceneQueryBuilder<Query, Sort, ParseException>) queryModelQuery;
    org.apache.lucene.search.Query luceneQuery = builder.buildQuery(selectorGroup, luceneContext, functionContext);

    ContextAwareQuery contextAwareQuery = new ContextAwareQuery(luceneQuery, Boolean.TRUE.equals(isFilter) ? null : searchParameters);
    return contextAwareQuery;
}
 
Example 27
Project: spacewalk   File: NGramQueryParser.java   Source Code and License 6 votes vote down vote up
protected Query getFieldQuery(String defaultField,
        String queryText) throws ParseException {
    Query orig = super.getFieldQuery(defaultField, queryText);
    if (!(orig instanceof PhraseQuery)) {
        log.debug("Returning default query.  No phrase query translation.");
        return orig;
    }
    /**
     * A ngram when parsed will become a series of smaller search terms,
     * these terms are grouped together into a PhraseQuery.  We are taking
     * that PhraseQuery and breaking out each ngram term then combining all
     * ngrams together to form a BooleanQuery.
     */
    PhraseQuery pq = (PhraseQuery)orig;
    return new NGramQuery(pq, useMust);
}
 
Example 28
Project: community-edition-old   File: SolrQueryParser.java   Source Code and License 6 votes vote down vote up
private void addLocaleSpecificTextRange(String expandedFieldName, String part1, String part2, boolean includeLower, boolean includeUpper, BooleanQuery booleanQuery,
        Locale locale, AnalysisMode analysisMode, IndexTokenisationMode tokenisationMode, IndexTokenisationMode preferredtokenisationMode) throws ParseException
{
    String field = getFieldName(expandedFieldName, locale, tokenisationMode, preferredtokenisationMode);
    StringBuilder builder = new StringBuilder();
    builder.append("\u0000").append(locale.toString()).append("\u0000").append(part1);
    String first = getToken(field, builder.toString(), analysisMode);
    if ((first == null) && (false == field.endsWith(".u")))
    {
        first = getToken(field + ".u", builder.toString(), analysisMode);
    }

    builder = new StringBuilder();
    builder.append("\u0000").append(locale.toString()).append("\u0000").append(part2);
    String last = getToken(field, builder.toString(), analysisMode);
    if ((last == null) && (false == field.endsWith(".u")))
    {
        last = getToken(field + ".u", builder.toString(), analysisMode);
    }

    Query query = new TermRangeQuery(field, first, last, includeLower, includeUpper);
    booleanQuery.add(query, Occur.SHOULD);
}
 
Example 29
Project: community-edition-old   File: AbstractLuceneQueryParser.java   Source Code and License 6 votes vote down vote up
/**
 * @param field String
 * @param queryText String
 * @param analysisMode AnalysisMode
 * @param luceneFunction LuceneFunction
 * @return the query
 * @throws ParseException
 */
public Query getDoesNotMatchFieldQuery(String field, String queryText, AnalysisMode analysisMode, LuceneFunction luceneFunction) throws ParseException
{
    BooleanQuery query = new BooleanQuery();
    Query allQuery = new MatchAllDocsQuery();
    Query matchQuery = getFieldQuery(field, queryText, analysisMode, luceneFunction);
    if ((matchQuery != null))
    {
        query.add(allQuery, Occur.MUST);
        query.add(matchQuery, Occur.MUST_NOT);
    }
    else
    {
        throw new UnsupportedOperationException();
    }
    return query;
}
 
Example 30
Project: reviki   File: LuceneSearcher.java   Source Code and License 6 votes vote down vote up
public Set<SearchMatch> search(final String queryString, final boolean provideExtracts, final boolean singleWiki) throws IOException, QuerySyntaxException {
  if (_dir == null || queryString == null || queryString.trim().length() == 0) {
    return Collections.emptySet();
  }
  return doReadOperation(new ReadOperation<Set<SearchMatch>>() {
    public Set<SearchMatch> execute(final IndexReader reader, final Searcher searcher, final Analyzer analyzer) throws IOException, ParseException {
      LinkedHashSet<SearchMatch> results = new LinkedHashSet<SearchMatch>();
      // Prefer path, then title then content matches (match equality is on page name)
      for (String field : ALL_SEARCH_FIELDS) {
        if (field.equals(FIELD_PATH_LOWER)) {
          final Query query = new WildcardQuery(new Term(FIELD_PATH_LOWER, "*" + queryString.toLowerCase() + "*"));
          results.addAll(doQuery(reader, analyzer, searcher, field, provideExtracts, query));
        }
        else {
          results.addAll(query(reader, analyzer, searcher, field, queryString, provideExtracts));
        }
      }
      return orderResults(results);
    }
  }, !singleWiki);
}
 
Example 31
Project: community-edition-old   File: LegacyLuceneQueryParserAdaptor.java   Source Code and License 6 votes vote down vote up
@Override
public Query getQuery()  throws ParseException
{
    if(booleanQuery.getClauses().length == 0)
    {
        return getMatchNoneQuery();
    }
    else if (booleanQuery.getClauses().length == 1)
    {
        BooleanClause clause = booleanQuery.getClauses()[0];
        if(clause.isProhibited())
        {
            booleanQuery.add(getMatchAllQuery(), Occur.MUST);
            return booleanQuery;
        }
        else
        {
            return clause.getQuery();
        }
    }
    else
    {
        return booleanQuery;
    }
}
 
Example 32
Project: community-edition-old   File: AbstractLuceneQueryParser.java   Source Code and License 6 votes vote down vote up
protected Query createDataTypeDefinitionQuery(String field, String queryText, AnalysisMode analysisMode, LuceneFunction luceneFunction) throws ParseException
{
    Collection<QName> contentAttributes = dictionaryService.getAllProperties(matchDataTypeDefinition(field).getName());
    BooleanQuery query = new BooleanQuery();
    for (QName qname : contentAttributes)
    {
        // The super implementation will create phrase queries etc if required
        Query part = getFieldQuery(PROPERTY_FIELD_PREFIX + qname.toString(), queryText, analysisMode, luceneFunction);
        if (part != null)
        {
            query.add(part, Occur.SHOULD);
        }
        else
        {
            query.add(createNoMatchQuery(), Occur.SHOULD);
        }
    }
    return query;
}
 
Example 33
Project: community-edition-old   File: AbstractLuceneQueryParser.java   Source Code and License 6 votes vote down vote up
protected Query createIsNullQuery(String queryText, AnalysisMode analysisMode, LuceneFunction luceneFunction) throws ParseException
{
    PropertyDefinition pd = matchPropertyDefinition(queryText);
    if (pd != null)
    {
        BooleanQuery query = new BooleanQuery();
        Query presenceQuery = getWildcardQuery(PROPERTY_FIELD_PREFIX + pd.getName().toString(), "*");
        if (presenceQuery != null)
        {
            query.add(new MatchAllDocsQuery(), Occur.MUST);
            query.add(presenceQuery, Occur.MUST_NOT);
        }
        return query;
    }
    else
    {
        return getFieldQueryImpl(FIELD_ISNULL, queryText, analysisMode, luceneFunction);
    }
}
 
Example 34
Project: reviki   File: LuceneSearcher.java   Source Code and License 6 votes vote down vote up
public Set<String> incomingLinks(final String page) throws IOException, PageStoreException {
  if (_dir == null) {
    return Collections.emptySet();
  }
  try {
    return doReadOperation(new ReadOperation<Set<String>>() {
      public Set<String> execute(final IndexReader reader, final Searcher searcher, final Analyzer analyzer) throws IOException, ParseException {
        final String pageEscaped = escape(URIUtil.encodeWithinPath(page));
        Set<String> results = Sets.newLinkedHashSet(Iterables.transform(query(reader, createAnalyzer(), searcher, FIELD_OUTGOING_LINKS, pageEscaped, false), SearchMatch.TO_PAGE_NAME));
        results.remove(page);
        return results;
      }
    }, false);
  }
  catch (QuerySyntaxException ex) {
    throw new NoQueryPerformedException(ex);
  }
}
 
Example 35
Project: xodus   File: ExodusLuceneWithPatriciaTests.java   Source Code and License 6 votes vote down vote up
@Test
public void addSearchPhraseTestQuery() throws IOException, ParseException {
    addSearchMatch();
    Query query = getQuery(DESCRIPTION, "\"could now start selling\"");
    Assert.assertTrue(query instanceof PhraseQuery);
    TopDocs docs = indexSearcher.search(query, Integer.MAX_VALUE);
    Assert.assertEquals(1, docs.totalHits);
    query = getQuery(DESCRIPTION, "\"the fourth stage\"");
    Assert.assertTrue(query instanceof PhraseQuery);
    docs = indexSearcher.search(query, Integer.MAX_VALUE);
    Assert.assertEquals(1, docs.totalHits);
    removeStopWord("on");
    query = getQuery(DESCRIPTION, "\"on the plane\"");
    Assert.assertTrue(query instanceof PhraseQuery);
    docs = indexSearcher.search(query, Integer.MAX_VALUE);
    Assert.assertEquals(0, docs.totalHits);
    removeStopWord("as");
    query = getQuery(DESCRIPTION, "\"as a player\"");
    Assert.assertTrue(query instanceof PhraseQuery);
    docs = indexSearcher.search(query, Integer.MAX_VALUE);
    Assert.assertEquals(0, docs.totalHits);
}
 
Example 36
Project: GeoprocessingAppstore   File: QueryProvider.java   Source Code and License 6 votes vote down vote up
/**
 * Makes a timeperiod query.
 * @param meaning the property meaning
 * @param the lower bound for the range
 * @param the upper bound for the range
 * @param inclusive true if the range is inclusive
 * @return the query
 * @throws ParseException 
 * @throws DiscoveryException 
 */
private Query makeTimeperiodQuery(PropertyMeaning meaning, 
    String lower, String upper, boolean inclusive) 
    throws DiscoveryException, ParseException {
  
  // make the clause
  Discoverable target = new Discoverable(meaning.getName());
  target.setMeaning(meaning);
  target.setStoreable(new TimeperiodProperty(meaning.getName()));
  PropertyClause.PropertyIsBetween clause = new PropertyClause.PropertyIsBetween();
  clause.setTarget(target);
  clause.setLowerBoundary(lower);
  clause.setUpperBoundary(upper);
  
  // make the query
  BooleanQuery query = new BooleanQuery();
  TimeperiodClauseAdapter adaptor = new TimeperiodClauseAdapter(getLuceneQueryAdapter());
  adaptor.setInclusive(inclusive);
  adaptor.adaptPropertyClause(query,new LogicalClause.LogicalAnd(),clause);
  return query;
}
 
Example 37
Project: community-edition-old   File: LegacyLuceneQueryParserAdaptor.java   Source Code and License 6 votes vote down vote up
public Query getNegatedQuery() throws ParseException
{
    if(booleanQuery.getClauses().length == 0)
    {
        return getMatchAllQuery();
    }
    else if (booleanQuery.getClauses().length == 1)
    {
        BooleanClause clause = booleanQuery.getClauses()[0];
        if(clause.isProhibited())
        {
            return clause.getQuery();
        }
        else
        {
            return LegacyLuceneQueryParserAdaptor.this.getNegatedQuery(getQuery());
        }
    }
    else
    {
        return LegacyLuceneQueryParserAdaptor.this.getNegatedQuery(getQuery());
    }
}
 
Example 38
Project: marathonv5   File: IndexSearcher.java   Source Code and License 5 votes vote down vote up
public Map<DocumentType, List<SearchResult>> search(String searchString) throws ParseException {
    Map<DocumentType, List<SearchResult>> resultMap = new TreeMap<DocumentType, List<SearchResult>>();
    try {
        Query query = parser.parse(searchString);
        final SecondPassGroupingCollector collector = new SecondPassGroupingCollector("documentType", searchGroups,
                Sort.RELEVANCE, null, 5, true, false, true);
        searcher.search(query, collector);
        final TopGroups groups = collector.getTopGroups(0);
        for (GroupDocs groupDocs : groups.groups) {
            DocumentType docType = DocumentType.valueOf(groupDocs.groupValue);
            List<SearchResult> results = new ArrayList<SearchResult>();
            for (ScoreDoc scoreDoc : groupDocs.scoreDocs) {
                Document doc = searcher.doc(scoreDoc.doc);
                SearchResult result = new SearchResult(
                        docType,
                        doc.get("name"),
                        doc.get("url"),
                        doc.get("className"),
                        doc.get("package"),
                        doc.get("ensemblePath"),
                        doc.get("shortDescription")
                );
                results.add(result);
            }
            resultMap.put(docType, results);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return resultMap;
}
 
Example 39
Project: marathonv5   File: IndexSearcher.java   Source Code and License 5 votes vote down vote up
public Map<DocumentType, List<SearchResult>> search(String searchString) throws ParseException {
    Map<DocumentType, List<SearchResult>> resultMap = new TreeMap<DocumentType, List<SearchResult>>();
    try {
        Query query = parser.parse(searchString);
        final SecondPassGroupingCollector collector = new SecondPassGroupingCollector("documentType", searchGroups,
                Sort.RELEVANCE, null, 5, true, false, true);
        searcher.search(query, collector);
        final TopGroups groups = collector.getTopGroups(0);
        for (GroupDocs groupDocs : groups.groups) {
            DocumentType docType = DocumentType.valueOf(groupDocs.groupValue);
            List<SearchResult> results = new ArrayList<SearchResult>();
            for (ScoreDoc scoreDoc : groupDocs.scoreDocs) {
                Document doc = searcher.doc(scoreDoc.doc);
                SearchResult result = new SearchResult(
                        docType,
                        doc.get("name"),
                        doc.get("url"),
                        doc.get("className"),
                        doc.get("package"),
                        doc.get("ensemblePath"),
                        doc.get("shortDescription")
                );
                results.add(result);
            }
            resultMap.put(docType, results);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return resultMap;
}
 
Example 40
Project: joai-project   File: FieldExpansionQueryParser.java   Source Code and License 5 votes vote down vote up
/**
 *  Parses a query string, returning a Query. Same as the QueryParser parse method but adds the ability to
 *  specify the default field rather than using the one initialized in the constructor.
 *
 * @param  query            the query string to be parsed.
 * @param  field            the default field for this query.
 * @return                  A Query Object.
 * @throws  ParseException  if the parsing fails
 */
public Query parse(String query, String field) throws ParseException {
	ReInit(new FastCharStream(new StringReader(query)));
	try {
		return Query(field);
	} catch (TokenMgrError tme) {
		throw new ParseException(tme.getMessage());
	} catch (BooleanQuery.TooManyClauses tmc) {
		throw new ParseException("Too many boolean clauses");
	}
}
 
Example 41
Project: joai-project   File: ExtractorQueryParser.java   Source Code and License 5 votes vote down vote up
/**
 *  Gets the fieldQuery attribute of the ExtractorQueryParser object
 *
 * @param  field               The field being processed
 * @param  queryText           The text in the field
 * @return                     The fieldQuery value
 * @exception  ParseException  If error
 */
protected Query getFieldQuery(String field, String queryText)
	 throws ParseException {

	if (field.equals(extractField)) {
		// If > 1 term, "this was a phrase"...
		String[] terms = queryText.split("\\s+");
		for (int i = 0; i < terms.length; i++)
			fieldTerms.add(terms[i]);
	}

	return null;
}
 
Example 42
Project: Equella   File: TLEQueryParser.java   Source Code and License 5 votes vote down vote up
@Override
public org.apache.lucene.search.Query parse(String query) throws ParseException
{
	/**
	 * Seriously ghetto code follows. This is to combat lucene query syntax
	 * in item titles. If the title is autocompleted the query should
	 * already be escaped (using QueryParser.escape) and if it is manually
	 * entered plus "+", hyphen "-" and exclamation "!" should only be
	 * considered prohibitors if directly followed by the term. Hopefully
	 * this can be removed in future due to the following fix in Lucene
	 * 3.6.1 and higher - https://issues.apache.org/jira/browse/LUCENE-2566
	 * Which changes the way - + ! are handled. Does not appear to work
	 * correctly for ! though.
	 */
	Matcher matcher = pattern.matcher(query);
	StringBuffer s = new StringBuffer();

	while( matcher.find() )
	{
		matcher.appendReplacement(s, "\\\\" + matcher.group()); //$NON-NLS-1$
	}
	matcher.appendTail(s);

	String buffered = s.toString();
	if( !Check.isEmpty(buffered) )
	{
		query = buffered;
	}

	return super.parse(query);
}
 
Example 43
Project: parabuild-ci   File: SearchServiceImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Performs search.
 *
 * @param queryString
 * @param defaultField
 */
public Hits search(final String queryString, final String defaultField) throws IOException, ParseException {
  final Searcher searcher = new IndexSearcher(ConfigurationConstants.INDEX_HOME.getAbsolutePath());
  final Analyzer analyzer = makeAnalyzer();
  final QueryParser queryParser = new QueryParser(defaultField, analyzer);
  queryParser.setOperator(QueryParser.DEFAULT_OPERATOR_AND);
  final Query query = queryParser.parse(queryString);
  if (log.isDebugEnabled()) log.debug("Searching for: " + query.toString("contents"));
  final Hits hits = searcher.search(query);
  // REVIEWME: [email protected] -> how do we close searcher?
  if (log.isDebugEnabled()) log.debug(hits.length() + " total matching documents");
  return hits;
}
 
Example 44
Project: my-paper   File: SearchServiceImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public Page<Article> search(String keyword, Pageable pageable) {
	if (StringUtils.isEmpty(keyword)) {
		return new Page<Article>();
	}
	if (pageable == null) {
		pageable = new Pageable();
	}
	try {
		String text = QueryParser.escape(keyword);
		QueryParser titleParser = new QueryParser(Version.LUCENE_35, "title", new IKAnalyzer());
		titleParser.setDefaultOperator(QueryParser.AND_OPERATOR);
		Query titleQuery = titleParser.parse(text);
		FuzzyQuery titleFuzzyQuery = new FuzzyQuery(new Term("title", text), FUZZY_QUERY_MINIMUM_SIMILARITY);
		Query contentQuery = new TermQuery(new Term("content", text));
		Query isPublicationQuery = new TermQuery(new Term("isPublication", "true"));
		BooleanQuery textQuery = new BooleanQuery();
		BooleanQuery query = new BooleanQuery();
		textQuery.add(titleQuery, Occur.SHOULD);
		textQuery.add(titleFuzzyQuery, Occur.SHOULD);
		textQuery.add(contentQuery, Occur.SHOULD);
		query.add(isPublicationQuery, Occur.MUST);
		query.add(textQuery, Occur.MUST);
		FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
		FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Article.class);
		fullTextQuery.setSort(new Sort(new SortField[] { new SortField("isTop", SortField.STRING, true), new SortField(null, SortField.SCORE), new SortField("createDate", SortField.LONG, true) }));
		fullTextQuery.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize());
		fullTextQuery.setMaxResults(pageable.getPageSize());
		return new Page<Article>(fullTextQuery.getResultList(), fullTextQuery.getResultSize(), pageable);
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return new Page<Article>();
}
 
Example 45
Project: document-management-system   File: WikiPageIdx.java   Source Code and License 5 votes vote down vote up
/**
 * Perform search
 */
public static TopDocs performSearch(String field, String qs) throws IOException, ParseException {
	IndexSearcher searcher = Indexer.getIndexSearcher();
	QueryParser parser = new QueryParser(Config.LUCENE_VERSION, field, Indexer.getAnalyzer());
	Query query = parser.parse(qs);
	TopDocs result = searcher.search(query, Indexer.HITS_PER_PAGE);
	return result;
}
 
Example 46
Project: document-management-system   File: SearchDemo.java   Source Code and License 5 votes vote down vote up
/**
 * Add documents
 */
private static void add(Directory index, Analyzer analyzer, String str) throws IOException, ParseException {
	IndexWriterConfig config = new IndexWriterConfig(Config.LUCENE_VERSION, analyzer);
	IndexWriter w = new IndexWriter(index, config);
	Document doc = new Document();
	doc.add(new Field(DOC_FIELD, str, Field.Store.YES, Field.Index.ANALYZED));
	w.addDocument(doc);
	w.close();
}
 
Example 47
Project: rrs   File: SearchController.java   Source Code and License 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/search/{key}", method = RequestMethod.GET, 
			produces="application/json;charset=UTF-8")
public String search(@PathVariable String key) throws IOException, 
		ParseException, InvalidTokenOffsetsException {
	return searchData(key);
}
 
Example 48
Project: dls-repository-stack   File: VirtualSearchFieldMapper.java   Source Code and License 5 votes vote down vote up
/**
 *  Sets the Query assigned for the given field and term, overwriting any previous definition. The query
 *  String provided must conform to the grammar understood by the {@link
 *  org.apache.lucene.queryParser.QueryParser} Object that was passed into the constructor.
 *
 * @param  virtualField        The field
 * @param  virtualTerm         The term
 * @param  query               The new Query value for this field/term
 * @exception  ParseException  If error parsing the query String
 */
public void setQuery(String virtualField, String virtualTerm, String query) throws ParseException {
	if (virtualField == null || virtualTerm == null || query == null || localQueryParser == null)
		return;

	HashMap virtualFieldMap = (HashMap) virtualFields.get(virtualField);
	if (virtualFieldMap == null)
		virtualFieldMap = new HashMap();
	virtualFieldMap.put(virtualTerm, localQueryParser.parse(query));
	virtualFields.put(virtualField, virtualFieldMap);
}
 
Example 49
Project: dls-repository-stack   File: FieldExpansionQueryParser.java   Source Code and License 5 votes vote down vote up
/**
 *  Parses a query string, returning a Query. Same as the QueryParser parse method but adds the ability to
 *  specify the default field rather than using the one initialized in the constructor.
 *
 * @param  query            the query string to be parsed.
 * @param  field            the default field for this query.
 * @return                  A Query Object.
 * @throws  ParseException  if the parsing fails
 */
public Query parse(String query, String field) throws ParseException {
	ReInit(new FastCharStream(new StringReader(query)));
	try {
		return Query(field);
	} catch (TokenMgrError tme) {
		throw new ParseException(tme.getMessage());
	} catch (BooleanQuery.TooManyClauses tmc) {
		throw new ParseException("Too many boolean clauses");
	}
}
 
Example 50
Project: dls-repository-stack   File: ExtractorQueryParser.java   Source Code and License 5 votes vote down vote up
/**
 *  Gets the fieldQuery attribute of the ExtractorQueryParser object
 *
 * @param  field               The field being processed
 * @param  queryText           The text in the field
 * @return                     The fieldQuery value
 * @exception  ParseException  If error
 */
protected Query getFieldQuery(String field, String queryText)
	 throws ParseException {

	if (field.equals(extractField)) {
		// If > 1 term, "this was a phrase"...
		String[] terms = queryText.split("\\s+");
		for (int i = 0; i < terms.length; i++)
			fieldTerms.add(terms[i]);
	}

	return null;
}
 
Example 51
Project: Wiab.pro   File: LuceneSearchImpl.java   Source Code and License 5 votes vote down vote up
private Query makeQuery(List<IndexCondition> conditions) throws ParseException {
  BooleanQuery query = new BooleanQuery();
  for (IndexCondition condition : conditions) {
    query.add(makeQuery(condition), condition.isNot()?Occur.MUST_NOT:Occur.MUST);
  }
  return query;
}
 
Example 52
Project: ephesoft   File: QueryParser.java   Source Code and License 5 votes vote down vote up
/**
 * Base implementation delegates to {@link #getFieldQuery(String,String)}. This method may be overridden, for example, to return a
 * SpanNearQuery instead of a PhraseQuery.
 * 
 * @exception ParseException throw in overridden method to disallow
 */
protected Query getFieldQuery(String field, String queryText, int slop) throws ParseException {
	Query query = getFieldQuery(field, queryText);

	if (query instanceof PhraseQuery) {
		((PhraseQuery) query).setSlop(slop);
	}
	if (query instanceof MultiPhraseQuery) {
		((MultiPhraseQuery) query).setSlop(slop);
	}

	return query;
}
 
Example 53
Project: ephesoft   File: QueryParser.java   Source Code and License 5 votes vote down vote up
/**
 * @exception ParseException throw in overridden method to disallow
 */
protected Query getRangeQuery(String field, String part1, String part2, boolean inclusive) throws ParseException {
	if (lowercaseExpandedTerms) {
		part1 = part1.toLowerCase();
		part2 = part2.toLowerCase();
	}
	try {
		DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
		df.setLenient(true);
		Date d1 = df.parse(part1);
		Date d2 = df.parse(part2);
		if (inclusive) {
			// The user can only specify the date, not the time, so make sure
			// the time is set to the latest possible time of that date to really
			// include all documents:
			Calendar cal = Calendar.getInstance(locale);
			cal.setTime(d2);
			cal.set(Calendar.HOUR_OF_DAY, 23);
			cal.set(Calendar.MINUTE, 59);
			cal.set(Calendar.SECOND, 59);
			cal.set(Calendar.MILLISECOND, 999);
			d2 = cal.getTime();
		}
		DateTools.Resolution resolution = getDateResolution(field);
		if (resolution == null) {
			// no default or field specific date resolution has been set,
			// use deprecated DateField to maintain compatibility with
			// pre-1.9 Lucene versions.
			part1 = DateField.dateToString(d1);
			part2 = DateField.dateToString(d2);
		} else {
			part1 = DateTools.dateToString(d1, resolution);
			part2 = DateTools.dateToString(d2, resolution);
		}
	} catch (Exception e) {
	}

	return newRangeQuery(field, part1, part2, inclusive);
}
 
Example 54
Project: ephesoft   File: QueryParser.java   Source Code and License 5 votes vote down vote up
/** Returns the numeric value of the hexadecimal character */
private static final int hexToInt(char c) throws ParseException {
	if ('0' <= c && c <= '9') {
		return c - '0';
	} else if ('a' <= c && c <= 'f') {
		return c - 'a' + 10;
	} else if ('A' <= c && c <= 'F') {
		return c - 'A' + 10;
	} else {
		throw new ParseException("None-hex character in unicode escape sequence: " + c);
	}
}
 
Example 55
Project: ephesoft   File: QueryParser.java   Source Code and License 5 votes vote down vote up
final public int Conjunction() throws ParseException {
	int ret = CONJ_NONE;
	switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
		case AND:
		case OR:
			switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
				case AND:
					jj_consume_token(AND);
					ret = CONJ_AND;
					break;
				case OR:
					jj_consume_token(OR);
					ret = CONJ_OR;
					break;
				default:
					jj_la1[0] = jj_gen;
					jj_consume_token(-1);
					throw new ParseException();
			}
			break;
		default:
			jj_la1[1] = jj_gen;
			;
	}
	{
		if (true)
			return ret;
	}
	throw new Error("Missing return statement in function");
}
 
Example 56
Project: ephesoft   File: QueryParser.java   Source Code and License 5 votes vote down vote up
final public int Modifiers() throws ParseException {
	int ret = MOD_NONE;
	switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
		case NOT:
		case PLUS:
		case MINUS:
			switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
				case PLUS:
					jj_consume_token(PLUS);
					ret = MOD_REQ;
					break;
				case MINUS:
					jj_consume_token(MINUS);
					ret = MOD_NOT;
					break;
				case NOT:
					jj_consume_token(NOT);
					ret = MOD_NOT;
					break;
				default:
					jj_la1[2] = jj_gen;
					jj_consume_token(-1);
					throw new ParseException();
			}
			break;
		default:
			jj_la1[3] = jj_gen;
			;
	}
	{
		if (true)
			return ret;
	}
	throw new Error("Missing return statement in function");
}
 
Example 57
Project: ephesoft   File: QueryParser.java   Source Code and License 5 votes vote down vote up
final public Query TopLevelQuery(String field) throws ParseException {
	Query q;
	q = Query(field);
	jj_consume_token(0);
	{
		if (true)
			return q;
	}
	throw new Error("Missing return statement in function");
}
 
Example 58
Project: ephesoft   File: QueryParser.java   Source Code and License 5 votes vote down vote up
/** Generate ParseException. */
public ParseException generateParseException() {
	jj_expentries.clear();
	boolean[] la1tokens = new boolean[34];
	if (jj_kind >= 0) {
		la1tokens[jj_kind] = true;
		jj_kind = -1;
	}
	for (int i = 0; i < 23; i++) {
		if (jj_la1[i] == jj_gen) {
			for (int j = 0; j < 32; j++) {
				if ((jj_la1_0[i] & (1 << j)) != 0) {
					la1tokens[j] = true;
				}
				if ((jj_la1_1[i] & (1 << j)) != 0) {
					la1tokens[32 + j] = true;
				}
			}
		}
	}
	for (int i = 0; i < 34; i++) {
		if (la1tokens[i]) {
			jj_expentry = new int[1];
			jj_expentry[0] = i;
			jj_expentries.add(jj_expentry);
		}
	}
	jj_endpos = 0;
	jj_rescan_token();
	jj_add_error_token(0, 0);
	int[][] exptokseq = new int[jj_expentries.size()][];
	for (int i = 0; i < jj_expentries.size(); i++) {
		exptokseq[i] = jj_expentries.get(i);
	}
	return new ParseException(token, exptokseq, tokenImage);
}
 
Example 59
Project: Tank   File: FieldSearchParam.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Query getLuceneQuery() {
    QueryParser qp = new QueryParser(SearchConstants.version, fieldName, SearchConstants.analyzer);
    if (value.startsWith("*")) {
        qp.setAllowLeadingWildcard(true);
    }
    Query parse = null;
    try {
        parse = qp.parse(value);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return parse;
    // return new TermQuery(new Term(fieldName, value));
}
 
Example 60
Project: ldadmin   File: GenericDaoHibernate.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public List<T> search(String searchTerm) throws SearchException {
    Session sess = getSession();
    FullTextSession txtSession = Search.getFullTextSession(sess);

    org.apache.lucene.search.Query qry;
    try {
        qry = HibernateSearchTools.generateQuery(searchTerm, this.persistentClass, sess, defaultAnalyzer);
    } catch (ParseException ex) {
        throw new SearchException(ex);
    }
    org.hibernate.search.FullTextQuery hibQuery = txtSession.createFullTextQuery(qry,
            this.persistentClass);
    return hibQuery.list();
}