protected void AddNumericRangeQuery(BooleanQuery query, NumericRangeField range, BooleanClause.Occur occurance)
 {
     var startTerm = new Term(range.FieldName, NumberTools.LongToString(range.Start));
     var endTerm = new Term(range.FieldName, NumberTools.LongToString(range.End));
     var rangeQuery = new RangeQuery(startTerm, endTerm, true);
     query.Add(rangeQuery, occurance);
 }
 protected void AddNumericRangeQuery(BooleanQuery query, NumericRangeField range, BooleanClause.Occur occurance)
 {
     var startTerm = new Term(range.FieldName, SearchHelper.FormatNumber(range.Start));
      var endTerm = new Term(range.FieldName, SearchHelper.FormatNumber(range.End));
      var rangeQuery = new RangeQuery(startTerm, endTerm, true);
      query.Add(rangeQuery, occurance);
 }
        internal static void AddDateRangeQuery(BooleanQuery query, DateRangeSearchParam.DateRangeField dateRangeField, BooleanClause.Occur occurance)
        {
            var startDateTime = dateRangeField.StartDate;
            if (dateRangeField.InclusiveStart)
            {
                if (startDateTime != DateTime.MinValue)
                {
                    startDateTime.ChangeTime(0, 0, 0, 0);
                }
            }

            var endDateTime = dateRangeField.EndDate;
            if (dateRangeField.InclusiveStart)
            {
                if (endDateTime != DateTime.MaxValue)
                {
                    endDateTime = endDateTime.ChangeTime(23, 59, 59, 59);
                }
            }

            BooleanQuery.SetMaxClauseCount(int.MaxValue);

            if (!(dateRangeField.StartDate == DateTime.MinValue && dateRangeField.EndDate == DateTime.MaxValue))
            {
                query.Add(new RangeQuery(new Term(SearchFieldIDs.CreatedDate, startDateTime.ToString("yyyyMMdd")), new Term(SearchFieldIDs.CreatedDate, endDateTime.ToString("yyyyMMdd")), true), occurance);
            }
        }
		public static Query MergeQueries(Query queryA, Query queryB, BooleanClause.Occur queryAOccurence, BooleanClause.Occur queryBOccurence)
		{
			BooleanQuery compoundQuery = new BooleanQuery();
			compoundQuery.Add(new BooleanClause(queryA, queryAOccurence));
			compoundQuery.Add(new BooleanClause(queryB, queryBOccurence));

			return compoundQuery;
		}
 public static Query Raw(this BooleanQuery booleanQuery, string field, string queryText, BooleanClause.Occur occur = null)
 {
     Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
     QueryParser queryParser = new QueryParser(Version.LUCENE_29, field, analyzer);
     Query query = queryParser.Parse(queryText);
     booleanQuery.Add(query, occur);
     return query;
 }
 public static PhraseQuery Phrase(this BooleanQuery inputQuery, BooleanClause.Occur occur = null)
 {
     BooleanQuery parentQuery = GetParentQuery(inputQuery);
     PhraseQuery query = new PhraseQuery();
     SetOccurValue(inputQuery, ref occur);
     parentQuery.Add(query, occur);
     return query;
 }
		public static Query MergeQueries(BooleanClause.Occur queryOccurence, params Query[] queries)
		{
			BooleanQuery compoundQuery = new BooleanQuery();
			foreach (Query query in queries)
			{
				compoundQuery.Add(new BooleanClause(query, queryOccurence));
			}
			return compoundQuery;
		}
 public static TermQuery Term(this BooleanQuery inputQuery, string fieldName, string fieldValue, BooleanClause.Occur occur = null)
 {
     Term term = new Term(fieldName, fieldValue);
     BooleanQuery parentQuery = GetParentQuery(inputQuery);
     TermQuery query = new TermQuery(term);
     SetOccurValue(inputQuery, ref occur);
     parentQuery.Add(query, occur);
     return query;
 }
 public static BooleanQuery Group(this BooleanQuery inputQuery, BooleanClause.Occur occur = null, params Action<GroupedBooleanQuery>[] queries)
 {
     var groupedBooleanQuery = inputQuery.AddGroup(BooleanClause.Occur.SHOULD, queries);
     if (groupedBooleanQuery == null)
     {
         throw new Exception("An error occurred creating the inner query");
     }
     return inputQuery.AddGroup(BooleanClause.Occur.SHOULD, queries);
 }
 public static void AddQueriesToBoolean(
     BooleanQuery bq,
     IEnumerable<Search.Query> queries,
     BooleanClause.Occur occur)
 {
     foreach (var query in queries)
     {
         bq.Add(query, occur);
     }
 }
 private static void AssertResult(LuceneQueryPredicateExpression result, BooleanClause.Occur expectedOccur)
 {
     Assert.That(result, Is.Not.Null, "Expected LuceneQueryPredicateExpression to be returned.");
     Assert.That(result, Is.Not.SameAs(predicate));
     Assert.That(result.QueryField, Is.SameAs(predicate.QueryField));
     Assert.That(result.QueryPattern, Is.SameAs(predicate.QueryPattern));
     Assert.That(result.QueryType, Is.EqualTo(predicate.QueryType));
     Assert.That(result.Occur, Is.EqualTo(expectedOccur));
     Assert.That(result.Boost, Is.EqualTo(predicate.Boost));
     Assert.That(result.AllowSpecialCharacters, Is.EqualTo(predicate.AllowSpecialCharacters));
 }
 public static Search.Query MakeBooleanQuery(
     IEnumerable<Search.Query> queries,
     BooleanClause.Occur occur)
 {
     if (queries.Count() <= 1)
     {
         throw new InvalidOperationException("Too few subqueries: " + queries.Count());
     }
     BooleanQuery bq = new BooleanQuery();
     AddQueriesToBoolean(bq, queries, occur);
     return bq;
 }
        protected BooleanQuery ApplyNumericRangeSearchParam(BooleanClause.Occur innerOccurance)
        {
            var innerQuery = new BooleanQuery();

            if (Ranges.Count <= 0) return null;

            foreach (var range in Ranges)
            {
                AddNumericRangeQuery(innerQuery, range, innerOccurance);
            }

            return innerQuery;
        }
Esempio n. 14
0
        protected BooleanQuery ApplyDateRangeSearchParam(BooleanClause.Occur innerCondition)
        {
            var innerQuery = new BooleanQuery();

             if (Ranges.Count <= 0) return null;

             foreach (var dateParam in Ranges)
             {
            AddDateRangeQuery(innerQuery, dateParam, innerCondition);
             }

             return innerQuery;
        }
        public virtual List<SkinnyItem> GetItems(IEnumerable<SearchParam> parameters, bool showAllVersions, string sortField, bool reverse, int start, int end, out int totalResults)
        {
            Assert.IsNotNull(Index, "Index");

            var translator = new QueryTranslator(Index);
            var query = new BooleanQuery();

            foreach (var parameter in parameters.Where(p => p != null))
            {
                var innerQueryResult = parameter.ProcessQuery(parameter.Condition, Index);
                if (innerQueryResult.GetClauses().Length > 0)
                {
                    var clause = new BooleanClause(innerQueryResult, translator.GetOccur(parameter.Condition));
                    query.Add(clause);
                }
            }

            return RunQuery(query, showAllVersions, sortField, reverse, start, end, out totalResults);
        }
Esempio n. 16
0
        public ISearchBuilder Parse(string[] defaultFields, string query, bool escape, bool mandatory) {
            if ( defaultFields.Length == 0 ) {
                throw new ArgumentException("Default field can't be empty");
            }

            if ( String.IsNullOrWhiteSpace(query) ) {
                throw new ArgumentException("Query can't be empty");
            }

            if (escape) {
                query = QueryParser.Escape(query);
            }

            var analyzer = LuceneIndexProvider.CreateAnalyzer();
            foreach ( var defaultField in defaultFields ) {
                var clause = new BooleanClause(new QueryParser(LuceneIndexProvider.LuceneVersion, defaultField, analyzer).Parse(query), mandatory ? BooleanClause.Occur.MUST : BooleanClause.Occur.SHOULD);
                _clauses.Add(clause);
            }
            
            _query = null;
            return this;
        }
Esempio n. 17
0
        protected void AddDateRangeQuery(BooleanQuery query, DateRange dateRangeField, BooleanClause.Occur occurance)
        {
            var startDateTime = dateRangeField.StartDate;
             var endDateTime = dateRangeField.EndDate;

             if (dateRangeField.InclusiveStart && startDateTime > DateTime.MinValue.AddDays(1))
             {
            startDateTime = startDateTime.AddDays(-1);
             }

             if (dateRangeField.InclusiveEnd && endDateTime < DateTime.MaxValue.AddDays(-1))
             {
            endDateTime = endDateTime.AddDays(1);
             }

             // converting to lucene format
             var startDate = DateTools.DateToString(startDateTime, DateTools.Resolution.DAY);
             var endDate = DateTools.DateToString(endDateTime, DateTools.Resolution.DAY);

             var rangeQuery = new RangeQuery(new Term(dateRangeField.FieldName, startDate), new Term(dateRangeField.FieldName, endDate), true);
             query.Add(rangeQuery, occurance);
        }
        public static Query BuildDateRangeSearchParam(IEnumerable<DateRangeSearchParam.DateRange> ranges, BooleanClause.Occur condition)
        {
            Assert.ArgumentNotNull(ranges, "Ranges");

            if (!ranges.Any())
            {
                return null;
            }

            if (ranges.Count() == 1)
            {
                return BuildDateRangeQuery(ranges.First());
            }

            var innerQuery = new BooleanQuery();
            foreach (var range in ranges)
            {
                innerQuery.Add(BuildDateRangeQuery(range), condition);
            }

            return innerQuery;
        }
Esempio n. 19
0
 public virtual BooleanClause[] VisitBooleanClauses(BooleanClause[] clauses)
 {
     List<BooleanClause> newList = null;
     int index = 0;
     int count = clauses.Length;
     while (index < count)
     {
         var visitedClause = VisitBooleanClause(clauses[index]);
         if (newList != null)
         {
             newList.Add(visitedClause);
         }
         else if (visitedClause != clauses[index])
         {
             newList = new List<BooleanClause>();
             for (int i = 0; i < index; i++)
                 newList.Add(clauses[i]);
             newList.Add(visitedClause);
         }
         index++;
     }
     return newList != null ? newList.ToArray() : clauses;
 }
Esempio n. 20
0
 public override void Add(BooleanClause clause)
 {
     throw new NotSupportedException();
 }
Esempio n. 21
0
        protected void ApplyLanguageClause(BooleanQuery query, string language, BooleanClause.Occur occurance)
        {
            if (String.IsNullOrEmpty(language)) return;

            var phraseQuery = new PhraseQuery();
            phraseQuery.Add(new Term(BuiltinFields.Language, language.ToLowerInvariant()));

            query.Add(phraseQuery, occurance);
        }
Esempio n. 22
0
        private Query CompileExpressionListNode(ExpressionList expression)
        {
            int expCount = expression.Expressions.Count;
            if (expCount == 0)
                throw new NotSupportedException("Do not use empty ExpressionList");

            if (expression.Expressions.Count == 1)
                return CompileExpressionNode(expression.Expressions[0]);

            var result = new BooleanQuery();
            var occur = (expression.OperatorType == ChainOperator.And) ? BooleanClause.Occur.MUST : BooleanClause.Occur.SHOULD;
            foreach (Expression expr in expression.Expressions)
            {
                //var q = CompileExpressionNode(expr);
                //var clause = new BooleanClause(q, occur);
                //result.Add(clause);

                Query q;
                BooleanClause clause;
                var notExp = expr as NotExpression;
                if (notExp != null)
                {
                    q = CompileExpressionNode(notExp.Expression);
                    clause = new BooleanClause(q, BooleanClause.Occur.MUST_NOT);
                }
                else
                {
                    var binwrapper = expr as IBinaryExpressionWrapper;
                    if (binwrapper != null && binwrapper.BinExp.Operator == Operator.NotEqual)
                    {
                        q = CompileBinaryExpression(binwrapper.BinExp.LeftValue, Operator.Equal, binwrapper.BinExp.RightValue);
                        clause = new BooleanClause(q, BooleanClause.Occur.MUST_NOT);
                    }
                    else
                    {
                        q = CompileExpressionNode(expr);
                        clause = new BooleanClause(q, occur);
                    }
                }
                result.Add(clause);
            }
            return result;
        }
Esempio n. 23
0
        private Query CompileNotExpressionNode(NotExpression expression)
        {
            //var notInTreeQ = CompileCheckNotInTreeQuery(expression);
            //if (notInTreeQ != null)
            //    return notInTreeQ;

            var q = CompileExpressionNode(expression.Expression);
            var result = new BooleanQuery();
            var clause = new BooleanClause(q, BooleanClause.Occur.MUST_NOT);
            result.Add(clause);
            return result;
        }
Esempio n. 24
0
        private void AddBooleanClause(BooleanQuery boolQuery, Query query, BooleanClause.Occur occur)
        {
            var boolQ = query as BooleanQuery;
            if (boolQ == null)
            {
                boolQuery.Add(new BooleanClause(query, occur));
                return;
            }
            var clauses = boolQ.GetClauses();
            if (clauses.Length == 0)
            {
                throw ParserError("Empty BooleanQuery");
            }
            if (clauses.Length > 1)
            {
                boolQuery.Add(new BooleanClause(query, occur));
                return;
            }

            //-- boolQ has one clause: combine occurs
            var clause = (BooleanClause)clauses[0];
            var clauseOccur = clause.GetOccur();
            BooleanClause.Occur effectiveOccur;
            if (Operator == DefaultOperator.Or)
            {
                // in    cl      eff
                // null  _  ==>  _
                // null  +  ==>  +
                // null  -  ==>  -
                //    _  _  ==>  _
                //    _  +  ==>  +
                //    _  -  ==>  -
                //    +  _  ==>  +
                //    +  +  ==>  +
                //    +  -  ==>  -
                //    -  _  ==>  -
                //    -  +  ==>  -
                //    -  -  ==>  -
                if (occur == null || occur == BooleanClause.Occur.SHOULD)
                    effectiveOccur = clauseOccur;
                else if (occur == BooleanClause.Occur.MUST_NOT)
                    effectiveOccur = occur;
                else if (clauseOccur == BooleanClause.Occur.MUST_NOT)
                    effectiveOccur = clauseOccur;
                else
                    effectiveOccur = occur;
            }
            else
            {
                // in    cl      eff
                // null  _  ==>  _
                // null  +  ==>  +
                // null  -  ==>  -
                //    _  _  ==>  _
                //    _  +  ==>  _
                //    _  -  ==>  -
                //    +  _  ==>  +
                //    +  +  ==>  +
                //    +  -  ==>  -
                //    -  _  ==>  -
                //    -  +  ==>  -
                //    -  -  ==>  -
                if (occur == null)
                    effectiveOccur = clauseOccur;
                else if (occur == BooleanClause.Occur.MUST_NOT)
                    effectiveOccur = occur;
                else if (clauseOccur == BooleanClause.Occur.MUST_NOT)
                    effectiveOccur = clauseOccur;
                else
                    effectiveOccur = occur;
            }
            clause.SetOccur(effectiveOccur);
            boolQuery.Add(clause);
        }
Esempio n. 25
0
            public virtual Explanation Explain(IndexReader reader, int doc)
            {
                Explanation sumExpl = new Explanation();

                sumExpl.SetDescription("sum of:");
                int   coord    = 0;
                int   maxCoord = 0;
                float sum      = 0.0f;

                for (int i = 0; i < weights.Count; i++)
                {
                    BooleanClause c = (BooleanClause)Enclosing_Instance.clauses[i];
                    Weight        w = (Weight)weights[i];
                    Explanation   e = w.Explain(reader, doc);
                    if (!c.IsProhibited())
                    {
                        maxCoord++;
                    }
                    if (e.GetValue() > 0)
                    {
                        if (!c.IsProhibited())
                        {
                            sumExpl.AddDetail(e);
                            sum += e.GetValue();
                            coord++;
                        }
                        else
                        {
                            return(new Explanation(0.0f, "match prohibited"));
                        }
                    }
                    else if (c.IsRequired())
                    {
                        return(new Explanation(0.0f, "match required"));
                    }
                }
                sumExpl.SetValue(sum);

                if (coord == 1)
                {
                    // only one clause matched
                    sumExpl = sumExpl.GetDetails()[0];                     // eliminate wrapper
                }
                float coordFactor = similarity.Coord(coord, maxCoord);

                if (coordFactor == 1.0f)
                {
                    // coord is no-op
                    return(sumExpl);
                }
                // eliminate wrapper
                else
                {
                    Explanation result = new Explanation();
                    result.SetDescription("product of:");
                    result.AddDetail(sumExpl);
                    result.AddDetail(new Explanation(coordFactor, "coord(" + coord + "/" + maxCoord + ")"));
                    result.SetValue(sum * coordFactor);
                    return(result);
                }
            }
Esempio n. 26
0
        protected virtual void SetOccurValue(IQueryBuilder inputQueryBuilder, ref BooleanClause.Occur occur)
        {
            if (occur != null)
            {
                return;
            }

            occur = inputQueryBuilder != null ? inputQueryBuilder.DefaultChildrenOccur : BooleanClause.Occur.MUST;
        }
Esempio n. 27
0
            public override Explanation Explain(AtomicReaderContext context, int doc)
            {
                int minShouldMatch         = outerInstance.MinimumNumberShouldMatch;
                ComplexExplanation sumExpl = new ComplexExplanation();

                sumExpl.Description = "sum of:";
                int   coord            = 0;
                float sum              = 0.0f;
                bool  fail             = false;
                int   shouldMatchCount = 0;

                using (IEnumerator <BooleanClause> cIter = outerInstance.clauses.GetEnumerator())
                {
                    foreach (Weight w in m_weights)
                    {
                        cIter.MoveNext();
                        BooleanClause c = cIter.Current;
                        if (w.GetScorer(context, context.AtomicReader.LiveDocs) == null)
                        {
                            if (c.IsRequired)
                            {
                                fail = true;
                                Explanation r = new Explanation(0.0f, "no match on required clause (" + c.Query.ToString() + ")");
                                sumExpl.AddDetail(r);
                            }
                            continue;
                        }
                        Explanation e = w.Explain(context, doc);
                        if (e.IsMatch)
                        {
                            if (!c.IsProhibited)
                            {
                                sumExpl.AddDetail(e);
                                sum += e.Value;
                                coord++;
                            }
                            else
                            {
                                Explanation r = new Explanation(0.0f, "match on prohibited clause (" + c.Query.ToString() + ")");
                                r.AddDetail(e);
                                sumExpl.AddDetail(r);
                                fail = true;
                            }
                            if (c.Occur == Occur_e.SHOULD)
                            {
                                shouldMatchCount++;
                            }
                        }
                        else if (c.IsRequired)
                        {
                            Explanation r = new Explanation(0.0f, "no match on required clause (" + c.Query.ToString() + ")");
                            r.AddDetail(e);
                            sumExpl.AddDetail(r);
                            fail = true;
                        }
                    }
                }
                if (fail)
                {
                    sumExpl.Match       = false;
                    sumExpl.Value       = 0.0f;
                    sumExpl.Description = "Failure to meet condition(s) of required/prohibited clause(s)";
                    return(sumExpl);
                }
                else if (shouldMatchCount < minShouldMatch)
                {
                    sumExpl.Match       = false;
                    sumExpl.Value       = 0.0f;
                    sumExpl.Description = "Failure to match minimum number " + "of optional clauses: " + minShouldMatch;
                    return(sumExpl);
                }

                sumExpl.Match = 0 < coord ? true : false;
                sumExpl.Value = sum;

                float coordFactor = disableCoord ? 1.0f : Coord(coord, m_maxCoord);

                if (coordFactor == 1.0f)
                {
                    return(sumExpl); // eliminate wrapper
                }
                else
                {
                    ComplexExplanation result = new ComplexExplanation(sumExpl.IsMatch, sum * coordFactor, "product of:");
                    result.AddDetail(sumExpl);
                    result.AddDetail(new Explanation(coordFactor, "coord(" + coord + "/" + m_maxCoord + ")"));
                    return(result);
                }
            }
Esempio n. 28
0
            public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
            {
                IList <Scorer> required           = new List <Scorer>();
                IList <Scorer> prohibited         = new List <Scorer>();
                IList <Scorer> optional           = new List <Scorer>();
                IEnumerator <BooleanClause> cIter = outerInstance.clauses.GetEnumerator();

                foreach (Weight w in m_weights)
                {
                    cIter.MoveNext();
                    BooleanClause c         = cIter.Current;
                    Scorer        subScorer = w.GetScorer(context, acceptDocs);
                    if (subScorer == null)
                    {
                        if (c.IsRequired)
                        {
                            return(null);
                        }
                    }
                    else if (c.IsRequired)
                    {
                        required.Add(subScorer);
                    }
                    else if (c.IsProhibited)
                    {
                        prohibited.Add(subScorer);
                    }
                    else
                    {
                        optional.Add(subScorer);
                    }
                }

                if (required.Count == 0 && optional.Count == 0)
                {
                    // no required and optional clauses.
                    return(null);
                }
                else if (optional.Count < outerInstance.m_minNrShouldMatch)
                {
                    // either >1 req scorer, or there are 0 req scorers and at least 1
                    // optional scorer. Therefore if there are not enough optional scorers
                    // no documents will be matched by the query
                    return(null);
                }

                // simple conjunction
                if (optional.Count == 0 && prohibited.Count == 0)
                {
                    float coord = disableCoord ? 1.0f : Coord(required.Count, m_maxCoord);
                    return(new ConjunctionScorer(this, required.ToArray(), coord));
                }

                // simple disjunction
                if (required.Count == 0 && prohibited.Count == 0 && outerInstance.m_minNrShouldMatch <= 1 && optional.Count > 1)
                {
                    var coord = new float[optional.Count + 1];
                    for (int i = 0; i < coord.Length; i++)
                    {
                        coord[i] = disableCoord ? 1.0f : Coord(i, m_maxCoord);
                    }
                    return(new DisjunctionSumScorer(this, optional.ToArray(), coord));
                }

                // Return a BooleanScorer2
                return(new BooleanScorer2(this, disableCoord, outerInstance.m_minNrShouldMatch, required, prohibited, optional, m_maxCoord));
            }
Esempio n. 29
0
            public override Explanation Explain(IndexReader reader, int doc)
            {
                int minShouldMatch         = Enclosing_Instance.GetMinimumNumberShouldMatch();
                ComplexExplanation sumExpl = new ComplexExplanation();

                sumExpl.SetDescription("sum of:");
                int   coord                       = 0;
                int   maxCoord                    = 0;
                float sum                         = 0.0f;
                bool  fail                        = false;
                int   shouldMatchCount            = 0;
                IEnumerator <BooleanClause> cIter = Enclosing_Instance.clauses.GetEnumerator();

                foreach (Weight w in weights)
                {
                    cIter.MoveNext();

                    BooleanClause c = cIter.Current;
                    if (w.Scorer(reader, true, true) == null)
                    {
                        continue;
                    }
                    Explanation e = w.Explain(reader, doc);
                    if (!c.IsProhibited())
                    {
                        maxCoord++;
                    }
                    if (e.IsMatch())
                    {
                        if (!c.IsProhibited())
                        {
                            sumExpl.AddDetail(e);
                            sum += e.GetValue();
                            coord++;
                        }
                        else
                        {
                            Explanation r = new Explanation(0.0f, "match on prohibited clause (" + c.GetQuery().ToString() + ")");
                            r.AddDetail(e);
                            sumExpl.AddDetail(r);
                            fail = true;
                        }
                        if (c.GetOccur() == Occur.SHOULD)
                        {
                            shouldMatchCount++;
                        }
                    }
                    else if (c.IsRequired())
                    {
                        Explanation r = new Explanation(0.0f, "no match on required clause (" + c.GetQuery().ToString() + ")");
                        r.AddDetail(e);
                        sumExpl.AddDetail(r);
                        fail = true;
                    }
                }
                if (fail)
                {
                    System.Boolean tempAux = false;
                    sumExpl.SetMatch(tempAux);
                    sumExpl.SetValue(0.0f);
                    sumExpl.SetDescription("Failure to meet condition(s) of required/prohibited clause(s)");
                    return(sumExpl);
                }
                else if (shouldMatchCount < minShouldMatch)
                {
                    System.Boolean tempAux2 = false;
                    sumExpl.SetMatch(tempAux2);
                    sumExpl.SetValue(0.0f);
                    sumExpl.SetDescription("Failure to match minimum number " + "of optional clauses: " + minShouldMatch);
                    return(sumExpl);
                }

                sumExpl.SetMatch(0 < coord?true:false);
                sumExpl.SetValue(sum);

                float coordFactor = similarity.Coord(coord, maxCoord);

                if (coordFactor == 1.0f)
                {
                    // coord is no-op
                    return(sumExpl);
                }
                // eliminate wrapper
                else
                {
                    ComplexExplanation result = new ComplexExplanation(sumExpl.IsMatch(), sum * coordFactor, "product of:");
                    result.AddDetail(sumExpl);
                    result.AddDetail(new Explanation(coordFactor, "coord(" + coord + "/" + maxCoord + ")"));
                    return(result);
                }
            }
Esempio n. 30
0
        /// <summary>Prints a user-readable version of this query. </summary>
        public override System.String ToString(System.String field)
        {
            System.Text.StringBuilder buffer = new System.Text.StringBuilder();
            bool needParens = (GetBoost() != 1.0) || (GetMinimumNumberShouldMatch() > 0);

            if (needParens)
            {
                buffer.Append("(");
            }

            for (int i = 0; i < clauses.Count; i++)
            {
                BooleanClause c = clauses[i];
                if (c.IsProhibited())
                {
                    buffer.Append("-");
                }
                else if (c.IsRequired())
                {
                    buffer.Append("+");
                }

                Query subQuery = c.GetQuery();
                if (subQuery != null)
                {
                    if (subQuery is BooleanQuery)
                    {
                        // wrap sub-bools in parens
                        buffer.Append("(");
                        buffer.Append(subQuery.ToString(field));
                        buffer.Append(")");
                    }
                    else
                    {
                        buffer.Append(subQuery.ToString(field));
                    }
                }
                else
                {
                    buffer.Append("null");
                }

                if (i != clauses.Count - 1)
                {
                    buffer.Append(" ");
                }
            }

            if (needParens)
            {
                buffer.Append(")");
            }

            if (GetMinimumNumberShouldMatch() > 0)
            {
                buffer.Append('~');
                buffer.Append(GetMinimumNumberShouldMatch());
            }

            if (GetBoost() != 1.0f)
            {
                buffer.Append(ToStringUtils.Boost(GetBoost()));
            }

            return(buffer.ToString());
        }
Esempio n. 31
0
 public override void Add(Search.Query query, BooleanClause.Occur occur)
 {
     throw new NotSupportedException();
 }
        public static Query BuildMultiFieldQuery(IEnumerable<MultiFieldSearchParam.Refinement> refinements, BooleanClause.Occur condition)
        {
            Assert.ArgumentNotNull(refinements, "Refinements");

            if (!refinements.Any())
            {
                return null;
            }

            if (refinements.Count() == 1)
            {
                return BuildFieldQuery(refinements.First().Name, refinements.First().Value);
            }

            var innerQuery = new BooleanQuery();
            foreach (var refinement in refinements)
            {
                innerQuery.Add(BuildFieldQuery(refinement.Name, refinement.Value), condition);
            }

            return innerQuery;
        }
Esempio n. 33
0
        /// <summary>
        /// Parses a query, searching on the fields specified. Use this if you need to
        /// specify certain fields as required, and others as prohibited.
        /// <para/>
        /// Usage:
        /// <code>
        /// string[] fields = {&quot;filename&quot;, &quot;contents&quot;, &quot;description&quot;};
        /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
        ///     BooleanClause.Occur.MUST,
        ///     BooleanClause.Occur.MUST_NOT};
        /// MultiFieldQueryParser.Parse(&quot;query&quot;, fields, flags, analyzer);
        /// </code>
        /// <para/>
        /// The code above would construct a query:
        /// <code>
        /// (filename:query) +(contents:query) -(description:query)
        /// </code>
        /// </summary>
        /// <param name="query">Query string to parse</param>
        /// <param name="fields">Fields to search on</param>
        /// <param name="flags">Flags describing the fields</param>
        /// <param name="analyzer">Analyzer to use</param>
        /// <exception cref="ArgumentException">
        /// if the length of the fields array differs from the length of the
        /// flags array
        /// </exception>
        public static Query Parse(string query, string[] fields,
            BooleanClause.Occur[] flags, Analyzer analyzer)
        {
            if (fields.Length != flags.Length)
                throw new ArgumentException("fields.length != flags.length");
            BooleanQuery bQuery = new BooleanQuery();

            StandardQueryParser qp = new StandardQueryParser();
            qp.Analyzer = analyzer;

            for (int i = 0; i < fields.Length; i++)
            {
                Query q = qp.Parse(query, fields[i]);

                if (q != null && // q never null, just being defensive
                    (!(q is BooleanQuery) || ((BooleanQuery)q).GetClauses().Count > 0))
                {
                    bQuery.Add(q, flags[i]);
                }
            }
            return bQuery;
        }
Esempio n. 34
0
 /// <summary>Adds a clause to a boolean query.
 /// 
 /// </summary>
 /// <throws>  TooManyClauses if the new number of clauses exceeds the maximum clause number </throws>
 /// <seealso cref="#GetMaxClauseCount()">
 /// </seealso>
 public virtual void Add(Query query, BooleanClause.Occur occur)
 {
     Add(new BooleanClause(query, occur));
 }
Esempio n. 35
0
        /// <summary>Adds a clause to a boolean query.</summary>
        /// <throws>  TooManyClauses if the new number of clauses exceeds the maximum clause number </throws>
        /// <seealso cref="#GetMaxClauseCount()">
        /// </seealso>
        public virtual void Add(BooleanClause clause)
        {
            if (clauses.Count >= maxClauseCount)
                throw new TooManyClauses();

            clauses.Add(clause);
        }
Esempio n. 36
0
            /// <returns> A good old 1.4 Scorer
            /// </returns>
            public virtual Scorer Scorer(IndexReader reader)
            {
                // First see if the (faster) ConjunctionScorer will work.  This can be
                // used when all clauses are required.  Also, at this point a
                // BooleanScorer cannot be embedded in a ConjunctionScorer, as the hits
                // from a BooleanScorer are not always sorted by document number (sigh)
                // and hence BooleanScorer cannot implement skipTo() correctly, which is
                // required by ConjunctionScorer.
                bool allRequired = true;
                bool noneBoolean = true;

                for (int i = 0; i < weights.Count; i++)
                {
                    BooleanClause c = (BooleanClause)Enclosing_Instance.clauses[i];
                    if (!c.IsRequired())
                    {
                        allRequired = false;
                    }
                    if (c.GetQuery() is BooleanQuery)
                    {
                        noneBoolean = false;
                    }
                }

                if (allRequired && noneBoolean)
                {
                    // ConjunctionScorer is okay
                    ConjunctionScorer result = new ConjunctionScorer(similarity);
                    for (int i = 0; i < weights.Count; i++)
                    {
                        Weight w         = (Weight)weights[i];
                        Scorer subScorer = w.Scorer(reader);
                        if (subScorer == null)
                        {
                            return(null);
                        }
                        result.Add(subScorer);
                    }
                    return(result);
                }

                // Use good-old BooleanScorer instead.
                BooleanScorer result2 = new BooleanScorer(similarity);

                for (int i = 0; i < weights.Count; i++)
                {
                    BooleanClause c         = (BooleanClause)Enclosing_Instance.clauses[i];
                    Weight        w         = (Weight)weights[i];
                    Scorer        subScorer = w.Scorer(reader);
                    if (subScorer != null)
                    {
                        result2.Add(subScorer, c.IsRequired(), c.IsProhibited());
                    }
                    else if (c.IsRequired())
                    {
                        return(null);
                    }
                }

                return(result2);
            }