List of usage examples for org.apache.lucene.search BooleanQuery BooleanQuery
BooleanQuery
From source file:com.searchbox.solr.SenseLikeThisHandlerNoReduction.java
License:Apache License
@Override public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { SolrParams params = req.getParams(); if (!keystate) { LOGGER.error(/*from w ww. j av a 2s .c o m*/ "License key failure, not performing sense query. Please email contact@searchbox.com for more information."); return; } int docID; // Set field flags ReturnFields returnFields = new SolrReturnFields(req); rsp.setReturnFields(returnFields); int flags = 0; if (returnFields.wantsScore()) { flags |= SolrIndexSearcher.GET_SCORES; } String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE); String q = params.get(CommonParams.Q); Query query = null; SortSpec sortSpec = null; List<Query> filters = new ArrayList<Query>(); try { if (q != null) { QParser parser = QParser.getParser(q, defType, req); query = parser.getQuery(); sortSpec = parser.getSort(true); } String[] fqs = req.getParams().getParams(CommonParams.FQ); if (fqs != null && fqs.length != 0) { for (String fq : fqs) { if (fq != null && fq.trim().length() != 0) { QParser fqp = QParser.getParser(fq, null, req); filters.add(fqp.getQuery()); } } } } catch (Exception e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e); } SolrIndexSearcher searcher = req.getSearcher(); SchemaField uniqueKeyField = searcher.getSchema().getUniqueKeyField(); DocListAndSet sltDocs = null; // Parse Required Params // This will either have a single Reader or valid query Reader reader = null; try { if (q == null || q.trim().length() < 1) { Iterable<ContentStream> streams = req.getContentStreams(); if (streams != null) { Iterator<ContentStream> iter = streams.iterator(); if (iter.hasNext()) { reader = iter.next().getReader(); } if (iter.hasNext()) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "SenseLikeThis does not support multiple ContentStreams"); } } } int start = params.getInt(CommonParams.START, 0); int rows = params.getInt(CommonParams.ROWS, 10); // Find documents SenseLikeThis - either with a reader or a query // -------------------------------------------------------------------------------- SenseQuery slt = null; if (reader != null) { throw new RuntimeException("SLT based on a reader is not yet implemented"); } else if (q != null) { // Matching options boolean includeMatch = params.getBool(MoreLikeThisParams.MATCH_INCLUDE, true); int matchOffset = params.getInt(MoreLikeThisParams.MATCH_OFFSET, 0); // Find the base match DocList match = searcher.getDocList(query, null, null, matchOffset, 1, flags); // only get the first one... if (includeMatch) { rsp.add("match", match); } // Get docID DocIterator iterator = match.iterator(); docID = iterator.nextDoc(); BooleanQuery bq = new BooleanQuery(); Document doc = searcher.getIndexReader().document(docID); bq.add(new TermQuery(new Term(uniqueKeyField.getName(), uniqueKeyField.getType().storedToIndexed(doc.getField(uniqueKeyField.getName())))), BooleanClause.Occur.MUST_NOT); filters.add(bq); } else { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "SenseLikeThis requires either a query (?q=) or text to find similar documents."); } String CKBid = params.get(SenseParams.SENSE_CKB, SenseParams.SENSE_CKB_DEFAULT); String senseField = params.get(SenseParams.SENSE_FIELD, SenseParams.DEFAULT_SENSE_FIELD); slt = new SenseQuery(new RealTermFreqVector(docID, searcher.getIndexReader(), senseField), senseField, CKBid, params.getFloat(SenseParams.SENSE_WEIGHT, SenseParams.DEFAULT_SENSE_WEIGHT), null); //Execute the SLT query //DocSet filtered = searcher.getDocSet(filters); //System.out.println("Number of documents to search:\t" + filtered.size()); //sltDocs = searcher.getDocListAndSet(slt, filtered, Sort.RELEVANCE, start, rows, flags); sltDocs = searcher.getDocListAndSet(slt, filters, Sort.RELEVANCE, start, rows, flags); } finally { if (reader != null) { reader.close(); } } if (sltDocs == null) { sltDocs = new DocListAndSet(); // avoid NPE } rsp.add("response", sltDocs.docList); // maybe facet the results if (params.getBool(FacetParams.FACET, false)) { if (sltDocs.docSet == null) { rsp.add("facet_counts", null); } else { SimpleFacets f = new SimpleFacets(req, sltDocs.docSet, params); rsp.add("facet_counts", f.getFacetCounts()); } } // Debug info, not doing it for the moment. boolean dbg = req.getParams().getBool(CommonParams.DEBUG_QUERY, false); boolean dbgQuery = false, dbgResults = false; if (dbg == false) {//if it's true, we are doing everything anyway. String[] dbgParams = req.getParams().getParams(CommonParams.DEBUG); if (dbgParams != null) { for (int i = 0; i < dbgParams.length; i++) { if (dbgParams[i].equals(CommonParams.QUERY)) { dbgQuery = true; } else if (dbgParams[i].equals(CommonParams.RESULTS)) { dbgResults = true; } } } } else { dbgQuery = true; dbgResults = true; } // Copied from StandardRequestHandler... perhaps it should be added to doStandardDebug? if (dbg == true) { try { NamedList<Object> dbgInfo = SolrPluginUtils.doStandardDebug(req, q, query, sltDocs.docList, dbgQuery, dbgResults); if (null != dbgInfo) { if (null != filters) { dbgInfo.add("filter_queries", req.getParams().getParams(CommonParams.FQ)); List<String> fqs = new ArrayList<String>(filters.size()); for (Query fq : filters) { fqs.add(QueryParsing.toString(fq, req.getSchema())); } dbgInfo.add("parsed_filter_queries", fqs); } rsp.add("debug", dbgInfo); } } catch (Exception e) { SolrException.log(SolrCore.log, "Exception during debug", e); rsp.add("exception_during_debug", SolrException.toStr(e)); } } }
From source file:com.silverwrist.dynamo.index.IndexServiceImpl.java
License:Mozilla Public License
private final Query compileInternal(String query_string, java.util.Date date_low, java.util.Date date_high, DynamoUser match_owner, String match_scope) throws IndexException { ArrayList queries = new ArrayList(); if (query_string != null) { // we have a query language string... try { // parse the query string, which matches on the "text" field only queries.add(Parser.parse(query_string)); } // end try catch (ParseException pe) { // parse error in the query IndexException ie = new IndexException(IndexServiceImpl.class, "IndexMessages", "query.syntax", pe); ie.setParameter(0, pe.getMessage()); throw ie; } // end catch } // end if/*from ww w . j ava 2s . co m*/ if ((date_low != null) || (date_high != null)) { // add an inclusive range of dates Term term_low = null, term_high = null; if (date_low != null) term_low = new Term("date", DateField.dateToString(date_low)); if (date_high != null) term_high = new Term("date", DateField.dateToString(date_high)); queries.add(new RangeQuery(term_low, term_high, true)); } // end if if (match_owner != null) queries.add(new TermQuery(new Term("owner", match_owner.getName()))); if (match_scope != null) { // treat "scope" as a possible wildcard match and create it if (match_scope.indexOf('?') >= 0) queries.add(new WildcardQuery(new Term("scope", match_scope))); else if (match_scope.indexOf('*') >= 0) { // append another query String s = match_scope.substring(0, match_scope.length() - 1); if (s.indexOf('*') < 0) queries.add(new PrefixQuery(new Term("scope", s))); else queries.add(new WildcardQuery(new Term("scope", match_scope))); } // end else if else // match the scope directly queries.add(new TermQuery(new Term("scope", match_scope))); } // end if // Boil down all the queries for me. if (queries.size() == 0) return null; if (queries.size() == 1) return (Query) (queries.get(0)); BooleanQuery rc = new BooleanQuery(); for (int i = 0; i < queries.size(); i++) rc.add((Query) (queries.get(i)), true, false); return rc; }
From source file:com.sindicetech.siren.qparser.keyword.BasicSyntaxTest.java
License:Open Source License
@Test public void testParseEmpty() throws Exception { assertEquals(new BooleanQuery(), this.parse(null, "")); }
From source file:com.sindicetech.siren.qparser.keyword.BasicSyntaxTest.java
License:Open Source License
@Test public void testBoostQuery() throws Exception { final BooleanQuery q = new BooleanQuery(); q.add(ntq("c").getLuceneProxyQuery(), BooleanClause.Occur.MUST); final NodeQuery nq = ntq("b").getQuery(); nq.setBoost(2);//from ww w .j a v a2 s . c om q.add(new LuceneProxyNodeQuery(nq), BooleanClause.Occur.MUST); this._assertSirenQuery(q, "c b^2"); }
From source file:com.sindicetech.siren.qparser.keyword.BasicSyntaxTest.java
License:Open Source License
@Test public void testDatatypes1() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); // Set the default datatypes final Map<String, Analyzer> datatypes = new HashMap<String, Analyzer>(); datatypes.put("xsd:int", new IntNumericAnalyzer(4)); final Analyzer dateAnalyser = new Analyzer() { @Override// w ww. ja v a2 s. c o m protected TokenStreamComponents createComponents(final String fieldName, final Reader reader) { final WhitespaceTokenizer t = new WhitespaceTokenizer(LuceneTestCase.TEST_VERSION_CURRENT, reader); final TokenStream ts = new LowerCaseFilter(LuceneTestCase.TEST_VERSION_CURRENT, t); return new TokenStreamComponents(t, ts); } }; datatypes.put("xsd:date", dateAnalyser); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, datatypes); // Test for custom datatypes final BooleanQuery bq1 = new BooleanQuery(); final DatatypedNodeQuery range1 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 12, 21, true, true); range1.setDatatype("xsd:int"); bq1.add(new LuceneProxyNodeQuery(range1), BooleanClause.Occur.MUST); final Query npq = npq("12", "oct", "2012").setDatatype("xsd:date").getLuceneProxyQuery(); bq1.add(npq, BooleanClause.Occur.MUST); this._assertSirenQuery(config, bq1, "xsd:int([12 TO 21]) xsd:date(\"12 Oct 2012\")"); }
From source file:com.sindicetech.siren.qparser.keyword.BasicSyntaxTest.java
License:Open Source License
@Test public void testDatatypes2() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); // Set the default datatypes final Map<String, Analyzer> datatypes = new HashMap<String, Analyzer>(); datatypes.put("xsd:int", new IntNumericAnalyzer(4)); final Analyzer dateAnalyser = new Analyzer() { @Override/*from w w w.j a v a2 s. co m*/ protected TokenStreamComponents createComponents(final String fieldName, final Reader reader) { final WhitespaceTokenizer t = new WhitespaceTokenizer(LuceneTestCase.TEST_VERSION_CURRENT, reader); final TokenStream ts = new LowerCaseFilter(LuceneTestCase.TEST_VERSION_CURRENT, t); return new TokenStreamComponents(t, ts); } }; datatypes.put("xsd:date", dateAnalyser); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, datatypes); // Test for custom datatypes final BooleanQuery bq1 = new BooleanQuery(); final BooleanQuery bq2 = new BooleanQuery(); final DatatypedNodeQuery range1 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 12, 21, true, true); range1.setDatatype("xsd:int"); bq2.add(new LuceneProxyNodeQuery(range1), BooleanClause.Occur.MUST); final DatatypedNodeQuery range2 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 12, 12, true, true); range2.setDatatype("xsd:int"); bq2.add(new LuceneProxyNodeQuery(range2), BooleanClause.Occur.MUST); bq1.add(bq2, BooleanClause.Occur.MUST); final Query npq = npq("12", "oct", "2012").setDatatype("xsd:date").getLuceneProxyQuery(); bq1.add(npq, BooleanClause.Occur.MUST); this._assertSirenQuery(config, bq1, "(xsd:int([12 TO 21] '12')) xsd:date(\"12 Oct 2012\")"); }
From source file:com.sindicetech.siren.qparser.keyword.BasicSyntaxTest.java
License:Open Source License
/** * Multiple terms in a datatype are in a group *//* w w w. ja v a 2s. c o m*/ @Test public void testDatatypes3() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); // Set the default datatypes final Map<String, Analyzer> datatypes = new HashMap<String, Analyzer>(); datatypes.put("xsd:int", new IntNumericAnalyzer(4)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, datatypes); // Test for custom datatypes final BooleanQuery bq1 = new BooleanQuery(); final DatatypedNodeQuery range1To10 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 1, 10, true, true); range1To10.setDatatype("xsd:int"); final DatatypedNodeQuery range20To40 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 20, 40, true, true); range20To40.setDatatype("xsd:int"); bq1.add(new LuceneProxyNodeQuery(range1To10), BooleanClause.Occur.SHOULD); bq1.add(new LuceneProxyNodeQuery(range20To40), BooleanClause.Occur.SHOULD); final BooleanQuery bq2 = new BooleanQuery(); final DatatypedNodeQuery range10To15 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 10, 15, true, true); range10To15.setDatatype("xsd:int"); final DatatypedNodeQuery range50To55 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 50, 55, true, true); range50To55.setDatatype("xsd:int"); bq2.add(new LuceneProxyNodeQuery(range10To15), BooleanClause.Occur.SHOULD); bq2.add(new LuceneProxyNodeQuery(range50To55), BooleanClause.Occur.SHOULD); final BooleanQuery bq3 = new BooleanQuery(); bq3.add(bq1, BooleanClause.Occur.MUST); bq3.add(bq2, BooleanClause.Occur.MUST); this._assertSirenQuery(config, bq3, "(xsd:int([1 TO 10] OR [20 TO 40])) AND (xsd:int([10 TO 15] OR [50 TO 55]))"); }
From source file:com.sindicetech.siren.qparser.keyword.BasicSyntaxTest.java
License:Open Source License
@Test public void testDatatypes4() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); // Set the default datatypes final Map<String, Analyzer> datatypes = new HashMap<String, Analyzer>(); datatypes.put("xsd:int", new IntNumericAnalyzer(4)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, datatypes); // Test for custom datatypes final BooleanQuery bq1 = new BooleanQuery(); final DatatypedNodeQuery range1 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 1, 1, true, true);// ww w . ja v a 2 s . c om range1.setDatatype("xsd:int"); bq1.add(new LuceneProxyNodeQuery(range1), BooleanClause.Occur.MUST); final DatatypedNodeQuery range2 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 2, 2, true, true); range2.setDatatype("xsd:int"); bq1.add(new LuceneProxyNodeQuery(range2), BooleanClause.Occur.MUST_NOT); this._assertSirenQuery(config, bq1, "+xsd:int(1) -xsd:int(2)"); this._assertSirenQuery(config, bq1, "xsd:int(+1 -2)"); }
From source file:com.sindicetech.siren.qparser.keyword.BasicSyntaxTest.java
License:Open Source License
/** * Boolean of ranges./*from ww w . j a va 2s . com*/ * <p> * Numeric ranges get processed with {@link NodeNumericRangeQueryNodeProcessor}. * Single numeric values are processed with {@link NodeNumericQueryNodeProcessor}. */ @Test public void testNumericQuery3() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); final Map<String, Analyzer> datatypes = new HashMap<String, Analyzer>(); datatypes.put("int", new IntNumericAnalyzer(4)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, datatypes); config.put(ConfigurationKeys.DEFAULT_OPERATOR, Operator.OR); final DatatypedNodeQuery r1 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 50, 100, true, true); r1.setDatatype("int"); final DatatypedNodeQuery r2 = NodeNumericRangeQuery.newIntRange(SirenTestCase.DEFAULT_TEST_FIELD, 4, 100, 500, true, true); r2.setDatatype("int"); final BooleanQuery bq = new BooleanQuery(); bq.add(new LuceneProxyNodeQuery(r1), BooleanClause.Occur.SHOULD); bq.add(new LuceneProxyNodeQuery(r2), BooleanClause.Occur.SHOULD); this._assertSirenQuery(config, bq, "int([50 TO 100] OR [100 TO 500])"); }
From source file:com.sindicetech.siren.qparser.keyword.builders.AnyQueryNodeBuilder.java
License:Open Source License
public BooleanQuery build(QueryNode queryNode) throws QueryNodeException { AnyQueryNode andNode = (AnyQueryNode) queryNode; BooleanQuery bQuery = new BooleanQuery(); List<QueryNode> children = andNode.getChildren(); if (children != null) { for (QueryNode child : children) { Object obj = child.getTag(QueryTreeBuilder.QUERY_TREE_BUILDER_TAGID); if (obj != null) { Query query = (Query) obj; try { bQuery.add(query, BooleanClause.Occur.SHOULD); } catch (TooManyClauses ex) { throw new QueryNodeException(new MessageImpl( /* * IQQQ.Q0028E_TOO_MANY_BOOLEAN_CLAUSES, * BooleanQuery.getMaxClauseCount() *//*from w w w .ja v a 2 s . c o m*/ QueryParserMessages.EMPTY_MESSAGE), ex); } } } } bQuery.setMinimumNumberShouldMatch(andNode.getMinimumMatchingElements()); return bQuery; }