You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucenenet.apache.org by pa...@apache.org on 2026/04/17 02:21:42 UTC
(lucenenet) branch master updated: BREAKING: Add cancellation support to IndexSearcher, #922 (#1080)
This is an automated email from the ASF dual-hosted git repository.
paulirwin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/lucenenet.git
The following commit(s) were added to refs/heads/master by this push:
new 57e0b8c45 BREAKING: Add cancellation support to IndexSearcher, #922 (#1080)
57e0b8c45 is described below
commit 57e0b8c45b8c812b3164f8d6a7eb0347a343cae4
Author: Paul Irwin <pa...@gmail.com>
AuthorDate: Thu Apr 16 20:21:37 2026 -0600
BREAKING: Add cancellation support to IndexSearcher, #922 (#1080)
* Add CancellationToken parameter to IndexSearcher methods, #922
* Pass cancellation token and throw if requested, #922
* Pass cancellation token further down in multithreaded code, #922
* PR feedback
* Apply suggestions from code review
Co-authored-by: Copilot <17...@users.noreply.github.com>
* Add unit tests for cancellation support
---------
Co-authored-by: Copilot <17...@users.noreply.github.com>
---
src/Lucene.Net.Grouping/package.md | 2 +-
.../Index/Sorter/BlockJoinComparatorSource.cs | 3 +-
.../Search/AssertingIndexSearcher.cs | 5 +-
src/Lucene.Net.TestFramework/Search/CheckHits.cs | 17 +-
.../Search/ShardSearchingTestBase.cs | 35 +--
src/Lucene.Net.Tests/Search/TestBooleanQuery.cs | 5 +-
.../Search/TestCustomSearcherSort.cs | 9 +-
src/Lucene.Net.Tests/Search/TestIndexSearcher.cs | 319 +++++++++++++++++++++
.../Search/CollectionTerminatedException.cs | 3 +-
src/Lucene.Net/Search/FieldComparator.cs | 22 +-
src/Lucene.Net/Search/FieldDoc.cs | 3 +-
src/Lucene.Net/Search/FieldValueHitQueue.cs | 5 +-
src/Lucene.Net/Search/IndexSearcher.cs | 162 +++++++----
src/Lucene.Net/Search/Sort.cs | 5 +-
src/Lucene.Net/Search/TopDocs.cs | 5 +-
src/Lucene.Net/Search/TopFieldDocs.cs | 3 +-
src/Lucene.Net/Search/package.md | 2 +-
.../Threading/TaskSchedulerCompletionService.cs | 5 +-
src/Lucene.Net/overview.md | 2 +-
19 files changed, 493 insertions(+), 119 deletions(-)
diff --git a/src/Lucene.Net.Grouping/package.md b/src/Lucene.Net.Grouping/package.md
index 22d2ab8dc..5eaf07e50 100644
--- a/src/Lucene.Net.Grouping/package.md
+++ b/src/Lucene.Net.Grouping/package.md
@@ -166,4 +166,4 @@ int maxDoc = s.MaxDoc;
FixedBitSet groupHeadsBitSet = c.RetrieveGroupHeads(maxDoc);
```
-For each of the above collector types there is also a variant that works with `ValueSource` instead of of fields. Concretely this means that these variants can work with functions. These variants are slower than there term based counter parts. These implementations are located in the `Lucene.Net.Search.Grouping.Function` package, but can also be used with the `GroupingSearch` convenience utility
+For each of the above collector types there is also a variant that works with `ValueSource` instead of fields. Concretely, this means that these variants can work with functions. These variants are slower than their term-based counterparts. These implementations are located in the `Lucene.Net.Search.Grouping.Function` package, but can also be used with the `GroupingSearch` convenience utility.
diff --git a/src/Lucene.Net.Misc/Index/Sorter/BlockJoinComparatorSource.cs b/src/Lucene.Net.Misc/Index/Sorter/BlockJoinComparatorSource.cs
index cf0cd9622..28e70effd 100644
--- a/src/Lucene.Net.Misc/Index/Sorter/BlockJoinComparatorSource.cs
+++ b/src/Lucene.Net.Misc/Index/Sorter/BlockJoinComparatorSource.cs
@@ -2,6 +2,7 @@
using Lucene.Net.Util;
using System;
using System.IO;
+using System.Threading;
namespace Lucene.Net.Index.Sorter
{
@@ -28,7 +29,7 @@ namespace Lucene.Net.Index.Sorter
/// Note that this class is intended to used with <see cref="SortingMergePolicy"/>,
/// and for other purposes has some limitations:
/// <list type="bullet">
- /// <item><description>Cannot yet be used with <see cref="IndexSearcher.SearchAfter(ScoreDoc, Query, Filter, int, Sort)">
+ /// <item><description>Cannot yet be used with <see cref="IndexSearcher.SearchAfter(ScoreDoc, Query, Filter, int, Sort, CancellationToken)">
/// IndexSearcher.SearchAfter</see></description></item>
/// <item><description>Filling sort field values is not yet supported.</description></item>
/// </list>
diff --git a/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs b/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
index 9996afa1d..a242b0083 100644
--- a/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
+++ b/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
@@ -3,6 +3,7 @@
using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
+using System.Threading;
using System.Threading.Tasks;
namespace Lucene.Net.Search
@@ -100,10 +101,10 @@ protected override Query WrapFilter(Query query, Filter filter)
return (filter is null) ? query : new FilteredQuery(query, filter, TestUtil.RandomFilterStrategy(random));
}
- protected override void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector)
+ protected override void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector, CancellationToken cancellationToken = default)
{
// TODO: shouldn't we AssertingCollector.wrap(collector) here?
- base.Search(leaves, AssertingWeight.Wrap(random, weight), collector);
+ base.Search(leaves, AssertingWeight.Wrap(random, weight), collector, cancellationToken);
}
public override string ToString()
diff --git a/src/Lucene.Net.TestFramework/Search/CheckHits.cs b/src/Lucene.Net.TestFramework/Search/CheckHits.cs
index 02b619f36..b27501015 100644
--- a/src/Lucene.Net.TestFramework/Search/CheckHits.cs
+++ b/src/Lucene.Net.TestFramework/Search/CheckHits.cs
@@ -5,6 +5,7 @@
using System.Diagnostics;
using System.Globalization;
using System.Text;
+using System.Threading;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
@@ -450,28 +451,28 @@ protected virtual void CheckExplanations(Query q)
base.Search(q, null, new ExplanationAsserter(q, null, this));
}
- public override TopFieldDocs Search(Query query, Filter filter, int n, Sort sort)
+ public override TopFieldDocs Search(Query query, Filter filter, int n, Sort sort, CancellationToken cancellationToken = default)
{
CheckExplanations(query);
- return base.Search(query, filter, n, sort);
+ return base.Search(query, filter, n, sort, cancellationToken);
}
- public override void Search(Query query, ICollector results)
+ public override void Search(Query query, ICollector results, CancellationToken cancellationToken = default)
{
CheckExplanations(query);
- base.Search(query, results);
+ base.Search(query, results, cancellationToken);
}
- public override void Search(Query query, Filter filter, ICollector results)
+ public override void Search(Query query, Filter filter, ICollector results, CancellationToken cancellationToken = default)
{
CheckExplanations(query);
- base.Search(query, filter, results);
+ base.Search(query, filter, results, cancellationToken);
}
- public override TopDocs Search(Query query, Filter filter, int n)
+ public override TopDocs Search(Query query, Filter filter, int n, CancellationToken cancellationToken = default)
{
CheckExplanations(query);
- return base.Search(query, filter, n);
+ return base.Search(query, filter, n, cancellationToken);
}
}
diff --git a/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs b/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
index 14fd43f7a..b0352d2c7 100644
--- a/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
+++ b/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
@@ -11,6 +11,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
+using System.Threading;
using JCG = J2N.Collections.Generic;
#if FEATURE_SERIALIZABLE_EXCEPTIONS
using System.ComponentModel;
@@ -192,7 +193,7 @@ internal virtual void BroadcastNodeReopen(int nodeID, long version, IndexSearche
// MOCK: in a real env you have to hit the wire
// (send this query to all remote nodes
// concurrently):
- internal virtual TopDocs SearchNode(int nodeID, long[] nodeVersions, Query q, Sort sort, int numHits, ScoreDoc searchAfter)
+ internal virtual TopDocs SearchNode(int nodeID, long[] nodeVersions, Query q, Sort sort, int numHits, ScoreDoc searchAfter, CancellationToken cancellationToken = default)
{
NodeState.ShardIndexSearcher s = m_nodes[nodeID].Acquire(nodeVersions);
try
@@ -201,17 +202,17 @@ internal virtual TopDocs SearchNode(int nodeID, long[] nodeVersions, Query q, So
{
if (searchAfter != null)
{
- return s.LocalSearchAfter(searchAfter, q, numHits);
+ return s.LocalSearchAfter(searchAfter, q, numHits, cancellationToken);
}
else
{
- return s.LocalSearch(q, numHits);
+ return s.LocalSearch(q, numHits, cancellationToken);
}
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(searchAfter is null); // not supported yet
- return s.LocalSearch(q, numHits, sort);
+ return s.LocalSearch(q, numHits, sort, cancellationToken);
}
}
finally
@@ -448,7 +449,7 @@ public override CollectionStatistics CollectionStatistics(string field)
return new CollectionStatistics(field, maxDoc, docCount, sumTotalTermFreq, sumDocFreq);
}
- public override TopDocs Search(Query query, int numHits)
+ public override TopDocs Search(Query query, int numHits, CancellationToken cancellationToken = default)
{
TopDocs[] shardHits = new TopDocs[nodeVersions.Length];
for (int nodeID = 0; nodeID < nodeVersions.Length; nodeID++)
@@ -457,7 +458,7 @@ public override TopDocs Search(Query query, int numHits)
{
// My node; run using local shard searcher we
// already aquired:
- shardHits[nodeID] = LocalSearch(query, numHits);
+ shardHits[nodeID] = LocalSearch(query, numHits, cancellationToken);
}
else
{
@@ -469,12 +470,12 @@ public override TopDocs Search(Query query, int numHits)
return TopDocs.Merge(null, numHits, shardHits);
}
- public virtual TopDocs LocalSearch(Query query, int numHits)
+ public virtual TopDocs LocalSearch(Query query, int numHits, CancellationToken cancellationToken = default)
{
- return base.Search(query, numHits);
+ return base.Search(query, numHits, cancellationToken);
}
- public override TopDocs SearchAfter(ScoreDoc after, Query query, int numHits)
+ public override TopDocs SearchAfter(ScoreDoc after, Query query, int numHits, CancellationToken cancellationToken = default)
{
TopDocs[] shardHits = new TopDocs[nodeVersions.Length];
// results are merged in that order: score, shardIndex, doc. therefore we set
@@ -521,7 +522,7 @@ public override TopDocs SearchAfter(ScoreDoc after, Query query, int numHits)
{
// My node; run using local shard searcher we
// already aquired:
- shardHits[nodeID] = LocalSearchAfter(shardAfter, query, numHits);
+ shardHits[nodeID] = LocalSearchAfter(shardAfter, query, numHits, cancellationToken);
}
else
{
@@ -534,12 +535,12 @@ public override TopDocs SearchAfter(ScoreDoc after, Query query, int numHits)
return TopDocs.Merge(null, numHits, shardHits);
}
- public virtual TopDocs LocalSearchAfter(ScoreDoc after, Query query, int numHits)
+ public virtual TopDocs LocalSearchAfter(ScoreDoc after, Query query, int numHits, CancellationToken cancellationToken = default)
{
- return base.SearchAfter(after, query, numHits);
+ return base.SearchAfter(after, query, numHits, cancellationToken);
}
- public override TopFieldDocs Search(Query query, int numHits, Sort sort)
+ public override TopFieldDocs Search(Query query, int numHits, Sort sort, CancellationToken cancellationToken = default)
{
if (Debugging.AssertsEnabled) Debugging.Assert(sort != null);
TopDocs[] shardHits = new TopDocs[nodeVersions.Length];
@@ -549,11 +550,11 @@ public override TopFieldDocs Search(Query query, int numHits, Sort sort)
{
// My node; run using local shard searcher we
// already aquired:
- shardHits[nodeID] = LocalSearch(query, numHits, sort);
+ shardHits[nodeID] = LocalSearch(query, numHits, sort, cancellationToken);
}
else
{
- shardHits[nodeID] = outerInstance.outerInstance.SearchNode(nodeID, nodeVersions, query, sort, numHits, null);
+ shardHits[nodeID] = outerInstance.outerInstance.SearchNode(nodeID, nodeVersions, query, sort, numHits, null, cancellationToken);
}
}
@@ -561,9 +562,9 @@ public override TopFieldDocs Search(Query query, int numHits, Sort sort)
return (TopFieldDocs)TopDocs.Merge(sort, numHits, shardHits);
}
- public virtual TopFieldDocs LocalSearch(Query query, int numHits, Sort sort)
+ public virtual TopFieldDocs LocalSearch(Query query, int numHits, Sort sort, CancellationToken cancellationToken = default)
{
- return base.Search(query, numHits, sort);
+ return base.Search(query, numHits, sort, cancellationToken);
}
}
diff --git a/src/Lucene.Net.Tests/Search/TestBooleanQuery.cs b/src/Lucene.Net.Tests/Search/TestBooleanQuery.cs
index f3bd107c8..91dff6c87 100644
--- a/src/Lucene.Net.Tests/Search/TestBooleanQuery.cs
+++ b/src/Lucene.Net.Tests/Search/TestBooleanQuery.cs
@@ -3,6 +3,7 @@
using NUnit.Framework;
using System;
using System.Collections.Generic;
+using System.Threading;
using System.Threading.Tasks;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
@@ -395,10 +396,10 @@ public IndexSearcherAnonymousClass(IndexReader r)
{
}
- protected override void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector)
+ protected override void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector, CancellationToken cancellationToken = default)
{
Assert.AreEqual(-1, collector.GetType().Name.IndexOf("OutOfOrder", StringComparison.Ordinal));
- base.Search(leaves, weight, collector);
+ base.Search(leaves, weight, collector, cancellationToken);
}
}
}
diff --git a/src/Lucene.Net.Tests/Search/TestCustomSearcherSort.cs b/src/Lucene.Net.Tests/Search/TestCustomSearcherSort.cs
index d53f23733..1962c479b 100644
--- a/src/Lucene.Net.Tests/Search/TestCustomSearcherSort.cs
+++ b/src/Lucene.Net.Tests/Search/TestCustomSearcherSort.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.Text;
+using System.Threading;
using Assert = Lucene.Net.TestFramework.Assert;
using JCG = J2N.Collections.Generic;
@@ -212,20 +213,20 @@ public CustomSearcher(IndexReader r, int switcher)
this.switcher = switcher;
}
- public override TopFieldDocs Search(Query query, Filter filter, int nDocs, Sort sort)
+ public override TopFieldDocs Search(Query query, Filter filter, int nDocs, Sort sort, CancellationToken cancellationToken = default)
{
BooleanQuery bq = new BooleanQuery();
bq.Add(query, Occur.MUST);
bq.Add(new TermQuery(new Term("mandant", Convert.ToString(switcher))), Occur.MUST);
- return base.Search(bq, filter, nDocs, sort);
+ return base.Search(bq, filter, nDocs, sort, cancellationToken);
}
- public override TopDocs Search(Query query, Filter filter, int nDocs)
+ public override TopDocs Search(Query query, Filter filter, int nDocs, CancellationToken cancellationToken = default)
{
BooleanQuery bq = new BooleanQuery();
bq.Add(query, Occur.MUST);
bq.Add(new TermQuery(new Term("mandant", Convert.ToString(switcher))), Occur.MUST);
- return base.Search(bq, filter, nDocs);
+ return base.Search(bq, filter, nDocs, cancellationToken);
}
}
diff --git a/src/Lucene.Net.Tests/Search/TestIndexSearcher.cs b/src/Lucene.Net.Tests/Search/TestIndexSearcher.cs
index 6e9a565ac..d6ca1d0c0 100644
--- a/src/Lucene.Net.Tests/Search/TestIndexSearcher.cs
+++ b/src/Lucene.Net.Tests/Search/TestIndexSearcher.cs
@@ -1,9 +1,12 @@
+using Lucene.Net.Attributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
+using System.Collections.Generic;
+using System.Threading;
using System.Threading.Tasks;
namespace Lucene.Net.Search
@@ -160,5 +163,321 @@ public virtual void TestSearchAfterPassedMaxDoc()
IOUtils.Dispose(r, dir);
}
}
+
+ // LUCENENET specific - tests for the CancellationToken support
+ // added to IndexSearcher methods. See #922.
+
+ /// <summary>
+ /// Builds a multi-segment index so cancellation at leaf boundaries is observable.
+ /// </summary>
+ private static IndexReader BuildMultiSegmentReader(Directory directory)
+ {
+ RandomIndexWriter iw = new RandomIndexWriter(Random, directory);
+ for (int i = 0; i < 50; i++)
+ {
+ Document doc = new Document();
+ doc.Add(NewStringField("field", Convert.ToString(i), Field.Store.NO));
+ iw.AddDocument(doc);
+ // Commit every few docs to force multiple segments (leaves).
+ if (i % 5 == 0)
+ {
+ iw.Commit();
+ }
+ }
+ IndexReader r = iw.GetReader();
+ iw.Dispose();
+ return r;
+ }
+
+ [Test]
+ [LuceneNetSpecific]
+ public virtual void TestCancellation_SingleThreaded_PreCanceledToken_ThrowsOperationCanceledException()
+ {
+ // When the executor is null (single-threaded), an already-canceled token should
+ // cause OperationCanceledException to be thrown on the first leaf.
+ using CancellationTokenSource cts = new CancellationTokenSource();
+ cts.Cancel();
+
+ IndexSearcher searcher = new IndexSearcher(reader);
+ Query query = new MatchAllDocsQuery();
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.Search(query, 10, cts.Token));
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.Search(query, filter: null, 10, cts.Token));
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.SearchAfter(after: null, query, 10, cts.Token));
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.SearchAfter(after: null, query, filter: null, 10, cts.Token));
+
+ Sort sort = new Sort(new SortField("field", SortFieldType.STRING));
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.Search(query, 10, sort, cts.Token));
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.Search(query, filter: null, 10, sort, cts.Token));
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.Search(query, filter: null, 10, sort, doDocScores: true, doMaxScore: true, cts.Token));
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.SearchAfter(after: null, query, filter: null, 10, sort, cts.Token));
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.SearchAfter(after: null, query, filter: null, 10, sort, doDocScores: true, doMaxScore: true, cts.Token));
+ }
+
+ [Test]
+ [LuceneNetSpecific]
+ public virtual void TestCancellation_SingleThreaded_CollectorOverload_PreCanceledTokenThrows()
+ {
+ // The ICollector overloads also thread the CancellationToken through and
+ // should throw on entry to the leaf iteration.
+ using CancellationTokenSource cts = new CancellationTokenSource();
+ cts.Cancel();
+
+ IndexSearcher searcher = new IndexSearcher(reader);
+ Query query = new MatchAllDocsQuery();
+
+ TotalHitCountCollector collector = new TotalHitCountCollector();
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.Search(query, collector, cts.Token));
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.Search(query, filter: null, collector, cts.Token));
+ }
+
+ [Test]
+ [LuceneNetSpecific]
+ public virtual void TestCancellation_SingleThreaded_CancelDuringSearch_StopsAtNextLeaf()
+ {
+ // Verify that cancellation requested during collection takes effect at the
+ // next leaf boundary, and the partial work already performed does not prevent
+ // the OperationCanceledException from being observed.
+ using Directory directory = NewDirectory();
+ IndexReader r = BuildMultiSegmentReader(directory);
+ try
+ {
+ // Require at least 2 leaves for this assertion to be meaningful.
+ Assume.That(r.Leaves.Count >= 2, "Test requires a multi-segment index");
+
+ IndexSearcher searcher = new IndexSearcher(r);
+ using CancellationTokenSource cts = new CancellationTokenSource();
+
+ int leavesEntered = 0;
+ ICollector collector = Collector.NewAnonymous(
+ setScorer: _ => { },
+ collect: _ => { },
+ setNextReader: _ =>
+ {
+ // Trigger cancellation on the first leaf; the next leaf should
+ // observe the cancellation at the loop's entry check.
+ Interlocked.Increment(ref leavesEntered);
+ cts.Cancel();
+ },
+ acceptsDocsOutOfOrder: () => true);
+
+ Assert.Throws<OperationCanceledException>(
+ () => searcher.Search(new MatchAllDocsQuery(), collector, cts.Token));
+
+ // Only the first leaf should have been entered; subsequent leaves must have
+ // been skipped due to the cancellation check.
+ Assert.AreEqual(1, leavesEntered);
+ }
+ finally
+ {
+ r.Dispose();
+ }
+ }
+
+ [Test]
+ [LuceneNetSpecific]
+ public virtual void TestCancellation_SingleThreaded_DefaultToken_SearchCompletesNormally()
+ {
+ // Sanity check: a default (non-cancellable) token must not affect a normal search.
+ IndexSearcher searcher = new IndexSearcher(reader);
+ TopDocs docs = searcher.Search(new MatchAllDocsQuery(), 10, CancellationToken.None);
+ Assert.AreEqual(100, docs.TotalHits);
+ }
+
+ [Test]
+ [LuceneNetSpecific]
+ public virtual void TestCancellation_MultiThreaded_PreCanceledTokenThrows()
+ {
+ // When the executor is non-null, cancellation is propagated to the submitted
+ // tasks. The awaiting call in ExecutionHelper.MoveNext catches any Wait
+ // exception and re-throws it wrapped via RuntimeException.Create, so we
+ // assert on the wrapped exception having a cancellation-derived inner.
+ TaskScheduler service = new LimitedConcurrencyLevelTaskScheduler(4);
+
+ using Directory directory = NewDirectory();
+ IndexReader r = BuildMultiSegmentReader(directory);
+ try
+ {
+ IndexSearcher searcher = new IndexSearcher(r, service);
+ Query query = new MatchAllDocsQuery();
+
+ using CancellationTokenSource cts = new CancellationTokenSource();
+ cts.Cancel();
+
+ Exception ex = Assert.Catch(() => searcher.Search(query, 10, cts.Token));
+ AssertCancellationInChain(ex);
+
+ ex = Assert.Catch(() => searcher.SearchAfter(after: null, query, 10, cts.Token));
+ AssertCancellationInChain(ex);
+
+ Sort sort = new Sort(new SortField("field", SortFieldType.STRING));
+ ex = Assert.Catch(() => searcher.Search(query, 10, sort, cts.Token));
+ AssertCancellationInChain(ex);
+
+ ex = Assert.Catch(() => searcher.Search(query, filter: null, 10, sort, doDocScores: true, doMaxScore: true, cts.Token));
+ AssertCancellationInChain(ex);
+
+ ex = Assert.Catch(() => searcher.SearchAfter(after: null, query, filter: null, 10, sort, cts.Token));
+ AssertCancellationInChain(ex);
+ }
+ finally
+ {
+ r.Dispose();
+ }
+ }
+
+ [Test]
+ [LuceneNetSpecific]
+ public virtual void TestCancellation_MultiThreaded_CancelDuringSearch_Throws()
+ {
+ // Verify that cancellation requested while tasks are in-flight causes the
+ // multi-threaded search to observe the cancellation. We override the leaf-level
+ // Search to cancel the token after entering the first leaf, which is deterministic
+ // regardless of scheduling.
+ using Directory directory = NewDirectory();
+ IndexReader r = BuildMultiSegmentReader(directory);
+ try
+ {
+ Assume.That(r.Leaves.Count >= 2, "Test requires a multi-segment index");
+
+ using CancellationTokenSource cts = new CancellationTokenSource();
+ TaskScheduler service = new LimitedConcurrencyLevelTaskScheduler(4);
+ IndexSearcher searcher = new CancelAfterFirstLeafSearcher(r, service, cts);
+
+ Exception ex = Assert.Catch(() => searcher.Search(new MatchAllDocsQuery(), 10, cts.Token));
+ AssertCancellationInChain(ex);
+ }
+ finally
+ {
+ r.Dispose();
+ }
+ }
+
+ [Test]
+ [LuceneNetSpecific]
+ public virtual void TestCancellation_MultiThreaded_DefaultToken_SearchCompletesNormally()
+ {
+ // Sanity check: a default (non-cancellable) token must not affect a normal
+ // multi-threaded search.
+ TaskScheduler service = new LimitedConcurrencyLevelTaskScheduler(4);
+
+ using Directory directory = NewDirectory();
+ IndexReader r = BuildMultiSegmentReader(directory);
+ try
+ {
+ IndexSearcher searcher = new IndexSearcher(r, service);
+ TopDocs docs = searcher.Search(new MatchAllDocsQuery(), 10, CancellationToken.None);
+ Assert.AreEqual(50, docs.TotalHits);
+ }
+ finally
+ {
+ r.Dispose();
+ }
+ }
+
+ /// <summary>
+ /// Walks the exception chain (exception + inner exceptions, including the inner
+ /// exceptions of any <see cref="AggregateException"/> encountered) looking for an
+ /// <see cref="OperationCanceledException"/>. The multi-threaded search path wraps
+ /// cancellation exceptions via <c>RuntimeException.Create</c>, so the cancellation
+ /// is not the top-level exception but should always be present in the chain.
+ /// </summary>
+ private static void AssertCancellationInChain(Exception ex)
+ {
+ Assert.IsNotNull(ex, "Expected an exception, but none was thrown.");
+ Exception current = ex;
+ while (current != null)
+ {
+ if (current is OperationCanceledException)
+ {
+ return;
+ }
+ if (current is AggregateException agg)
+ {
+ foreach (Exception inner in agg.InnerExceptions)
+ {
+ if (ContainsOperationCanceled(inner))
+ {
+ return;
+ }
+ }
+ }
+ current = current.InnerException;
+ }
+ Assert.Fail("Expected OperationCanceledException in the exception chain, but got: " + ex);
+ }
+
+ private static bool ContainsOperationCanceled(Exception ex)
+ {
+ Exception current = ex;
+ while (current != null)
+ {
+ if (current is OperationCanceledException)
+ {
+ return true;
+ }
+ if (current is AggregateException agg)
+ {
+ foreach (Exception inner in agg.InnerExceptions)
+ {
+ if (ContainsOperationCanceled(inner))
+ {
+ return true;
+ }
+ }
+ }
+ current = current.InnerException;
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// An <see cref="IndexSearcher"/> subclass that cancels the given
+ /// <see cref="CancellationTokenSource"/> after the first leaf context is entered
+ /// in the leaf-level Search method. This makes cancellation during multi-threaded
+ /// search deterministic — the first slice triggers cancellation, and subsequent
+ /// slices (or leaves within the same slice) observe it.
+ /// </summary>
+ private sealed class CancelAfterFirstLeafSearcher : IndexSearcher
+ {
+ private readonly CancellationTokenSource cts;
+ private int leafEntered; // 0 = not yet, 1 = already canceled
+
+ public CancelAfterFirstLeafSearcher(IndexReader r, TaskScheduler executor, CancellationTokenSource cts)
+ : base(r, executor)
+ {
+ this.cts = cts;
+ }
+
+ protected override void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector, CancellationToken cancellationToken = default)
+ {
+ // Cancel after the very first leaf has been entered across all slices.
+ if (Interlocked.Exchange(ref leafEntered, 1) == 0)
+ {
+ cts.Cancel();
+ }
+ base.Search(leaves, weight, collector, cancellationToken);
+ }
+ }
}
}
diff --git a/src/Lucene.Net/Search/CollectionTerminatedException.cs b/src/Lucene.Net/Search/CollectionTerminatedException.cs
index 1845e4de7..3471501e3 100644
--- a/src/Lucene.Net/Search/CollectionTerminatedException.cs
+++ b/src/Lucene.Net/Search/CollectionTerminatedException.cs
@@ -1,4 +1,5 @@
using System;
+using System.Threading;
#if FEATURE_SERIALIZABLE_EXCEPTIONS
using System.ComponentModel;
@@ -29,7 +30,7 @@ namespace Lucene.Net.Search
/// terminate collection of the current leaf.
/// <para/>Note: <see cref="IndexSearcher"/> swallows this exception and never re-throws it.
/// As a consequence, you should not catch it when calling any overload of
- /// <see cref="IndexSearcher.Search(Weight, FieldDoc, int, Sort, bool, bool, bool)"/> as it is unnecessary and might hide misuse
+ /// <see cref="IndexSearcher.Search(Weight, FieldDoc, int, Sort, bool, bool, bool, CancellationToken)"/> as it is unnecessary and might hide misuse
/// of this exception.
/// </summary>
// LUCENENET: It is no longer good practice to use binary serialization.
diff --git a/src/Lucene.Net/Search/FieldComparator.cs b/src/Lucene.Net/Search/FieldComparator.cs
index 1131ea1fe..92f01a49a 100644
--- a/src/Lucene.Net/Search/FieldComparator.cs
+++ b/src/Lucene.Net/Search/FieldComparator.cs
@@ -1,7 +1,9 @@
using Lucene.Net.Diagnostics;
+using Lucene.Net.Index;
using Lucene.Net.Support;
using System;
using System.IO;
+using System.Threading;
using JCG = J2N.Collections.Generic;
using Number = J2N.Numerics.Number;
@@ -403,7 +405,7 @@ public override FieldComparer SetNextReader(AtomicReaderContext context)
/// <summary>
/// Parses field's values as <see cref="byte"/> (using
- /// <see cref="IFieldCache.GetBytes(Index.AtomicReader, string, FieldCache.IByteParser, bool)"/> and sorts by ascending value
+ /// <see cref="IFieldCache.GetBytes(AtomicReader, string, FieldCache.IByteParser, bool)"/> and sorts by ascending value
/// </summary>
[Obsolete, CLSCompliant(false)] // LUCENENET NOTE: marking non-CLS compliant because of sbyte - it is obsolete, anyway
public sealed class ByteComparer : NumericComparer<J2N.Numerics.SByte>
@@ -488,7 +490,7 @@ public override int CompareTop(int doc)
/// <summary>
/// Parses field's values as <see cref="double"/> (using
- /// <see cref="IFieldCache.GetDoubles(Index.AtomicReader, string, FieldCache.IDoubleParser, bool)"/> and sorts by ascending value
+ /// <see cref="IFieldCache.GetDoubles(AtomicReader, string, FieldCache.IDoubleParser, bool)"/> and sorts by ascending value
/// </summary>
public sealed class DoubleComparer : NumericComparer<J2N.Numerics.Double>
{
@@ -581,7 +583,7 @@ public override int CompareTop(int doc)
/// <summary>
/// Parses field's values as <see cref="float"/> (using
- /// <see cref="IFieldCache.GetSingles(Index.AtomicReader, string, FieldCache.ISingleParser, bool)"/> and sorts by ascending value
+ /// <see cref="IFieldCache.GetSingles(AtomicReader, string, FieldCache.ISingleParser, bool)"/> and sorts by ascending value
/// <para/>
/// NOTE: This was FloatComparator in Lucene
/// </summary>
@@ -677,7 +679,7 @@ public override int CompareTop(int doc)
/// <summary>
/// Parses field's values as <see cref="short"/> (using
- /// <see cref="IFieldCache.GetInt16s(Index.AtomicReader, string, FieldCache.IInt16Parser, bool)"/> and sorts by ascending value
+ /// <see cref="IFieldCache.GetInt16s(AtomicReader, string, FieldCache.IInt16Parser, bool)"/> and sorts by ascending value
/// <para/>
/// NOTE: This was ShortComparator in Lucene
/// </summary>
@@ -765,7 +767,7 @@ public override int CompareTop(int doc)
/// <summary>
/// Parses field's values as <see cref="int"/> (using
- /// <see cref="IFieldCache.GetInt32s(Index.AtomicReader, string, FieldCache.IInt32Parser, bool)"/> and sorts by ascending value
+ /// <see cref="IFieldCache.GetInt32s(AtomicReader, string, FieldCache.IInt32Parser, bool)"/> and sorts by ascending value
/// <para/>
/// NOTE: This was IntComparator in Lucene
/// </summary>
@@ -849,7 +851,7 @@ public override int CompareTop(int doc)
/// <summary>
/// Parses field's values as <see cref="long"/> (using
- /// <see cref="IFieldCache.GetInt64s(Index.AtomicReader, string, FieldCache.IInt64Parser, bool)"/> and sorts by ascending value
+ /// <see cref="IFieldCache.GetInt64s(AtomicReader, string, FieldCache.IInt64Parser, bool)"/> and sorts by ascending value
/// <para/>
/// NOTE: This was LongComparator in Lucene
/// </summary>
@@ -941,7 +943,7 @@ public override int CompareTop(int doc)
/// sorting only by descending relevance and then
/// secondarily by ascending docID, performance is faster
/// using <see cref="TopScoreDocCollector"/> directly (which all overloads of
- /// <see cref="IndexSearcher.Search(Query, int)"/> use when no <see cref="Sort"/> is
+ /// <see cref="IndexSearcher.Search(Query, int, CancellationToken)"/> use when no <see cref="Sort"/> is
/// specified).
/// </summary>
public sealed class RelevanceComparer : FieldComparer<J2N.Numerics.Single>
@@ -1105,11 +1107,11 @@ public override int CompareTop(int doc)
}
/// <summary>
- /// Sorts by field's natural <see cref="Index.Term"/> sort order, using
+ /// Sorts by field's natural <see cref="Term"/> sort order, using
/// ordinals. This is functionally equivalent to
/// <see cref="Lucene.Net.Search.FieldComparer.TermValComparer"/>, but it first resolves the string
/// to their relative ordinal positions (using the index
- /// returned by <see cref="IFieldCache.GetTermsIndex(Index.AtomicReader, string, float)"/>), and
+ /// returned by <see cref="IFieldCache.GetTermsIndex(AtomicReader, string, float)"/>), and
/// does most comparisons using the ordinals. For medium
/// to large results, this comparer will be much faster
/// than <see cref="Lucene.Net.Search.FieldComparer.TermValComparer"/>. For very small
@@ -1447,7 +1449,7 @@ public override int CompareValues(BytesRef val1, BytesRef val2)
}
/// <summary>
- /// Sorts by field's natural <see cref="Index.Term"/> sort order. All
+ /// Sorts by field's natural <see cref="Term"/> sort order. All
/// comparisons are done using <see cref="BytesRef.CompareTo(BytesRef)"/>, which is
/// slow for medium to large result sets but possibly
/// very fast for very small results sets.
diff --git a/src/Lucene.Net/Search/FieldDoc.cs b/src/Lucene.Net/Search/FieldDoc.cs
index be32ee1fc..d6ab214ea 100644
--- a/src/Lucene.Net/Search/FieldDoc.cs
+++ b/src/Lucene.Net/Search/FieldDoc.cs
@@ -1,6 +1,7 @@
using Lucene.Net.Support;
using System.Diagnostics.CodeAnalysis;
using System.Text;
+using System.Threading;
namespace Lucene.Net.Search
{
@@ -48,7 +49,7 @@ public class FieldDoc : ScoreDoc
/// the <see cref="FieldComparer.GetValue(int)"/> method corresponding
/// FieldComparer used to sort this field. </summary>
/// <seealso cref="Sort"/>
- /// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort)"/>
+ /// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort,CancellationToken)"/>
public object[] Fields;
/// <summary>
diff --git a/src/Lucene.Net/Search/FieldValueHitQueue.cs b/src/Lucene.Net/Search/FieldValueHitQueue.cs
index 56e15a6c0..8076ae502 100644
--- a/src/Lucene.Net/Search/FieldValueHitQueue.cs
+++ b/src/Lucene.Net/Search/FieldValueHitQueue.cs
@@ -6,6 +6,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
+using System.Threading;
namespace Lucene.Net.Search
{
@@ -196,7 +197,7 @@ public static FieldValueHitQueue<T> Create<T>(SortField[] fields, int size)
/// <para/>
/// @lucene.experimental
/// @since 2.9 </summary>
- /// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort)"/>
+ /// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort,CancellationToken)"/>
/// <seealso cref="FieldCache"/>
public abstract class FieldValueHitQueue<T> : PriorityQueue<T>
where T : FieldValueHitQueue.Entry
@@ -259,7 +260,7 @@ public virtual void SetComparer(int pos, FieldComparer comparer)
/// </summary>
/// <param name="entry"> The <see cref="FieldValueHitQueue.Entry"/> used to create a <see cref="FieldDoc"/> </param>
/// <returns> The newly created <see cref="FieldDoc"/> </returns>
- /// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort)"/>
+ /// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort,CancellationToken)"/>
internal virtual FieldDoc FillFields(FieldValueHitQueue.Entry entry)
{
int n = m_comparers.Length;
diff --git a/src/Lucene.Net/Search/IndexSearcher.cs b/src/Lucene.Net/Search/IndexSearcher.cs
index 964e05474..512831039 100644
--- a/src/Lucene.Net/Search/IndexSearcher.cs
+++ b/src/Lucene.Net/Search/IndexSearcher.cs
@@ -1,5 +1,6 @@
#nullable enable
using Lucene.Net.Diagnostics;
+using Lucene.Net.Index;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using System;
@@ -7,6 +8,7 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
+using System.Threading;
using System.Threading.Tasks;
namespace Lucene.Net.Search
@@ -42,22 +44,22 @@ namespace Lucene.Net.Search
using Terms = Lucene.Net.Index.Terms;
/// <summary>
- /// Implements search over a single <see cref="Index.IndexReader"/>.
+ /// Implements search over a single <see cref="IndexReader"/>.
///
/// <para/>Applications usually need only call the inherited
- /// <see cref="Search(Query,int)"/>
- /// or <see cref="Search(Query,Filter,int)"/> methods. For
+ /// <see cref="Search(Query,int,CancellationToken)"/>
+ /// or <see cref="Search(Query,Filter,int,CancellationToken)"/> methods. For
/// performance reasons, if your index is unchanging, you
/// should share a single <see cref="IndexSearcher"/> instance across
/// multiple searches instead of creating a new one
/// per-search. If your index has changed and you wish to
/// see the changes reflected in searching, you should
- /// use <see cref="Index.DirectoryReader.OpenIfChanged(Index.DirectoryReader)"/>
+ /// use <see cref="DirectoryReader.OpenIfChanged(DirectoryReader)"/>
/// to obtain a new reader and
/// then create a new <see cref="IndexSearcher"/> from that. Also, for
/// low-latency turnaround it's best to use a near-real-time
- /// reader (<see cref="Index.DirectoryReader.Open(Index.IndexWriter,bool)"/>).
- /// Once you have a new <see cref="Index.IndexReader"/>, it's relatively
+ /// reader (<see cref="DirectoryReader.Open(IndexWriter,bool)"/>).
+ /// Once you have a new <see cref="Net.Index.IndexReader"/>, it's relatively
/// cheap to create a new <see cref="IndexSearcher"/> from it.
///
/// <para/><a name="thread-safety"></a><p><b>NOTE</b>:
@@ -68,6 +70,18 @@ namespace Lucene.Net.Search
/// synchronize on the <see cref="IndexSearcher"/> instance;
/// use your own (non-Lucene) objects instead.</p>
/// </summary>
+ /// <remarks>
+ /// LUCENENET Specific - Search methods have had an optional <see cref="CancellationToken"/> parameter added
+ /// to allow for cancellation of the search operation. For multithreaded search operations, the
+ /// <see cref="TaskScheduler"/> passed to the constructor will be used to execute the search operations
+ /// and the <see cref="CancellationToken"/> will be passed to the awaited tasks. If the <see cref="TaskScheduler"/>
+ /// is <c>null</c>, the search operations will be executed synchronously, and the <see cref="CancellationToken"/>
+ /// will throw an <see cref="OperationCanceledException"/> if cancellation is requested upon entry to each leaf
+ /// reader. Each task in the multithreaded case acts as if it were a single-threaded search, and will do the same.
+ /// <para />
+ /// In both cases, this is a "best effort" attempt at cancellation, and some work may continue to proceed
+ /// after the cancellation has been requested.
+ /// </remarks>
public class IndexSearcher
{
internal readonly IndexReader reader; // package private for testing!
@@ -212,7 +226,7 @@ protected virtual LeafSlice[] GetSlices(IList<AtomicReaderContext> leaves)
}
/// <summary>
- /// Return the <see cref="Index.IndexReader"/> this searches. </summary>
+ /// Return the <see cref="IndexReader"/> this searches. </summary>
public virtual IndexReader IndexReader => reader;
/// <summary>
@@ -279,9 +293,10 @@ protected virtual Query WrapFilter(Query query, Filter? filter)
/// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> is <c>null</c>.</exception>
- public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, int n)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, int n, CancellationToken cancellationToken = default)
{
- return Search(CreateNormalizedWeight(query), after, n);
+ return Search(CreateNormalizedWeight(query), after, n, cancellationToken);
}
/// <summary>
@@ -296,9 +311,10 @@ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, int n)
/// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> is <c>null</c>.</exception>
- public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, Filter? filter, int n)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, Filter? filter, int n, CancellationToken cancellationToken = default)
{
- return Search(CreateNormalizedWeight(WrapFilter(query, filter)), after, n);
+ return Search(CreateNormalizedWeight(WrapFilter(query, filter)), after, n, cancellationToken);
}
/// <summary>
@@ -308,9 +324,10 @@ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, Filter? filter,
/// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> is <c>null</c>.</exception>
- public virtual TopDocs Search(Query query, int n)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopDocs Search(Query query, int n, CancellationToken cancellationToken = default)
{
- return Search(query, filter: null, n);
+ return Search(query, filter: null, n, cancellationToken);
}
/// <summary>
@@ -319,9 +336,10 @@ public virtual TopDocs Search(Query query, int n)
/// </summary>
/// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
- public virtual TopDocs Search(Query query, Filter? filter, int n)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopDocs Search(Query query, Filter? filter, int n, CancellationToken cancellationToken = default)
{
- return Search(CreateNormalizedWeight(WrapFilter(query, filter)), after: null, n);
+ return Search(CreateNormalizedWeight(WrapFilter(query, filter)), after: null, n, cancellationToken);
}
/// <summary>
@@ -337,9 +355,10 @@ public virtual TopDocs Search(Query query, Filter? filter, int n)
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> or
/// <paramref name="results"/> is <c>null</c>.</exception>
- public virtual void Search(Query query, Filter? filter, ICollector results)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual void Search(Query query, Filter? filter, ICollector results, CancellationToken cancellationToken = default)
{
- Search(m_leafContexts, CreateNormalizedWeight(WrapFilter(query, filter)), results);
+ Search(m_leafContexts, CreateNormalizedWeight(WrapFilter(query, filter)), results, cancellationToken);
}
/// <summary>
@@ -351,9 +370,10 @@ public virtual void Search(Query query, Filter? filter, ICollector results)
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> or
/// <paramref name="results"/> is <c>null</c>.</exception>
- public virtual void Search(Query query, ICollector results)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual void Search(Query query, ICollector results, CancellationToken cancellationToken = default)
{
- Search(m_leafContexts, CreateNormalizedWeight(query), results);
+ Search(m_leafContexts, CreateNormalizedWeight(query), results, cancellationToken);
}
/// <summary>
@@ -363,16 +383,17 @@ public virtual void Search(Query query, ICollector results)
/// <paramref name="sort"/>.
///
/// <para/>NOTE: this does not compute scores by default; use
- /// <see cref="IndexSearcher.Search(Query,Filter,int,Sort,bool,bool)"/> to
+ /// <see cref="IndexSearcher.Search(Query,Filter,int,Sort,bool,bool,CancellationToken)"/> to
/// control scoring.
/// </summary>
/// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> or
/// <paramref name="sort"/> is <c>null</c>.</exception>
- public virtual TopFieldDocs Search(Query query, Filter? filter, int n, Sort sort)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopFieldDocs Search(Query query, Filter? filter, int n, Sort sort, CancellationToken cancellationToken = default)
{
- return Search(CreateNormalizedWeight(WrapFilter(query, filter)), n, sort, false, false);
+ return Search(CreateNormalizedWeight(WrapFilter(query, filter)), n, sort, false, false, cancellationToken);
}
/// <summary>
@@ -391,9 +412,10 @@ public virtual TopFieldDocs Search(Query query, Filter? filter, int n, Sort sort
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> or
/// <paramref name="sort"/> is <c>null</c>.</exception>
- public virtual TopFieldDocs Search(Query query, Filter? filter, int n, Sort sort, bool doDocScores, bool doMaxScore)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopFieldDocs Search(Query query, Filter? filter, int n, Sort sort, bool doDocScores, bool doMaxScore, CancellationToken cancellationToken = default)
{
- return Search(CreateNormalizedWeight(WrapFilter(query, filter)), n, sort, doDocScores, doMaxScore);
+ return Search(CreateNormalizedWeight(WrapFilter(query, filter)), n, sort, doDocScores, doMaxScore, cancellationToken);
}
/// <summary>
@@ -409,11 +431,12 @@ public virtual TopFieldDocs Search(Query query, Filter? filter, int n, Sort sort
/// <seealso cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> or
/// <paramref name="sort"/> is <c>null</c>.</exception>
- public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, Filter? filter, int n, Sort sort)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, Filter? filter, int n, Sort sort, CancellationToken cancellationToken = default)
{
FieldDoc? fieldDoc = GetScoreDocAsFieldDocIfNotNull(after);
- return Search(CreateNormalizedWeight(WrapFilter(query, filter)), fieldDoc, n, sort, true, false, false);
+ return Search(CreateNormalizedWeight(WrapFilter(query, filter)), fieldDoc, n, sort, true, false, false, cancellationToken);
}
private static FieldDoc? GetScoreDocAsFieldDocIfNotNull(ScoreDoc? after)
@@ -439,9 +462,10 @@ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, Filter? filter,
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> or
/// <paramref name="sort"/> is <c>null</c>.</exception>
- public virtual TopFieldDocs Search(Query query, int n, Sort sort)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopFieldDocs Search(Query query, int n, Sort sort, CancellationToken cancellationToken = default)
{
- return Search(CreateNormalizedWeight(query), n, sort, false, false);
+ return Search(CreateNormalizedWeight(query), n, sort, false, false, cancellationToken);
}
/// <summary>
@@ -457,11 +481,12 @@ public virtual TopFieldDocs Search(Query query, int n, Sort sort)
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> or
/// <paramref name="sort"/> is <c>null</c>.</exception>
- public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, int n, Sort sort)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, int n, Sort sort, CancellationToken cancellationToken = default)
{
var fieldDoc = GetScoreDocAsFieldDocIfNotNull(after);
- return Search(CreateNormalizedWeight(query), fieldDoc, n, sort, true, false, false);
+ return Search(CreateNormalizedWeight(query), fieldDoc, n, sort, true, false, false, cancellationToken);
}
/// <summary>
@@ -482,23 +507,25 @@ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, int n, Sort sor
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="query"/> or
/// <paramref name="sort"/> is <c>null</c>.</exception>
- public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, Filter? filter, int n, Sort sort, bool doDocScores, bool doMaxScore)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ public virtual TopDocs SearchAfter(ScoreDoc? after, Query query, Filter? filter, int n, Sort sort, bool doDocScores, bool doMaxScore, CancellationToken cancellationToken = default)
{
var fieldDoc = GetScoreDocAsFieldDocIfNotNull(after);
- return Search(CreateNormalizedWeight(WrapFilter(query, filter)), fieldDoc, n, sort, true, doDocScores, doMaxScore);
+ return Search(CreateNormalizedWeight(WrapFilter(query, filter)), fieldDoc, n, sort, true, doDocScores, doMaxScore, cancellationToken);
}
/// <summary>
/// Expert: Low-level search implementation. Finds the top <paramref name="nDocs"/>
/// hits for <c>query</c>, applying <c>filter</c> if non-null.
///
- /// <para/>Applications should usually call <see cref="IndexSearcher.Search(Query,int)"/> or
- /// <see cref="IndexSearcher.Search(Query,Filter,int)"/> instead. </summary>
+ /// <para/>Applications should usually call <see cref="IndexSearcher.Search(Query,int,CancellationToken)"/> or
+ /// <see cref="IndexSearcher.Search(Query,Filter,int,CancellationToken)"/> instead. </summary>
/// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="weight"/> is <c>null</c>.</exception>
- protected virtual TopDocs Search(Weight weight, ScoreDoc? after, int nDocs)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ protected virtual TopDocs Search(Weight weight, ScoreDoc? after, int nDocs, CancellationToken cancellationToken = default)
{
int limit = reader.MaxDoc;
if (limit == 0)
@@ -513,7 +540,7 @@ protected virtual TopDocs Search(Weight weight, ScoreDoc? after, int nDocs)
if (executor is null)
{
- return Search(m_leafContexts, weight, after, nDocs);
+ return Search(m_leafContexts, weight, after, nDocs, cancellationToken);
}
else
{
@@ -525,11 +552,11 @@ protected virtual TopDocs Search(Weight weight, ScoreDoc? after, int nDocs)
HitQueue hq = new HitQueue(nDocs, prePopulate: false);
ReentrantLock @lock = new ReentrantLock();
- ExecutionHelper<TopDocs> runner = new ExecutionHelper<TopDocs>(executor);
+ ExecutionHelper<TopDocs> runner = new ExecutionHelper<TopDocs>(executor, cancellationToken);
for (int i = 0; i < m_leafSlices.Length; i++) // search each sub
{
- runner.Submit(new SearcherCallableNoSort(@lock, this, m_leafSlices[i], weight, after, nDocs, hq).Call);
+ runner.Submit(new SearcherCallableNoSort(@lock, this, m_leafSlices[i], weight, after, nDocs, hq, cancellationToken).Call);
}
int totalHits = 0;
@@ -557,13 +584,14 @@ protected virtual TopDocs Search(Weight weight, ScoreDoc? after, int nDocs)
/// Expert: Low-level search implementation. Finds the top <code>n</code>
/// hits for <c>query</c>.
///
- /// <para/>Applications should usually call <see cref="IndexSearcher.Search(Query,int)"/> or
- /// <see cref="IndexSearcher.Search(Query,Filter,int)"/> instead. </summary>
+ /// <para/>Applications should usually call <see cref="IndexSearcher.Search(Query,int,CancellationToken)"/> or
+ /// <see cref="IndexSearcher.Search(Query,Filter,int,CancellationToken)"/> instead. </summary>
/// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="leaves"/> or
/// <paramref name="weight"/> is <c>null</c>.</exception>
- protected virtual TopDocs Search(IList<AtomicReaderContext> leaves, Weight weight, ScoreDoc? after, int nDocs)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ protected virtual TopDocs Search(IList<AtomicReaderContext> leaves, Weight weight, ScoreDoc? after, int nDocs, CancellationToken cancellationToken = default)
{
// LUCENENET: Added guard clause
if (weight is null)
@@ -577,7 +605,7 @@ protected virtual TopDocs Search(IList<AtomicReaderContext> leaves, Weight weigh
}
nDocs = Math.Min(nDocs, limit);
TopScoreDocCollector collector = TopScoreDocCollector.Create(nDocs, after, !weight.ScoresDocsOutOfOrder);
- Search(leaves, weight, collector);
+ Search(leaves, weight, collector, cancellationToken);
return collector.GetTopDocs();
}
@@ -589,25 +617,27 @@ protected virtual TopDocs Search(IList<AtomicReaderContext> leaves, Weight weigh
/// by the criteria in <paramref name="sort"/>.
///
/// <para/>Applications should usually call
- /// <see cref="IndexSearcher.Search(Query,Filter,int,Sort)"/> instead.
+ /// <see cref="IndexSearcher.Search(Query,Filter,int,Sort,CancellationToken)"/> instead.
/// </summary>
/// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="weight"/> or
/// <paramref name="sort"/> is <c>null</c>.</exception>
- protected virtual TopFieldDocs Search(Weight weight, int nDocs, Sort sort, bool doDocScores, bool doMaxScore)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ protected virtual TopFieldDocs Search(Weight weight, int nDocs, Sort sort, bool doDocScores, bool doMaxScore, CancellationToken cancellationToken = default)
{
- return Search(weight, after: null, nDocs, sort, true, doDocScores, doMaxScore);
+ return Search(weight, after: null, nDocs, sort, true, doDocScores, doMaxScore, cancellationToken);
}
/// <summary>
- /// Just like <see cref="Search(Weight, int, Sort, bool, bool)"/>, but you choose
+ /// Just like <see cref="Search(Weight, int, Sort, bool, bool, CancellationToken)"/>, but you choose
/// whether or not the fields in the returned <see cref="FieldDoc"/> instances should
/// be set by specifying <paramref name="fillFields"/>.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="weight"/> or
/// <paramref name="sort"/> is <c>null</c>.</exception>
- protected virtual TopFieldDocs Search(Weight weight, FieldDoc? after, int nDocs, Sort sort, bool fillFields, bool doDocScores, bool doMaxScore)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ protected virtual TopFieldDocs Search(Weight weight, FieldDoc? after, int nDocs, Sort sort, bool fillFields, bool doDocScores, bool doMaxScore, CancellationToken cancellationToken = default)
{
if (sort is null)
throw new ArgumentNullException(nameof(sort), "Sort must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
@@ -622,7 +652,7 @@ protected virtual TopFieldDocs Search(Weight weight, FieldDoc? after, int nDocs,
if (executor is null)
{
// use all leaves here!
- return Search(m_leafContexts, weight, after, nDocs, sort, fillFields, doDocScores, doMaxScore);
+ return Search(m_leafContexts, weight, after, nDocs, sort, fillFields, doDocScores, doMaxScore, cancellationToken);
}
else
{
@@ -635,11 +665,11 @@ protected virtual TopFieldDocs Search(Weight weight, FieldDoc? after, int nDocs,
TopFieldCollector topCollector = TopFieldCollector.Create(sort, nDocs, after, fillFields, doDocScores, doMaxScore, false);
ReentrantLock @lock = new ReentrantLock();
- ExecutionHelper<TopFieldDocs> runner = new ExecutionHelper<TopFieldDocs>(executor);
+ ExecutionHelper<TopFieldDocs> runner = new ExecutionHelper<TopFieldDocs>(executor, cancellationToken);
for (int i = 0; i < m_leafSlices.Length; i++) // search each leaf slice
{
- runner.Submit(new SearcherCallableWithSort(@lock, this, m_leafSlices[i], weight, after, nDocs, topCollector, sort, doDocScores, doMaxScore).Call);
+ runner.Submit(new SearcherCallableWithSort(@lock, this, m_leafSlices[i], weight, after, nDocs, topCollector, sort, doDocScores, doMaxScore, cancellationToken).Call);
}
int totalHits = 0;
@@ -660,13 +690,14 @@ protected virtual TopFieldDocs Search(Weight weight, FieldDoc? after, int nDocs,
}
/// <summary>
- /// Just like <see cref="Search(Weight, int, Sort, bool, bool)"/>, but you choose
+ /// Just like <see cref="Search(Weight, int, Sort, bool, bool, CancellationToken)"/>, but you choose
/// whether or not the fields in the returned <see cref="FieldDoc"/> instances should
/// be set by specifying <paramref name="fillFields"/>.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="leaves"/> or
/// <paramref name="weight"/> is <c>null</c>.</exception>
- protected virtual TopFieldDocs Search(IList<AtomicReaderContext> leaves, Weight weight, FieldDoc? after, int nDocs, Sort sort, bool fillFields, bool doDocScores, bool doMaxScore)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ protected virtual TopFieldDocs Search(IList<AtomicReaderContext> leaves, Weight weight, FieldDoc? after, int nDocs, Sort sort, bool fillFields, bool doDocScores, bool doMaxScore, CancellationToken cancellationToken = default)
{
// LUCENENET: Added guard clause
if (weight is null)
@@ -681,7 +712,7 @@ protected virtual TopFieldDocs Search(IList<AtomicReaderContext> leaves, Weight
nDocs = Math.Min(nDocs, limit);
TopFieldCollector collector = TopFieldCollector.Create(sort, nDocs, after, fillFields, doDocScores, doMaxScore, !weight.ScoresDocsOutOfOrder);
- Search(leaves, weight, collector);
+ Search(leaves, weight, collector, cancellationToken);
return (TopFieldDocs)collector.GetTopDocs();
}
@@ -705,7 +736,8 @@ protected virtual TopFieldDocs Search(IList<AtomicReaderContext> leaves, Weight
/// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception>
/// <exception cref="ArgumentNullException"><paramref name="leaves"/>, <paramref name="weight"/>,
/// or <paramref name="collector"/> is <c>null</c>.</exception>
- protected virtual void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector)
+ /// <exception cref="OperationCanceledException">If cancellation is requested via the <paramref name="cancellationToken"/>.</exception>
+ protected virtual void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector, CancellationToken cancellationToken = default)
{
// LUCENENET: Added guard clauses
if (leaves is null)
@@ -720,6 +752,8 @@ protected virtual void Search(IList<AtomicReaderContext> leaves, Weight weight,
// always use single thread:
foreach (AtomicReaderContext ctx in leaves) // search each subreader
{
+ cancellationToken.ThrowIfCancellationRequested(); // LUCENENET specific - cancellation support at leaf level
+
try
{
collector.SetNextReader(ctx);
@@ -847,8 +881,9 @@ private sealed class SearcherCallableNoSort // LUCENENET: no need for ICallable<
private readonly int nDocs;
private readonly HitQueue hq;
private readonly LeafSlice slice;
+ private readonly CancellationToken cancellationToken;
- public SearcherCallableNoSort(ReentrantLock @lock, IndexSearcher searcher, LeafSlice slice, Weight weight, ScoreDoc? after, int nDocs, HitQueue hq)
+ public SearcherCallableNoSort(ReentrantLock @lock, IndexSearcher searcher, LeafSlice slice, Weight weight, ScoreDoc? after, int nDocs, HitQueue hq, CancellationToken cancellationToken)
{
this.@lock = @lock;
this.searcher = searcher;
@@ -856,12 +891,13 @@ public SearcherCallableNoSort(ReentrantLock @lock, IndexSearcher searcher, LeafS
this.after = after;
this.nDocs = nDocs;
this.hq = hq;
+ this.cancellationToken = cancellationToken;
this.slice = slice;
}
public TopDocs Call()
{
- TopDocs docs = searcher.Search(slice.Leaves, weight, after, nDocs);
+ TopDocs docs = searcher.Search(slice.Leaves, weight, after, nDocs, cancellationToken);
ScoreDoc[] scoreDocs = docs.ScoreDocs;
//it would be so nice if we had a thread-safe insert
@lock.Lock();
@@ -899,8 +935,9 @@ private sealed class SearcherCallableWithSort // LUCENENET: no need for ICallabl
private readonly FieldDoc? after;
private readonly bool doDocScores;
private readonly bool doMaxScore;
+ private readonly CancellationToken cancellationToken;
- public SearcherCallableWithSort(ReentrantLock @lock, IndexSearcher searcher, LeafSlice slice, Weight weight, FieldDoc? after, int nDocs, TopFieldCollector hq, Sort sort, bool doDocScores, bool doMaxScore)
+ public SearcherCallableWithSort(ReentrantLock @lock, IndexSearcher searcher, LeafSlice slice, Weight weight, FieldDoc? after, int nDocs, TopFieldCollector hq, Sort sort, bool doDocScores, bool doMaxScore, CancellationToken cancellationToken)
{
this.@lock = @lock;
this.searcher = searcher;
@@ -912,6 +949,7 @@ public SearcherCallableWithSort(ReentrantLock @lock, IndexSearcher searcher, Lea
this.after = after;
this.doDocScores = doDocScores;
this.doMaxScore = doMaxScore;
+ this.cancellationToken = cancellationToken;
}
private readonly FakeScorer fakeScorer = new FakeScorer();
@@ -919,7 +957,7 @@ public SearcherCallableWithSort(ReentrantLock @lock, IndexSearcher searcher, Lea
public TopFieldDocs Call()
{
if (Debugging.AssertsEnabled) Debugging.Assert(slice.Leaves.Length == 1);
- TopFieldDocs docs = searcher.Search(slice.Leaves, weight, after, nDocs, sort, true, doDocScores || sort.NeedsScores, doMaxScore);
+ TopFieldDocs docs = searcher.Search(slice.Leaves, weight, after, nDocs, sort, true, doDocScores || sort.NeedsScores, doMaxScore, cancellationToken);
@lock.Lock();
try
{
@@ -958,12 +996,14 @@ public TopFieldDocs Call()
private sealed class ExecutionHelper<T> : IEnumerator<T>, IEnumerable<T>
{
private readonly TaskSchedulerCompletionService<T> service;
+ private readonly CancellationToken cancellationToken;
private int numTasks;
private T current;
- internal ExecutionHelper(TaskScheduler executor)
+ internal ExecutionHelper(TaskScheduler executor, CancellationToken cancellationToken)
{
this.service = new TaskSchedulerCompletionService<T>(executor);
+ this.cancellationToken = cancellationToken;
}
public T Current => current;
@@ -977,7 +1017,7 @@ public void Dispose()
public void Submit(Func<T> task)
{
- this.service.Submit(task);
+ this.service.Submit(task, cancellationToken);
++numTasks;
}
@@ -993,7 +1033,7 @@ public bool MoveNext()
try
{
var awaitable = service.Take();
- awaitable.Wait();
+ awaitable.Wait(cancellationToken);
current = awaitable.Result;
return true;
diff --git a/src/Lucene.Net/Search/Sort.cs b/src/Lucene.Net/Search/Sort.cs
index e95c30417..7366f9a93 100644
--- a/src/Lucene.Net/Search/Sort.cs
+++ b/src/Lucene.Net/Search/Sort.cs
@@ -1,6 +1,7 @@
using Lucene.Net.Support;
using System.IO;
using System.Text;
+using System.Threading;
namespace Lucene.Net.Search
{
@@ -102,7 +103,7 @@ public class Sort
/// <summary>
/// Represents sorting by computed relevance. Using this sort criteria returns
/// the same results as calling
- /// <see cref="IndexSearcher.Search(Query, int)"/>without a sort criteria,
+ /// <see cref="IndexSearcher.Search(Query, int, CancellationToken)"/> without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public static readonly Sort RELEVANCE = new Sort();
@@ -116,7 +117,7 @@ public class Sort
/// <summary>
/// Sorts by computed relevance. This is the same sort criteria as calling
- /// <see cref="IndexSearcher.Search(Query, int)"/> without a sort criteria,
+ /// <see cref="IndexSearcher.Search(Query, int, CancellationToken)"/> without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public Sort()
diff --git a/src/Lucene.Net/Search/TopDocs.cs b/src/Lucene.Net/Search/TopDocs.cs
index b1ac33afe..bf445c276 100644
--- a/src/Lucene.Net/Search/TopDocs.cs
+++ b/src/Lucene.Net/Search/TopDocs.cs
@@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
+using System.Threading;
namespace Lucene.Net.Search
{
@@ -28,8 +29,8 @@ namespace Lucene.Net.Search
/// <summary>
/// Represents hits returned by
- /// <see cref="IndexSearcher.Search(Query,Filter,int)"/> and
- /// <see cref="IndexSearcher.Search(Query,int)"/>.
+ /// <see cref="IndexSearcher.Search(Query,Filter,int,CancellationToken)"/> and
+ /// <see cref="IndexSearcher.Search(Query,int,CancellationToken)"/>.
/// </summary>
public class TopDocs
{
diff --git a/src/Lucene.Net/Search/TopFieldDocs.cs b/src/Lucene.Net/Search/TopFieldDocs.cs
index ac0a11449..e55066a02 100644
--- a/src/Lucene.Net/Search/TopFieldDocs.cs
+++ b/src/Lucene.Net/Search/TopFieldDocs.cs
@@ -1,5 +1,6 @@
using Lucene.Net.Support;
using System.Diagnostics.CodeAnalysis;
+using System.Threading;
namespace Lucene.Net.Search
{
@@ -22,7 +23,7 @@ namespace Lucene.Net.Search
/// <summary>
/// Represents hits returned by
- /// <see cref="IndexSearcher.Search(Query, Filter, int, Sort)"/>.
+ /// <see cref="IndexSearcher.Search(Query, Filter, int, Sort, CancellationToken)"/>.
/// </summary>
public class TopFieldDocs : TopDocs
{
diff --git a/src/Lucene.Net/Search/package.md b/src/Lucene.Net/Search/package.md
index 5f122d30f..620befab1 100644
--- a/src/Lucene.Net/Search/package.md
+++ b/src/Lucene.Net/Search/package.md
@@ -35,7 +35,7 @@ Code to search indices.
Lucene offers a wide variety of <xref:Lucene.Net.Search.Query> implementations, most of which are in this package, its subpackages ([Lucene.Net.Spans](xref:Lucene.Net.Search.Spans), [Lucene.Net.Payloads](xref:Lucene.Net.Search.Payloads)), or the [Lucene.Net.Queries module](../queries/Lucene.Net.Queries.html). These implementations can be combined in a wide variety of ways to provide complex querying capabilities along with information about where matches took place in the document colle [...]
- To perform a search, applications usually call [Search(Query, int)](xref:Lucene.Net.Search.IndexSearcher#Lucene_Net_Search_IndexSearcher_Search_Lucene_Net_Search_Query_System_Int32_) or [Search(Query, Filter, int)](xref:Lucene.Net.Search.IndexSearcher#Lucene_Net_Search_IndexSearcher_Search_Lucene_Net_Search_Query_Lucene_Net_Search_Filter_System_Int32_).
+ To perform a search, applications usually call [Search(Query, int, CancellationToken)](xref:Lucene.Net.Search.IndexSearcher#Lucene_Net_Search_IndexSearcher_Search_Lucene_Net_Search_Query_System_Int32_System_Threading_CancellationToken_) or [Search(Query, Filter, int, CancellationToken)](xref:Lucene.Net.Search.IndexSearcher#Lucene_Net_Search_IndexSearcher_Search_Lucene_Net_Search_Query_Lucene_Net_Search_Filter_System_Int32_System_Threading_CancellationToken_).
Once a Query has been created and submitted to the [IndexSearcher](xref:Lucene.Net.Search.IndexSearcher), the scoring process begins. After some infrastructure setup, control finally passes to the [Weight](xref:Lucene.Net.Search.Weight) implementation and its [Scorer](xref:Lucene.Net.Search.Scorer) or [BulkScorer](xref:Lucene.Net.Search.BulkScorer) instances. See the [Algorithm](#appendix-search-algorithm) section for more notes on the process.
diff --git a/src/Lucene.Net/Support/Threading/TaskSchedulerCompletionService.cs b/src/Lucene.Net/Support/Threading/TaskSchedulerCompletionService.cs
index 2872250bd..28ca7e708 100644
--- a/src/Lucene.Net/Support/Threading/TaskSchedulerCompletionService.cs
+++ b/src/Lucene.Net/Support/Threading/TaskSchedulerCompletionService.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Threading;
using System.Threading.Tasks;
namespace Lucene.Net.Support.Threading
@@ -31,9 +32,9 @@ public TaskSchedulerCompletionService(TaskScheduler scheduler)
this.factory = new TaskFactory<T>(scheduler ?? TaskScheduler.Default);
}
- public Task<T> Submit(Func<T> task)
+ public Task<T> Submit(Func<T> task, CancellationToken cancellationToken = default)
{
- var t = factory.StartNew(task);
+ var t = factory.StartNew(task, cancellationToken);
taskQueue.Enqueue(t);
return t;
}
diff --git a/src/Lucene.Net/overview.md b/src/Lucene.Net/overview.md
index 527793b71..8dd7e438d 100644
--- a/src/Lucene.Net/overview.md
+++ b/src/Lucene.Net/overview.md
@@ -118,7 +118,7 @@ and add documents to it with [AddDocument()](xref:Lucene.Net.Index.IndexWriter#L
to build a query from a string; and
4. Create an [IndexSearcher](xref:Lucene.Net.Search.IndexSearcher)
-and pass the query to its [Search()](xref:Lucene.Net.Search.IndexSearcher#Lucene_Net_Search_IndexSearcher_Search_Lucene_Net_Search_Query_System_Int32_)
+and pass the query to its [Search()](xref:Lucene.Net.Search.IndexSearcher#Lucene_Net_Search_IndexSearcher_Search_Lucene_Net_Search_Query_System_Int32_System_Threading_CancellationToken_)
method.
Some simple examples of code which does this are: