本文整理汇总了C#中Lucene.Net.Search.BooleanQuery.Add方法的典型用法代码示例。如果您正苦于以下问题:C# BooleanQuery.Add方法的具体用法?C# BooleanQuery.Add怎么用?C# BooleanQuery.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Lucene.Net.Search.BooleanQuery
的用法示例。
在下文中一共展示了BooleanQuery.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Get
public List<int> Get(Query searchQuery)
{
var indexSearcher = _productSearcher.IndexSearcher;
var name = FieldDefinition.GetFieldName<ProductSearchCategoriesDefinition>();
var valueCollector = new ValueCollector(indexSearcher, name);
indexSearcher.Search(searchQuery, valueCollector);
var categoryIds = valueCollector.Values[name].Select(s => Convert.ToInt32(s)).Distinct().ToList();
if (!categoryIds.Any())
return categoryIds;
var mainQuery = new BooleanQuery();
var idsQuery = new BooleanQuery();
const string idFieldName = "id";
foreach (var categoryId in categoryIds)
{
idsQuery.Add(new TermQuery(new Term(idFieldName, categoryId.ToString())), Occur.SHOULD);
}
mainQuery.Add(idsQuery, Occur.MUST);
var publishedOn = FieldDefinition.GetFieldName<PublishedOnFieldDefinition>();
mainQuery.Add(new TermRangeQuery(
publishedOn, null,
DateTools.DateToString(CurrentRequestData.Now, DateTools.Resolution.SECOND), false, true), Occur.MUST);
var webpageSearcher = _indexSearcher.IndexSearcher;
var webpageValueCollector = new ValueCollector(webpageSearcher, idFieldName);
webpageSearcher.Search(mainQuery, null, webpageValueCollector);
return webpageValueCollector.Values[idFieldName].Select(s => Convert.ToInt32(s))
.Intersect(categoryIds)
.ToList();
}
示例2: TestMethod
public virtual void TestMethod()
{
RAMDirectory directory = new RAMDirectory();
System.String[] values = new System.String[]{"1", "2", "3", "4"};
try
{
IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true);
for (int i = 0; i < values.Length; i++)
{
Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();
doc.Add(new Field(FIELD, values[i], Field.Store.YES, Field.Index.UN_TOKENIZED));
writer.AddDocument(doc);
}
writer.Close();
BooleanQuery booleanQuery1 = new BooleanQuery();
booleanQuery1.Add(new TermQuery(new Term(FIELD, "1")), BooleanClause.Occur.SHOULD);
booleanQuery1.Add(new TermQuery(new Term(FIELD, "2")), BooleanClause.Occur.SHOULD);
BooleanQuery query = new BooleanQuery();
query.Add(booleanQuery1, BooleanClause.Occur.MUST);
query.Add(new TermQuery(new Term(FIELD, "9")), BooleanClause.Occur.MUST_NOT);
IndexSearcher indexSearcher = new IndexSearcher(directory);
Hits hits = indexSearcher.Search(query);
Assert.AreEqual(2, hits.Length(), "Number of matched documents");
}
catch (System.IO.IOException e)
{
Assert.Fail(e.Message);
}
}
示例3: TestBQ14
public virtual void TestBQ14()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), BooleanClause.Occur.SHOULD);
q.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
Qtest(q, new int[] { 0, 1, 2, 3 });
}
示例4: TestAsterisk
public virtual void TestAsterisk()
{
Directory indexStore = GetIndexStore("body", new string[] { "metal", "metals" });
IndexReader reader = DirectoryReader.Open(indexStore);
IndexSearcher searcher = NewSearcher(reader);
Query query1 = new TermQuery(new Term("body", "metal"));
Query query2 = new WildcardQuery(new Term("body", "metal*"));
Query query3 = new WildcardQuery(new Term("body", "m*tal"));
Query query4 = new WildcardQuery(new Term("body", "m*tal*"));
Query query5 = new WildcardQuery(new Term("body", "m*tals"));
BooleanQuery query6 = new BooleanQuery();
query6.Add(query5, BooleanClause.Occur.SHOULD);
BooleanQuery query7 = new BooleanQuery();
query7.Add(query3, BooleanClause.Occur.SHOULD);
query7.Add(query5, BooleanClause.Occur.SHOULD);
// Queries do not automatically lower-case search terms:
Query query8 = new WildcardQuery(new Term("body", "M*tal*"));
AssertMatches(searcher, query1, 1);
AssertMatches(searcher, query2, 2);
AssertMatches(searcher, query3, 1);
AssertMatches(searcher, query4, 2);
AssertMatches(searcher, query5, 1);
AssertMatches(searcher, query6, 1);
AssertMatches(searcher, query7, 2);
AssertMatches(searcher, query8, 0);
AssertMatches(searcher, new WildcardQuery(new Term("body", "*tall")), 0);
AssertMatches(searcher, new WildcardQuery(new Term("body", "*tal")), 1);
AssertMatches(searcher, new WildcardQuery(new Term("body", "*tal*")), 2);
reader.Dispose();
indexStore.Dispose();
}
示例5: FilterQueryByClasses
public static Lucene.Net.Search.Query FilterQueryByClasses(IESI.ISet<System.Type> classesAndSubclasses, Lucene.Net.Search.Query luceneQuery)
{
// A query filter is more practical than a manual class filtering post query (esp on scrollable resultsets)
// it also probably minimise the memory footprint
if (classesAndSubclasses == null)
{
return luceneQuery;
}
BooleanQuery classFilter = new BooleanQuery();
// annihilate the scoring impact of DocumentBuilder.CLASS_FIELDNAME
classFilter.SetBoost(0);
foreach (System.Type clazz in classesAndSubclasses)
{
Term t = new Term(DocumentBuilder.CLASS_FIELDNAME, TypeHelper.LuceneTypeName(clazz));
TermQuery termQuery = new TermQuery(t);
classFilter.Add(termQuery, BooleanClause.Occur.SHOULD);
}
BooleanQuery filteredQuery = new BooleanQuery();
filteredQuery.Add(luceneQuery, BooleanClause.Occur.MUST);
filteredQuery.Add(classFilter, BooleanClause.Occur.MUST);
return filteredQuery;
}
示例6: HandleRangeFacet
private void HandleRangeFacet(string index, Facet facet, IndexQuery indexQuery, IndexSearcher currentIndexSearcher, Dictionary<string, IEnumerable<FacetValue>> results)
{
var rangeResults = new List<FacetValue>();
foreach (var range in facet.Ranges)
{
var baseQuery = database.IndexStorage.GetLuceneQuery(index, indexQuery, database.IndexQueryTriggers);
//TODO the built-in parser can't handle [NULL TO 100.0}, i.e. a mix of [ and }
//so we need to handle this ourselves (greater and less-than-or-equal)
var rangeQuery = database.IndexStorage.GetLuceneQuery(index, new IndexQuery
{
Query = facet.Name + ":" + range
}, database.IndexQueryTriggers);
var joinedQuery = new BooleanQuery();
joinedQuery.Add(baseQuery, BooleanClause.Occur.MUST);
joinedQuery.Add(rangeQuery, BooleanClause.Occur.MUST);
var topDocs = currentIndexSearcher.Search(joinedQuery, null, 1);
if (topDocs.TotalHits > 0)
{
rangeResults.Add(new FacetValue
{
Count = topDocs.TotalHits,
Range = range
});
}
}
results[facet.Name] = rangeResults;
}
示例7: GetQuery
public Query GetQuery()
{
if (String.IsNullOrWhiteSpace(Term) && String.IsNullOrWhiteSpace(Type) && !CreatedOnTo.HasValue && !CreatedOnFrom.HasValue && Parent == null)
return new MatchAllDocsQuery();
var booleanQuery = new BooleanQuery();
if (!String.IsNullOrWhiteSpace(Term))
{
var indexDefinition = IndexingHelper.Get<AdminWebpageIndexDefinition>();
var analyser = indexDefinition.GetAnalyser();
var parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, indexDefinition.SearchableFieldNames, analyser);
Query query = Term.SafeGetSearchQuery(parser, analyser);
booleanQuery.Add(query, Occur.MUST);
}
if (CreatedOnFrom.HasValue || CreatedOnTo.HasValue)
booleanQuery.Add(GetDateQuery(), Occur.MUST);
if (!string.IsNullOrEmpty(Type))
booleanQuery.Add(new TermQuery(new Term(FieldDefinition.GetFieldName<TypeFieldDefinition>(), Type)),
Occur.MUST);
if (Parent != null)
booleanQuery.Add(
new TermQuery(new Term(FieldDefinition.GetFieldName<ParentIdFieldDefinition>(), Parent.Id.ToString())), Occur.MUST);
return booleanQuery;
}
示例8: TestNullOrSubScorer
public virtual void TestNullOrSubScorer()
{
Directory dir = new MockRAMDirectory();
IndexWriter w = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
Document doc = new Document();
doc.Add(new Field("field", "a b c d", Field.Store.NO, Field.Index.ANALYZED));
w.AddDocument(doc);
IndexReader r = w.GetReader();
IndexSearcher s = new IndexSearcher(r);
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("field", "a")), Occur.SHOULD);
// LUCENE-2617: make sure that a term not in the index still contributes to the score via coord factor
float score = s.Search(q, 10).MaxScore;
Query subQuery = new TermQuery(new Term("field", "not_in_index"));
subQuery.Boost = 0;
q.Add(subQuery, Occur.SHOULD);
float score2 = s.Search(q, 10).MaxScore;
Assert.AreEqual(score * .5, score2, 1e-6);
// LUCENE-2617: make sure that a clause not in the index still contributes to the score via coord factor
BooleanQuery qq = (BooleanQuery)q.Clone();
PhraseQuery phrase = new PhraseQuery();
phrase.Add(new Term("field", "not_in_index"));
phrase.Add(new Term("field", "another_not_in_index"));
phrase.Boost = 0;
qq.Add(phrase, Occur.SHOULD);
score2 = s.Search(qq, 10).MaxScore;
Assert.AreEqual(score * (1.0 / 3), score2, 1e-6);
// now test BooleanScorer2
subQuery = new TermQuery(new Term("field", "b"));
subQuery.Boost = 0;
q.Add(subQuery, Occur.MUST);
score2 = s.Search(q, 10).MaxScore;
Assert.AreEqual(score * (2.0 / 3), score2, 1e-6);
// PhraseQuery w/ no terms added returns a null scorer
PhraseQuery pq = new PhraseQuery();
q.Add(pq, Occur.SHOULD);
Assert.AreEqual(1, s.Search(q, 10).TotalHits);
// A required clause which returns null scorer should return null scorer to
// IndexSearcher.
q = new BooleanQuery();
pq = new PhraseQuery();
q.Add(new TermQuery(new Term("field", "a")), Occur.SHOULD);
q.Add(pq, Occur.MUST);
Assert.AreEqual(0, s.Search(q, 10).TotalHits);
DisjunctionMaxQuery dmq = new DisjunctionMaxQuery(1.0f);
dmq.Add(new TermQuery(new Term("field", "a")));
dmq.Add(pq);
Assert.AreEqual(1, s.Search(dmq, 10).TotalHits);
r.Close();
w.Close();
dir.Close();
}
示例9: Cache
public void Cache()
{
CreateData();
IFullTextSession s = Search.CreateFullTextSession(OpenSession());
s.Transaction.Begin();
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term("teacher", "andre")), BooleanClause.Occur.SHOULD);
query.Add(new TermQuery(new Term("teacher", "max")), BooleanClause.Occur.SHOULD);
query.Add(new TermQuery(new Term("teacher", "aaron")), BooleanClause.Occur.SHOULD);
IFullTextQuery ftQuery = s.CreateFullTextQuery(query, typeof(Driver));
Assert.AreEqual(3, ftQuery.ResultSize, "No filter should happen");
ftQuery = s.CreateFullTextQuery(query, typeof(Driver));
ftQuery.EnableFullTextFilter("cachetest");
Assert.AreEqual(0, ftQuery.ResultSize, "Should filter out all");
ftQuery = s.CreateFullTextQuery(query, typeof(Driver));
ftQuery.EnableFullTextFilter("cachetest");
try
{
int i = ftQuery.ResultSize;
}
catch (NotSupportedException)
{
Assert.Fail("Cache does not work");
}
s.Transaction.Commit();
s.Close();
DeleteData();
}
示例10: TestBasic
public virtual void TestBasic()
{
Directory dir = new RAMDirectory();
IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
Document doc = new Document();
doc.Add(new Field("field", "value", Field.Store.NO, Field.Index.ANALYZED));
writer.AddDocument(doc);
writer.Close();
TermQuery termQuery = new TermQuery(new Term("field", "value"));
// should not throw exception with primitive query
QueryWrapperFilter qwf = new QueryWrapperFilter(termQuery);
IndexSearcher searcher = new IndexSearcher(dir, true);
TopDocs hits = searcher.Search(new MatchAllDocsQuery(), qwf, 10);
Assert.AreEqual(1, hits.totalHits);
// should not throw exception with complex primitive query
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(termQuery, Occur.MUST);
booleanQuery.Add(new TermQuery(new Term("field", "missing")), Occur.MUST_NOT);
qwf = new QueryWrapperFilter(termQuery);
hits = searcher.Search(new MatchAllDocsQuery(), qwf, 10);
Assert.AreEqual(1, hits.totalHits);
// should not throw exception with non primitive Query (doesn't implement
// Query#createWeight)
qwf = new QueryWrapperFilter(new FuzzyQuery(new Term("field", "valu")));
hits = searcher.Search(new MatchAllDocsQuery(), qwf, 10);
Assert.AreEqual(1, hits.totalHits);
}
示例11: TestQueries
public virtual void TestQueries()
{
Single_Renamed = Single(Random());
Parallel_Renamed = Parallel(Random());
QueryTest(new TermQuery(new Term("f1", "v1")));
QueryTest(new TermQuery(new Term("f1", "v2")));
QueryTest(new TermQuery(new Term("f2", "v1")));
QueryTest(new TermQuery(new Term("f2", "v2")));
QueryTest(new TermQuery(new Term("f3", "v1")));
QueryTest(new TermQuery(new Term("f3", "v2")));
QueryTest(new TermQuery(new Term("f4", "v1")));
QueryTest(new TermQuery(new Term("f4", "v2")));
BooleanQuery bq1 = new BooleanQuery();
bq1.Add(new TermQuery(new Term("f1", "v1")), Occur.MUST);
bq1.Add(new TermQuery(new Term("f4", "v1")), Occur.MUST);
QueryTest(bq1);
Single_Renamed.IndexReader.Dispose();
Single_Renamed = null;
Parallel_Renamed.IndexReader.Dispose();
Parallel_Renamed = null;
Dir.Dispose();
Dir = null;
Dir1.Dispose();
Dir1 = null;
Dir2.Dispose();
Dir2 = null;
}
示例12: VisitWithinRadius
protected virtual Lucene.Net.Search.Query VisitWithinRadius(WithinRadiusNode node, LuceneQueryMapperState mappingState)
{
SpatialContext ctx = SpatialContext.GEO;
var strategy = new PointVectorStrategy(ctx, Sitecore.ContentSearch.Spatial.Common.Constants.LocationFieldName);
if (node.Latitude is double && node.Longitude is double && node.Radius is double)
{
var distance = DistanceUtils.Dist2Degrees((double)node.Radius, DistanceUtils.EARTH_MEAN_RADIUS_MI);
Circle circle = ctx.MakeCircle((double)node.Longitude,(double)node.Latitude, distance);
var spatialArgs = new SpatialArgs(SpatialOperation.IsWithin, circle);
var dq = strategy.MakeQuery(spatialArgs);
DistanceReverseValueSource valueSource = new DistanceReverseValueSource(strategy, circle.GetCenter(), distance);
ValueSourceFilter vsf = new ValueSourceFilter(new QueryWrapperFilter(dq), valueSource, 0, distance);
var filteredSpatial = new FilteredQuery(new MatchAllDocsQuery(), vsf);
mappingState.FilterQuery = filteredSpatial;
Lucene.Net.Search.Query spatialRankingQuery = new FunctionQuery(valueSource);
Random r = new Random(DateTime.Now.Millisecond);
var randomNumber = r.Next(10000101,11000101);
Lucene.Net.Search.Query dummyQuery = Lucene.Net.Search.NumericRangeQuery.NewIntRange("__smallcreateddate", randomNumber, Int32.Parse(DateTime.Now.ToString("yyyyMMdd")), true, true);
BooleanQuery bq = new BooleanQuery();
bq.Add(filteredSpatial, Occur.MUST);
bq.Add(spatialRankingQuery, Occur.MUST);
bq.Add(dummyQuery, Occur.SHOULD);
return bq;
}
throw new NotSupportedException("Wrong parameters type, Radius, latitude and longitude must be of type double");
}
示例13: GetQuery
public Query GetQuery()
{
var booleanQuery = new BooleanQuery
{
{
new TermRangeQuery(
FieldDefinition.GetFieldName<PublishedOnFieldDefinition>(), null,
DateTools.DateToString(CurrentRequestData.Now, DateTools.Resolution.SECOND), false, true),
Occur.MUST
}
};
if (!String.IsNullOrWhiteSpace(Term))
{
var indexDefinition = IndexingHelper.Get<WebpageSearchIndexDefinition>();
var analyser = indexDefinition.GetAnalyser();
var parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, indexDefinition.SearchableFieldNames, analyser);
Query query = Term.SafeGetSearchQuery(parser, analyser);
booleanQuery.Add(query, Occur.MUST);
}
if (CreatedOnFrom.HasValue || CreatedOnTo.HasValue)
booleanQuery.Add(GetDateQuery(), Occur.MUST);
if (!string.IsNullOrEmpty(Type))
booleanQuery.Add(new TermQuery(new Term(FieldDefinition.GetFieldName<TypeFieldDefinition>(), Type)),
Occur.MUST);
if (Parent != null)
booleanQuery.Add(
new TermQuery(new Term(FieldDefinition.GetFieldName<ParentIdFieldDefinition>(), Parent.Id.ToString())), Occur.MUST);
return booleanQuery;
}
示例14: Find
/// <summary>
/// Searches the index.
/// </summary>
/// <param name="queryText"></param>
/// <param name="categoryNames"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="roleIds"></param>
/// <returns></returns>
public SearchResultCollection Find(string queryText, IList<string> categoryNames, int pageIndex, int pageSize, IEnumerable<int> roleIds)
{
long startTicks = DateTime.Now.Ticks;
// the overall-query
BooleanQuery query = new BooleanQuery();
// add our parsed query
if (!String.IsNullOrEmpty(queryText))
{
Query multiQuery = MultiFieldQueryParser.Parse(new[] { queryText, queryText, queryText }, new[] { "title", "summary", "contents" }, new StandardAnalyzer());
query.Add(multiQuery, BooleanClause.Occur.MUST);
}
// add the security constraint - must be satisfied
query.Add(this.BuildSecurityQuery(roleIds), BooleanClause.Occur.MUST);
// Add the category query (if available)
if (categoryNames != null)
{
query.Add(this.BuildCategoryQuery(categoryNames), BooleanClause.Occur.MUST);
}
IndexSearcher searcher = new IndexSearcher(this._indexDirectory);
Hits hits = searcher.Search(query);
int start = pageIndex * pageSize;
int end = (pageIndex + 1) * pageSize;
if (hits.Length() <= end)
{
end = hits.Length();
}
SearchResultCollection results = new SearchResultCollection(end);
results.TotalCount = hits.Length();
results.PageIndex = pageIndex;
for (int i = start; i < end; i++)
{
SearchResult result = new SearchResult();
result.Title = hits.Doc(i).Get("title");
result.Summary = hits.Doc(i).Get("summary");
result.Author = hits.Doc(i).Get("author");
result.ModuleType = hits.Doc(i).Get("moduletype");
result.Path = hits.Doc(i).Get("path");
string[] categories = hits.Doc(i).GetValues("category");
result.Category = categories != null ? String.Join(", ", categories) : String.Empty;
//Caused 'String was not recognized as a valid DateTime.' when site culture was set
//to Africa (and maybe others: "z" Custom Format Specifier)
//See: http://stackoverflow.com/questions/284775/how-do-i-parse-and-convert-datetimes-to-the-rfc-822-date-time-format
result.DateCreated = Rfc822DateTime.Parse(hits.Doc(i).Get("datecreated")).ToLocalTime();
//result.DateCreated = DateTime.Parse((hits.Doc(i).Get("datecreated")));
result.Score = hits.Score(i);
result.Boost = hits.Doc(i).GetBoost();
result.SectionId = Int32.Parse(hits.Doc(i).Get("sectionid"));
results.Add(result);
}
searcher.Close();
results.ExecutionTime = DateTime.Now.Ticks - startTicks;
return results;
}
示例15: TestMethod
public virtual void TestMethod()
{
Directory directory = NewDirectory();
string[] values = new string[] { "1", "2", "3", "4" };
RandomIndexWriter writer = new RandomIndexWriter(Random(), directory, Similarity, TimeZone);
for (int i = 0; i < values.Length; i++)
{
Document doc = new Document();
doc.Add(NewStringField(FIELD, values[i], Field.Store.YES));
writer.AddDocument(doc);
}
IndexReader ir = writer.Reader;
writer.Dispose();
BooleanQuery booleanQuery1 = new BooleanQuery();
booleanQuery1.Add(new TermQuery(new Term(FIELD, "1")), BooleanClause.Occur.SHOULD);
booleanQuery1.Add(new TermQuery(new Term(FIELD, "2")), BooleanClause.Occur.SHOULD);
BooleanQuery query = new BooleanQuery();
query.Add(booleanQuery1, BooleanClause.Occur.MUST);
query.Add(new TermQuery(new Term(FIELD, "9")), BooleanClause.Occur.MUST_NOT);
IndexSearcher indexSearcher = NewSearcher(ir);
ScoreDoc[] hits = indexSearcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length, "Number of matched documents");
ir.Dispose();
directory.Dispose();
}