You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by da...@apache.org on 2018/07/25 08:33:43 UTC
[01/33] lucene-solr:jira/http2: SOLR-12553: Check local params in
SignificantTerms Query Parser
Repository: lucene-solr
Updated Branches:
refs/heads/jira/http2 3358d9366 -> 5bac295be
SOLR-12553: Check local params in SignificantTerms Query Parser
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/f6e9d00b
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/f6e9d00b
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/f6e9d00b
Branch: refs/heads/jira/http2
Commit: f6e9d00b90ac624b05586b225b9cda7eb7ea60ae
Parents: 9d3cc1e
Author: Alexandre Rafalovitch <ar...@apache.org>
Authored: Thu Jul 19 22:12:22 2018 -0400
Committer: Alexandre Rafalovitch <ar...@apache.org>
Committed: Thu Jul 19 22:12:22 2018 -0400
----------------------------------------------------------------------
solr/CHANGES.txt | 2 ++
.../solr/search/SignificantTermsQParserPlugin.java | 14 ++++++++++----
2 files changed, 12 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f6e9d00b/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 925f4aa..449f91d 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -157,6 +157,8 @@ Bug Fixes
* SOLR-12343: Fixed a bug in JSON Faceting that could cause incorrect counts/stats when using non default
sort options. This also adds a new configurable "overrefine" option. (Yonik Seeley, hossman)
+* SOLR-12553: Allow SignificantTerms Query Parser to use local parameters (Alexandre Rafalovitch)
+
Optimizations
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f6e9d00b/solr/core/src/java/org/apache/solr/search/SignificantTermsQParserPlugin.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/SignificantTermsQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/SignificantTermsQParserPlugin.java
index 93500a0..58335f1 100644
--- a/solr/core/src/java/org/apache/solr/search/SignificantTermsQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/SignificantTermsQParserPlugin.java
@@ -55,12 +55,18 @@ public class SignificantTermsQParserPlugin extends QParserPlugin {
@Override
public Query parse() throws SyntaxError {
String field = getParam("field");
- int numTerms = Integer.parseInt(params.get("numTerms", "20"));
- float minDocs = Float.parseFloat(params.get("minDocFreq", "5"));
- float maxDocs = Float.parseFloat(params.get("maxDocFreq", ".3"));
- int minTermLength = Integer.parseInt(params.get("minTermLength", "4"));
+ int numTerms = Integer.parseInt(getParamWithDefault("numTerms", "20"));
+ float minDocs = Float.parseFloat(getParamWithDefault("minDocFreq", "5"));
+ float maxDocs = Float.parseFloat(getParamWithDefault("maxDocFreq", ".3"));
+ int minTermLength = Integer.parseInt(getParamWithDefault("minTermLength", "4"));
+
return new SignificantTermsQuery(field, numTerms, minDocs, maxDocs, minTermLength);
}
+
+ private String getParamWithDefault(String paramName, String defaultValue) {
+ String result = getParam(paramName);
+ return (result != null)? result: defaultValue;
+ }
}
private static class SignificantTermsQuery extends AnalyticsQuery {
[25/33] lucene-solr:jira/http2: SOLR-12576: Update ref guide for
additional information displayed in cloud view
Posted by da...@apache.org.
SOLR-12576: Update ref guide for additional information displayed in cloud view
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/9d7aef6e
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/9d7aef6e
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/9d7aef6e
Branch: refs/heads/jira/http2
Commit: 9d7aef6e77a5be9768c7b94e905bb8adf1848c23
Parents: 6ed9607
Author: Erick Erickson <er...@apache.org>
Authored: Mon Jul 23 20:58:32 2018 -0700
Committer: Erick Erickson <er...@apache.org>
Committed: Mon Jul 23 20:58:32 2018 -0700
----------------------------------------------------------------------
solr/CHANGES.txt | 2 ++
solr/solr-ref-guide/src/cloud-screens.adoc | 14 +++++++++-----
.../src/images/cloud-screens/cloud-graph.png | Bin 54929 -> 94496 bytes
.../src/images/cloud-screens/cloud-hover.png | Bin 0 -> 83343 bytes
.../src/images/cloud-screens/cloud-radial.png | Bin 62572 -> 102878 bytes
.../src/images/cloud-screens/cloud-tree.png | Bin 105371 -> 122158 bytes
6 files changed, 11 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d7aef6e/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index e1069d8..4f6a75e 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -162,6 +162,8 @@ Bug Fixes
* SOLR-12570: OpenNLPExtractNamedEntitiesUpdateProcessor cannot support multi fields because pattern replacement
doesn't work correctly. (Koji Sekiguchi)
+* SOLR-12576: Update ref guide for additional information displayed in cloud view (Erick Erickson)
+
Optimizations
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d7aef6e/solr/solr-ref-guide/src/cloud-screens.adoc
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/cloud-screens.adoc b/solr/solr-ref-guide/src/cloud-screens.adoc
index f7d0dfb..77cf9e5 100644
--- a/solr/solr-ref-guide/src/cloud-screens.adoc
+++ b/solr/solr-ref-guide/src/cloud-screens.adoc
@@ -16,7 +16,7 @@
// specific language governing permissions and limitations
// under the License.
-When running in <<solrcloud.adoc#solrcloud,SolrCloud>> mode, a "Cloud" option will appear in the Admin UI between <<logging.adoc#logging,Logging>> and <<collections-core-admin.adoc#collections-core-admin,Collections/Core Admin>>.
+When running in <<solrcloud.adoc#solrcloud,SolrCloud>> mode, a "Cloud" option will appear in the Admin UI between <<logging.adoc#logging,Logging>> and <<collections-core-admin.adoc#collections-core-admin,Collections>>.
This screen provides status information about each collection & node in your cluster, as well as access to the low level data being stored in <<using-zookeeper-to-manage-configuration-files.adoc#using-zookeeper-to-manage-configuration-files,ZooKeeper>>.
@@ -26,18 +26,22 @@ This screen provides status information about each collection & node in your clu
The "Cloud" menu option is only available on Solr instances running in <<getting-started-with-solrcloud.adoc#getting-started-with-solrcloud,SolrCloud mode>>. Single node or master/slave replication instances of Solr will not display this option.
====
-Click on the Cloud option in the left-hand navigation, and a small sub-menu appears with options called "Tree", "Graph", "Graph (Radial)" and "Dump". The default view ("Graph") shows a graph of each collection, the shards that make up those collections, and the addresses of each replica for each shard.
+Click on the Cloud option in the left-hand navigation, and a small sub-menu appears with options called "Tree", "Graph", and "Graph (Radial)". The default view ("Graph") shows a graph of each collection, the shards that make up those collections, and the addresses and type ("NRT", "TLOG" or "PULL") of each replica for each shard.
-This example shows the very simple two-node cluster created using the `bin/solr -e cloud -noprompt` example command. In addition to the 2 shard, 2 replica "gettingstarted" collection, there is an additional "films" collection consisting of a single shard/replica:
+This example shows a simple cluster. In addition to the 2 shard, 2 replica "gettingstarted" collection, there is an additional "tlog" collection consisting of mixed TLOG and PULL replica types.
image::images/cloud-screens/cloud-graph.png[image,width=512,height=250]
+Tooltips appear when hovering over each replica giving additional information.
+
+image::images/cloud-screens/cloud-hover.png[image,width=512,height=250]
+
The "Graph (Radial)" option provides a different visual view of each node. Using the same example cluster, the radial graph view looks like:
image::images/cloud-screens/cloud-radial.png[image,width=478,height=250]
-The "Tree" option shows a directory structure of the data in ZooKeeper, including cluster wide information regarding the `live_nodes` and `overseer` status, as well as collection specific information such as the `state.json`, current shard leaders, and configuration files in use. In this example, we see the `state.json` file definition for the "films" collection:
+The "Tree" option shows a directory structure of the data in ZooKeeper, including cluster wide information regarding the `live_nodes` and `overseer` status, as well as collection specific information such as the `state.json`, current shard leaders, and configuration files in use. In this example, we see part of the `state.json` definition for the "tlog" collection:
image::images/cloud-screens/cloud-tree.png[image,width=487,height=250]
-The final option is "Dump", which returns a JSON document containing all nodes, their contents and their children (recursively). This can be used to export a snapshot of all the data that Solr has kept inside ZooKeeper and can aid in debugging SolrCloud problems.
+As an aid to debugging, the data shown in the "Tree" view can be exported locally using the following command `bin/solr zk ls -r /`
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d7aef6e/solr/solr-ref-guide/src/images/cloud-screens/cloud-graph.png
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/images/cloud-screens/cloud-graph.png b/solr/solr-ref-guide/src/images/cloud-screens/cloud-graph.png
index a1f81b2..5478cd4 100644
Binary files a/solr/solr-ref-guide/src/images/cloud-screens/cloud-graph.png and b/solr/solr-ref-guide/src/images/cloud-screens/cloud-graph.png differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d7aef6e/solr/solr-ref-guide/src/images/cloud-screens/cloud-hover.png
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/images/cloud-screens/cloud-hover.png b/solr/solr-ref-guide/src/images/cloud-screens/cloud-hover.png
new file mode 100644
index 0000000..db55ba0
Binary files /dev/null and b/solr/solr-ref-guide/src/images/cloud-screens/cloud-hover.png differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d7aef6e/solr/solr-ref-guide/src/images/cloud-screens/cloud-radial.png
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/images/cloud-screens/cloud-radial.png b/solr/solr-ref-guide/src/images/cloud-screens/cloud-radial.png
index 76f9e1e..d3b245f 100644
Binary files a/solr/solr-ref-guide/src/images/cloud-screens/cloud-radial.png and b/solr/solr-ref-guide/src/images/cloud-screens/cloud-radial.png differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d7aef6e/solr/solr-ref-guide/src/images/cloud-screens/cloud-tree.png
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/images/cloud-screens/cloud-tree.png b/solr/solr-ref-guide/src/images/cloud-screens/cloud-tree.png
index 127812a..200fb6d 100644
Binary files a/solr/solr-ref-guide/src/images/cloud-screens/cloud-tree.png and b/solr/solr-ref-guide/src/images/cloud-screens/cloud-tree.png differ
[23/33] lucene-solr:jira/http2: Fix precommit: unused
TestExportWriter imports
Posted by da...@apache.org.
Fix precommit: unused TestExportWriter imports
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/de16baaa
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/de16baaa
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/de16baaa
Branch: refs/heads/jira/http2
Commit: de16baaa2fe1767faa623d8c64f885319db512be
Parents: 877bde7
Author: Jason Gerlowski <ja...@lucidworks.com>
Authored: Mon Jul 23 20:14:58 2018 -0400
Committer: Jason Gerlowski <ja...@lucidworks.com>
Committed: Mon Jul 23 20:14:58 2018 -0400
----------------------------------------------------------------------
.../test/org/apache/solr/handler/export/TestExportWriter.java | 5 -----
1 file changed, 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/de16baaa/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
index 8b7de24..e431f47 100644
--- a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
+++ b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
@@ -31,15 +31,10 @@ import java.util.Set;
import org.apache.lucene.util.TestUtil;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrInputDocument;
-import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.util.SuppressForbidden;
import org.apache.solr.common.util.Utils;
import org.apache.solr.request.SolrQueryRequest;
-import org.apache.solr.response.ResultContext;
-import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.SchemaField;
-import org.apache.solr.search.DocIterator;
-import org.apache.solr.search.DocList;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.BeforeClass;
[09/33] lucene-solr:jira/http2: SOLR-12028: BadApple and AwaitsFix
annotations usage
Posted by da...@apache.org.
SOLR-12028: BadApple and AwaitsFix annotations usage
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/1bea1da5
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/1bea1da5
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/1bea1da5
Branch: refs/heads/jira/http2
Commit: 1bea1da5dc43d3b392c5e363c3ad970e1df6d5fc
Parents: 9d9c3a0
Author: Erick Erickson <er...@apache.org>
Authored: Fri Jul 20 13:37:05 2018 -0700
Committer: Erick Erickson <er...@apache.org>
Committed: Fri Jul 20 13:37:05 2018 -0700
----------------------------------------------------------------------
.../dataimport/TestSolrEntityProcessorEndToEnd.java | 3 ++-
.../test/org/apache/solr/cloud/MoveReplicaHDFSTest.java | 1 +
.../test/org/apache/solr/cloud/MultiThreadedOCPTest.java | 2 +-
.../test/org/apache/solr/cloud/ReplicationFactorTest.java | 1 +
.../solr/cloud/SharedFSAutoReplicaFailoverTest.java | 3 +++
.../src/test/org/apache/solr/cloud/TestCloudRecovery.java | 1 +
.../apache/solr/cloud/TestPullReplicaErrorHandling.java | 3 ++-
.../solr/cloud/TestStressCloudBlindAtomicUpdates.java | 1 +
.../cloud/api/collections/TestHdfsCloudBackupRestore.java | 2 ++
.../api/collections/TestLocalFSCloudBackupRestore.java | 2 ++
.../autoscaling/HdfsAutoAddReplicasIntegrationTest.java | 1 +
.../solr/cloud/autoscaling/ScheduledTriggerTest.java | 1 +
.../cloud/autoscaling/sim/TestSimDistributedQueue.java | 2 +-
.../cloud/autoscaling/sim/TestTriggerIntegration.java | 2 +-
.../solr/cloud/hdfs/HdfsBasicDistributedZk2Test.java | 3 +--
.../solr/cloud/hdfs/HdfsBasicDistributedZkTest.java | 3 +--
.../hdfs/HdfsTlogReplayBufferedWhileIndexingTest.java | 2 ++
.../src/test/org/apache/solr/core/TestDynamicLoading.java | 1 +
.../org/apache/solr/handler/TestReplicationHandler.java | 3 +--
.../solr/handler/admin/MetricsHistoryHandlerTest.java | 2 ++
.../hadoop/TestSolrCloudWithHadoopAuthPlugin.java | 3 +--
.../solr/update/processor/TestNamedUpdateProcessors.java | 1 +
.../solr/client/solrj/io/stream/MathExpressionTest.java | 1 +
.../solr/client/solrj/io/stream/StreamDecoratorTest.java | 1 +
.../solr/common/cloud/TestCollectionStateWatchers.java | 10 +++++-----
25 files changed, 37 insertions(+), 18 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.java
index a66b21e..858b9cc 100644
--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.java
+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.java
@@ -142,7 +142,8 @@ public class TestSolrEntityProcessorEndToEnd extends AbstractDataImportHandlerTe
instance.tearDown();
super.tearDown();
}
-
+
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void testFullImport() {
assertQ(req("*:*"), "//result[@numFound='0']");
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/MoveReplicaHDFSTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/MoveReplicaHDFSTest.java b/solr/core/src/test/org/apache/solr/cloud/MoveReplicaHDFSTest.java
index 64429fb..6c6b330 100644
--- a/solr/core/src/test/org/apache/solr/cloud/MoveReplicaHDFSTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/MoveReplicaHDFSTest.java
@@ -66,6 +66,7 @@ public class MoveReplicaHDFSTest extends MoveReplicaTest {
@Test
//2018-06-18 (commented) @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 21-May-2018
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void testNormalFailedMove() throws Exception {
inPlaceMove = false;
testFailedMove();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java b/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java
index 0a6ff40..d2e120b 100644
--- a/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java
@@ -58,7 +58,7 @@ public class MultiThreadedOCPTest extends AbstractFullDistribZkTestBase {
}
@Test
- @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
+// commented 20-July-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
@ShardsFixed(num = 4)
public void test() throws Exception {
testParallelCollectionAPICalls();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java b/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java
index acdbf9c..2a2bcc3 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java
@@ -76,6 +76,7 @@ public class ReplicationFactorTest extends AbstractFullDistribZkTestBase {
}
@Test
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void test() throws Exception {
log.info("replication factor test running");
waitForThingsToLevelOut(30000);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/SharedFSAutoReplicaFailoverTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/SharedFSAutoReplicaFailoverTest.java b/solr/core/src/test/org/apache/solr/cloud/SharedFSAutoReplicaFailoverTest.java
index 3b83bc4..64c1fc8 100644
--- a/solr/core/src/test/org/apache/solr/cloud/SharedFSAutoReplicaFailoverTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/SharedFSAutoReplicaFailoverTest.java
@@ -33,6 +33,7 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.Slow;
import com.carrotsearch.randomizedtesting.annotations.Nightly;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
@@ -77,6 +78,7 @@ import org.slf4j.LoggerFactory;
BadHdfsThreadsFilter.class // hdfs currently leaks thread(s)
})
@LogLevel("org.apache.solr.cloud.autoscaling=DEBUG;org.apache.solr.cloud.*=DEBUG")
+@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public class SharedFSAutoReplicaFailoverTest extends AbstractFullDistribZkTestBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@@ -138,6 +140,7 @@ public class SharedFSAutoReplicaFailoverTest extends AbstractFullDistribZkTestBa
@Test
@ShardsFixed(num = 4)
// 12-Jun-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void test() throws Exception {
try {
// to keep uncommitted docs during failover
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.java b/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.java
index 6b038af..955b4b8 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.java
@@ -87,6 +87,7 @@ public class TestCloudRecovery extends SolrCloudTestCase {
}
@Test
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void leaderRecoverFromLogOnStartupTest() throws Exception {
AtomicInteger countReplayLog = new AtomicInteger(0);
DirectUpdateHandler2.commitOnClose = false;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java b/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java
index dae0b4c..263f227 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java
@@ -134,7 +134,8 @@ public class TestPullReplicaErrorHandling extends SolrCloudTestCase {
}
// @Repeat(iterations=10)
- public void testCantConnectToPullReplica() throws Exception {
+@BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
+public void testCantConnectToPullReplica() throws Exception {
int numShards = 2;
CollectionAdminRequest.createCollection(collectionName, "conf", numShards, 1, 0, 1)
.setMaxShardsPerNode(1)
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java b/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java
index 489a1e3..1b4e876 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java
@@ -220,6 +220,7 @@ public class TestStressCloudBlindAtomicUpdates extends SolrCloudTestCase {
checkField(field);
}
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void test_dv_idx() throws Exception {
String field = "long_dv_idx";
checkExpectedSchemaField(map("name", field,
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
index 9029cc1..5bfed0a 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
@@ -33,6 +33,7 @@ import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
+import org.apache.lucene.util.LuceneTestCase;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.cloud.hdfs.HdfsTestUtil;
@@ -61,6 +62,7 @@ import static org.apache.solr.core.backup.BackupManager.ZK_STATE_DIR;
BadHdfsThreadsFilter.class // hdfs currently leaks thread(s)
})
//05-Jul-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 04-May-2018
+@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public class TestHdfsCloudBackupRestore extends AbstractCloudBackupRestoreTestCase {
public static final String SOLR_XML = "<solr>\n" +
"\n" +
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
index 587b9b1..f17d7d1 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
@@ -16,6 +16,7 @@
*/
package org.apache.solr.cloud.api.collections;
+import org.apache.lucene.util.LuceneTestCase;
import org.junit.BeforeClass;
/**
@@ -23,6 +24,7 @@ import org.junit.BeforeClass;
* Note that the Solr backup/restore still requires a "shared" file-system. Its just that in this case
* such file-system would be exposed via local file-system API.
*/
+@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public class TestLocalFSCloudBackupRestore extends AbstractCloudBackupRestoreTestCase {
private static String backupLocation;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/autoscaling/HdfsAutoAddReplicasIntegrationTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/HdfsAutoAddReplicasIntegrationTest.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/HdfsAutoAddReplicasIntegrationTest.java
index d508d74..260f39e 100644
--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/HdfsAutoAddReplicasIntegrationTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/HdfsAutoAddReplicasIntegrationTest.java
@@ -32,6 +32,7 @@ import org.junit.BeforeClass;
BadHdfsThreadsFilter.class, // hdfs currently leaks thread(s)
MoveReplicaHDFSTest.ForkJoinThreadsFilter.class
})
+@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public class HdfsAutoAddReplicasIntegrationTest extends AutoAddReplicasIntegrationTest {
private static MiniDFSCluster dfsCluster;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/autoscaling/ScheduledTriggerTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/ScheduledTriggerTest.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/ScheduledTriggerTest.java
index 0a22684..215c12b 100644
--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/ScheduledTriggerTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/ScheduledTriggerTest.java
@@ -57,6 +57,7 @@ public class ScheduledTriggerTest extends SolrCloudTestCase {
@Test
//2018-06-18 (commented) @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 09-Apr-2018
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void testTrigger() throws Exception {
CoreContainer container = cluster.getJettySolrRunners().get(0).getCoreContainer();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimDistributedQueue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimDistributedQueue.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimDistributedQueue.java
index 35dc1fa..bdf0737 100644
--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimDistributedQueue.java
+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimDistributedQueue.java
@@ -39,7 +39,7 @@ public class TestSimDistributedQueue extends SolrTestCaseJ4 {
protected ExecutorService executor = ExecutorUtil.newMDCAwareSingleThreadExecutor(new SolrjNamedThreadFactory("sdqtest-"));
@Test
- @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 05-Jul-2018
+// commented 20-July-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 05-Jul-2018
public void testDistributedQueue() throws Exception {
String dqZNode = "/distqueue/test1";
byte[] data = "hello world".getBytes(UTF8);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestTriggerIntegration.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestTriggerIntegration.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestTriggerIntegration.java
index 3fb528f..0a28a44 100644
--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestTriggerIntegration.java
+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestTriggerIntegration.java
@@ -269,7 +269,7 @@ public class TestTriggerIntegration extends SimSolrCloudTestCase {
}
@Test
- @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
+ // commented 20-July-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
public void testNodeLostTriggerRestoreState() throws Exception {
// for this test we want to update the trigger so we must assert that the actions were created twice
TestTriggerIntegration.actionInitCalled = new CountDownLatch(2);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZk2Test.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZk2Test.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZk2Test.java
index b1cc2fe..cfedc95 100644
--- a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZk2Test.java
+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZk2Test.java
@@ -19,7 +19,6 @@ package org.apache.solr.cloud.hdfs;
import java.io.IOException;
import org.apache.hadoop.hdfs.MiniDFSCluster;
-import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.cloud.BasicDistributedZk2Test;
import org.apache.solr.util.BadHdfsThreadsFilter;
@@ -34,7 +33,7 @@ import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;
@ThreadLeakFilters(defaultFilters = true, filters = {
BadHdfsThreadsFilter.class // hdfs currently leaks thread(s)
})
-@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 26-Mar-2018
+// commented 20-July-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 26-Mar-2018
public class HdfsBasicDistributedZk2Test extends BasicDistributedZk2Test {
private static MiniDFSCluster dfsCluster;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZkTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZkTest.java
index cfd11ea..380916a 100644
--- a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZkTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZkTest.java
@@ -19,7 +19,6 @@ package org.apache.solr.cloud.hdfs;
import java.io.IOException;
import org.apache.hadoop.hdfs.MiniDFSCluster;
-import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.cloud.BasicDistributedZkTest;
import org.apache.solr.util.BadHdfsThreadsFilter;
@@ -35,7 +34,7 @@ import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;
@ThreadLeakFilters(defaultFilters = true, filters = {
BadHdfsThreadsFilter.class // hdfs currently leaks thread(s)
})
-@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
+// commented 20-July-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
public class HdfsBasicDistributedZkTest extends BasicDistributedZkTest {
private static MiniDFSCluster dfsCluster;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsTlogReplayBufferedWhileIndexingTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsTlogReplayBufferedWhileIndexingTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsTlogReplayBufferedWhileIndexingTest.java
index 6cb85c9..d5015a3 100644
--- a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsTlogReplayBufferedWhileIndexingTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsTlogReplayBufferedWhileIndexingTest.java
@@ -19,6 +19,7 @@ package org.apache.solr.cloud.hdfs;
import java.io.IOException;
import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.cloud.TlogReplayBufferedWhileIndexingTest;
import org.apache.solr.util.BadHdfsThreadsFilter;
@@ -31,6 +32,7 @@ import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;
@Slow
@Nightly
// 12-Jun-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
+@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
@ThreadLeakFilters(defaultFilters = true, filters = {
BadHdfsThreadsFilter.class // hdfs currently leaks thread(s)
})
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/core/TestDynamicLoading.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/TestDynamicLoading.java b/solr/core/src/test/org/apache/solr/core/TestDynamicLoading.java
index d9d1834..add08f4 100644
--- a/solr/core/src/test/org/apache/solr/core/TestDynamicLoading.java
+++ b/solr/core/src/test/org/apache/solr/core/TestDynamicLoading.java
@@ -46,6 +46,7 @@ public class TestDynamicLoading extends AbstractFullDistribZkTestBase {
@Test
// 12-Jun-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void testDynamicLoading() throws Exception {
System.setProperty("enable.runtime.lib", "true");
setupRestTestHarnesses();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
index 20e1089..e5d2a16 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
@@ -42,7 +42,6 @@ import java.util.concurrent.TimeUnit;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
-import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.lucene.util.TestUtil;
import org.apache.solr.BaseDistributedSearchTestCase;
@@ -87,7 +86,7 @@ import org.slf4j.LoggerFactory;
*/
@Slow
@SuppressSSL // Currently unknown why SSL does not work with this test
-@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
+// commented 20-July-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
public class TestReplicationHandler extends SolrTestCaseJ4 {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/handler/admin/MetricsHistoryHandlerTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/handler/admin/MetricsHistoryHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/MetricsHistoryHandlerTest.java
index 7c84c16..dfdecc2 100644
--- a/solr/core/src/test/org/apache/solr/handler/admin/MetricsHistoryHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/admin/MetricsHistoryHandlerTest.java
@@ -21,6 +21,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.apache.lucene.util.LuceneTestCase;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.cloud.SolrCloudManager;
import org.apache.solr.client.solrj.cloud.autoscaling.AutoScalingConfig;
@@ -44,6 +45,7 @@ import org.rrd4j.core.RrdDb;
*
*/
@LogLevel("org.apache.solr.cloud=DEBUG")
+@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public class MetricsHistoryHandlerTest extends SolrCloudTestCase {
private static SolrCloudManager cloudManager;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.java b/solr/core/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.java
index 52a323f..118dc47 100644
--- a/solr/core/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.java
+++ b/solr/core/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithHadoopAuthPlugin.java
@@ -21,7 +21,6 @@ import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.util.Constants;
-import org.apache.lucene.util.LuceneTestCase;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
@@ -34,7 +33,7 @@ import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
-@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
+// commented 20-July-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
public class TestSolrCloudWithHadoopAuthPlugin extends SolrCloudTestCase {
protected static final int NUM_SERVERS = 1;
protected static final int NUM_SHARDS = 1;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/core/src/test/org/apache/solr/update/processor/TestNamedUpdateProcessors.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/update/processor/TestNamedUpdateProcessors.java b/solr/core/src/test/org/apache/solr/update/processor/TestNamedUpdateProcessors.java
index 41ed9c7..ea77235 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/TestNamedUpdateProcessors.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/TestNamedUpdateProcessors.java
@@ -44,6 +44,7 @@ import org.junit.Test;
public class TestNamedUpdateProcessors extends AbstractFullDistribZkTestBase {
@Test
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void test() throws Exception {
System.setProperty("enable.runtime.lib", "true");
setupRestTestHarnesses();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/MathExpressionTest.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/MathExpressionTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/MathExpressionTest.java
index ab2b876..fe782b2 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/MathExpressionTest.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/MathExpressionTest.java
@@ -1429,6 +1429,7 @@ public class MathExpressionTest extends SolrCloudTestCase {
@Test
// 12-Jun-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
+ @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void testDistributions() throws Exception {
String cexpr = "let(a=normalDistribution(10, 2), " +
"b=sample(a, 250), " +
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/StreamDecoratorTest.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/StreamDecoratorTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/StreamDecoratorTest.java
index a2412df..2726739 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/StreamDecoratorTest.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/StreamDecoratorTest.java
@@ -66,6 +66,7 @@ import org.junit.Test;
@Slow
@LuceneTestCase.SuppressCodecs({"Lucene3x", "Lucene40","Lucene41","Lucene42","Lucene45"})
+@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public class StreamDecoratorTest extends SolrCloudTestCase {
private static final String COLLECTIONORALIAS = "collection1";
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1bea1da5/solr/solrj/src/test/org/apache/solr/common/cloud/TestCollectionStateWatchers.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/test/org/apache/solr/common/cloud/TestCollectionStateWatchers.java b/solr/solrj/src/test/org/apache/solr/common/cloud/TestCollectionStateWatchers.java
index 9fdeffb..c08c5b7 100644
--- a/solr/solrj/src/test/org/apache/solr/common/cloud/TestCollectionStateWatchers.java
+++ b/solr/solrj/src/test/org/apache/solr/common/cloud/TestCollectionStateWatchers.java
@@ -146,7 +146,7 @@ public class TestCollectionStateWatchers extends SolrCloudTestCase {
}
@Test
- @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
+ // commented 20-July-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
public void testStateWatcherChecksCurrentStateOnRegister() throws Exception {
CloudSolrClient client = cluster.getSolrClient();
@@ -198,7 +198,7 @@ public class TestCollectionStateWatchers extends SolrCloudTestCase {
}
@Test
- @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
+ // commented 20-July-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
public void testCanWaitForNonexistantCollection() throws Exception {
Future<Boolean> future = waitInBackground("delayed", MAX_WAIT_TIMEOUT, TimeUnit.SECONDS,
@@ -212,7 +212,7 @@ public class TestCollectionStateWatchers extends SolrCloudTestCase {
}
@Test
- @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
+ // commented 20-July-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
public void testPredicateFailureTimesOut() throws Exception {
CloudSolrClient client = cluster.getSolrClient();
expectThrows(TimeoutException.class, () -> {
@@ -258,7 +258,7 @@ public class TestCollectionStateWatchers extends SolrCloudTestCase {
}
@Test
- @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
+ // commented 20-July-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 12-Jun-2018
public void testWatcherIsRemovedAfterTimeout() throws Exception {
CloudSolrClient client = cluster.getSolrClient();
assertTrue("There should be no watchers for a non-existent collection!",
@@ -274,7 +274,7 @@ public class TestCollectionStateWatchers extends SolrCloudTestCase {
}
@Test
- @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 09-Apr-2018
+ // commented 20-July-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 09-Apr-2018
public void testDeletionsTriggerWatches() throws Exception {
CollectionAdminRequest.createCollection("tobedeleted", "config", 1, 1)
.process(cluster.getSolrClient());
[05/33] lucene-solr:jira/http2: LUCENE-8418: Mute LatLonShape
polygonWithHole test until fix is applied
Posted by da...@apache.org.
LUCENE-8418: Mute LatLonShape polygonWithHole test until fix is applied
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/509561bf
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/509561bf
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/509561bf
Branch: refs/heads/jira/http2
Commit: 509561bf2a9effe4fce19551c9ec037975cf9c02
Parents: 20a7ee9
Author: Nicholas Knize <nk...@gmail.com>
Authored: Fri Jul 20 11:18:58 2018 -0500
Committer: Nicholas Knize <nk...@gmail.com>
Committed: Fri Jul 20 11:36:47 2018 -0500
----------------------------------------------------------------------
.../apache/lucene/document/TestLatLonShape.java | 37 ++++++++++++++------
1 file changed, 26 insertions(+), 11 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/509561bf/lucene/sandbox/src/test/org/apache/lucene/document/TestLatLonShape.java
----------------------------------------------------------------------
diff --git a/lucene/sandbox/src/test/org/apache/lucene/document/TestLatLonShape.java b/lucene/sandbox/src/test/org/apache/lucene/document/TestLatLonShape.java
index d0a4b32..ac11e1b 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/document/TestLatLonShape.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/document/TestLatLonShape.java
@@ -81,21 +81,12 @@ public class TestLatLonShape extends LuceneTestCase {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- // add a random polygon without a hole
+ // add a random polygon
Polygon p = GeoTestUtil.createRegularPolygon(0, 90, atLeast(1000000), numVertices);
Document document = new Document();
addPolygonsToDoc(FIELDNAME, document, p);
writer.addDocument(document);
- // add a random polygon with a hole
- Polygon inner = new Polygon(new double[] {-1d, -1d, 1d, 1d, -1d},
- new double[] {-91d, -89d, -89d, -91.0, -91.0});
- Polygon outer = GeoTestUtil.createRegularPolygon(0, -90, atLeast(1000000), numVertices);
-
- document = new Document();
- addPolygonsToDoc(FIELDNAME, document, new Polygon(outer.getPolyLats(), outer.getPolyLons(), inner));
- writer.addDocument(document);
-
////// search /////
// search an intersecting bbox
IndexReader reader = writer.getReader();
@@ -108,8 +99,32 @@ public class TestLatLonShape extends LuceneTestCase {
q = newRectQuery(FIELDNAME, p.minLat-1d, p.minLat+1, p.minLon-1d, p.minLon+1d);
assertEquals(0, searcher.count(q));
+ IOUtils.close(reader, dir);
+ }
+
+ @AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/LUCENE-8418")
+ /** test random polygons with a single hole */
+ public void testPolygonWithHole() throws Exception {
+ int numVertices = TestUtil.nextInt(random(), 50, 100);
+ Directory dir = newDirectory();
+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
+
+ // add a random polygon with a hole
+ Polygon inner = new Polygon(new double[] {-1d, -1d, 1d, 1d, -1d},
+ new double[] {-91d, -89d, -89d, -91.0, -91.0});
+ Polygon outer = GeoTestUtil.createRegularPolygon(0, -90, atLeast(1000000), numVertices);
+
+ Document document = new Document();
+ addPolygonsToDoc(FIELDNAME, document, new Polygon(outer.getPolyLats(), outer.getPolyLons(), inner));
+ writer.addDocument(document);
+
+ ///// search //////
+ IndexReader reader = writer.getReader();
+ writer.close();
+ IndexSearcher searcher = newSearcher(reader);
+
// search a bbox in the hole
- q = newRectQuery(FIELDNAME, inner.minLat + 1e-6, inner.maxLat - 1e-6, inner.minLon + 1e-6, inner.maxLon - 1e-6);
+ Query q = newRectQuery(FIELDNAME, inner.minLat + 1e-6, inner.maxLat - 1e-6, inner.minLon + 1e-6, inner.maxLon - 1e-6);
assertEquals(0, searcher.count(q));
IOUtils.close(reader, dir);
[10/33] lucene-solr:jira/http2: SOLR-12489: Fix test failures
Posted by da...@apache.org.
SOLR-12489: Fix test failures
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/18c29b73
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/18c29b73
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/18c29b73
Branch: refs/heads/jira/http2
Commit: 18c29b7303a96faeb125dee8a29b210539d23194
Parents: 1bea1da
Author: Varun Thacker <va...@apache.org>
Authored: Sat Jul 21 13:05:07 2018 -0700
Committer: Varun Thacker <va...@apache.org>
Committed: Sat Jul 21 13:05:07 2018 -0700
----------------------------------------------------------------------
.../AbstractCloudBackupRestoreTestCase.java | 20 +++++++++-----------
.../collections/TestHdfsCloudBackupRestore.java | 1 -
.../TestLocalFSCloudBackupRestore.java | 1 -
3 files changed, 9 insertions(+), 13 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/18c29b73/solr/core/src/test/org/apache/solr/cloud/api/collections/AbstractCloudBackupRestoreTestCase.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/AbstractCloudBackupRestoreTestCase.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/AbstractCloudBackupRestoreTestCase.java
index cdfd224..a78be03 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/AbstractCloudBackupRestoreTestCase.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/AbstractCloudBackupRestoreTestCase.java
@@ -58,6 +58,7 @@ public abstract class AbstractCloudBackupRestoreTestCase extends SolrCloudTestCa
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
protected static final int NUM_SHARDS = 2;//granted we sometimes shard split to get more
+ protected static final int NUM_SPLIT_SHARDS = 3; //We always split shard1 so total shards post split will be 3
int replFactor;
int numTlogReplicas;
@@ -102,12 +103,12 @@ public abstract class AbstractCloudBackupRestoreTestCase extends SolrCloudTestCa
if (random().nextBoolean()) {
create.setMaxShardsPerNode(-1);
+ } else if (doSplitShardOperation) {
+ create.setMaxShardsPerNode((int) Math.ceil(NUM_SPLIT_SHARDS * backupReplFactor / (double) cluster.getJettySolrRunners().size()));
} else if (NUM_SHARDS * (backupReplFactor) > cluster.getJettySolrRunners().size() || random().nextBoolean()) {
- create.setMaxShardsPerNode((int)Math.ceil(NUM_SHARDS * backupReplFactor / (double) cluster.getJettySolrRunners().size()));//just to assert it survives the restoration
- if (doSplitShardOperation) {
- create.setMaxShardsPerNode(create.getMaxShardsPerNode() * 2);
- }
+ create.setMaxShardsPerNode((int) Math.ceil(NUM_SHARDS * backupReplFactor / (double) cluster.getJettySolrRunners().size()));//just to assert it survives the restoration
}
+
if (random().nextBoolean()) {
create.setAutoAddReplicas(true);//just to assert it survives the restoration
}
@@ -293,12 +294,9 @@ public abstract class AbstractCloudBackupRestoreTestCase extends SolrCloudTestCa
}
if (rarely()) { // Try with createNodeSet configuration
- int nodeSetSize = cluster.getJettySolrRunners().size() / 2;
- List<String> nodeStrs = new ArrayList<>(nodeSetSize);
+ List<String> nodeStrs = new ArrayList<>(1);//Always 1 as cluster.getJettySolrRunners().size()=NUM_SHARDS=2
Iterator<JettySolrRunner> iter = cluster.getJettySolrRunners().iterator();
- for (int i = 0; i < nodeSetSize ; i++) {
- nodeStrs.add(iter.next().getNodeName());
- }
+ nodeStrs.add(iter.next().getNodeName());
restore.setCreateNodeSet(String.join(",", nodeStrs));
restore.setCreateNodeSetShuffle(usually());
// we need to double maxShardsPerNode value since we reduced number of available nodes by half.
@@ -307,8 +305,8 @@ public abstract class AbstractCloudBackupRestoreTestCase extends SolrCloudTestCa
computeRestoreMaxShardsPerNode = restore.getMaxShardsPerNode() * 2;
restore.setMaxShardsPerNode(computeRestoreMaxShardsPerNode);
} else {
- computeRestoreMaxShardsPerNode = origShardToDocCount.size() * 2;
- restore.setMaxShardsPerNode(origShardToDocCount.size() * 2);
+ computeRestoreMaxShardsPerNode = origShardToDocCount.size() * backupReplFactor;
+ restore.setMaxShardsPerNode(origShardToDocCount.size() * backupReplFactor);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/18c29b73/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
index 5bfed0a..d656f52 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
@@ -62,7 +62,6 @@ import static org.apache.solr.core.backup.BackupManager.ZK_STATE_DIR;
BadHdfsThreadsFilter.class // hdfs currently leaks thread(s)
})
//05-Jul-2018 @LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 04-May-2018
-@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public class TestHdfsCloudBackupRestore extends AbstractCloudBackupRestoreTestCase {
public static final String SOLR_XML = "<solr>\n" +
"\n" +
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/18c29b73/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
index f17d7d1..514b9b9 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
@@ -24,7 +24,6 @@ import org.junit.BeforeClass;
* Note that the Solr backup/restore still requires a "shared" file-system. Its just that in this case
* such file-system would be exposed via local file-system API.
*/
-@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public class TestLocalFSCloudBackupRestore extends AbstractCloudBackupRestoreTestCase {
private static String backupLocation;
[27/33] lucene-solr:jira/http2: LUCENE-8415: Clean up Directory
contracts (write-once,
no reads-before-write-completed). Minor test improvements and cleanups.
Posted by da...@apache.org.
LUCENE-8415: Clean up Directory contracts (write-once, no reads-before-write-completed). Minor test improvements and cleanups.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/8892c0d9
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/8892c0d9
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/8892c0d9
Branch: refs/heads/jira/http2
Commit: 8892c0d9aff9e8b7a6722a50a18908ef575276da
Parents: 9d7aef6
Author: Dawid Weiss <dw...@apache.org>
Authored: Tue Jul 24 08:47:50 2018 +0200
Committer: Dawid Weiss <dw...@apache.org>
Committed: Tue Jul 24 08:47:50 2018 +0200
----------------------------------------------------------------------
lucene/CHANGES.txt | 2 +
.../java/org/apache/lucene/store/Directory.java | 194 +-
.../org/apache/lucene/store/IndexOutput.java | 13 +-
.../apache/lucene/index/TestIndexWriter.java | 16 +-
.../org/apache/lucene/util/bkd/TestBKD.java | 7 +-
.../org/apache/lucene/mockfile/ExtrasFS.java | 18 +-
.../lucene/store/BaseDirectoryTestCase.java | 1652 +++++++++---------
.../lucene/store/MockDirectoryWrapper.java | 40 +-
.../org/apache/lucene/util/LuceneTestCase.java | 33 +
.../lucene/store/TestMockDirectoryWrapper.java | 9 +-
10 files changed, 1005 insertions(+), 979 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 730e24c..e324f2c 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -202,6 +202,8 @@ Improvements
* LUCENE-8345, GitHub PR #392: Remove instantiation of redundant wrapper classes for primitives;
add wrapper class constructors to forbiddenapis. (Michael Braun via Uwe Schindler)
+* LUCENE-8415: Clean up Directory contracts and JavaDoc comments. (Dawid Weiss)
+
Other:
* LUCENE-8366: Upgrade to ICU 62.1. Emoji handling now uses Unicode 11's
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/core/src/java/org/apache/lucene/store/Directory.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/store/Directory.java b/lucene/core/src/java/org/apache/lucene/store/Directory.java
index 0c6101d..505be7f 100644
--- a/lucene/core/src/java/org/apache/lucene/store/Directory.java
+++ b/lucene/core/src/java/org/apache/lucene/store/Directory.java
@@ -27,102 +27,139 @@ import java.util.Set;
import org.apache.lucene.util.IOUtils;
-/** A Directory is a flat list of files. Files may be written once, when they
- * are created. Once a file is created it may only be opened for read, or
- * deleted. Random access is permitted both when reading and writing.
+/**
+ * A {@code Directory} provides an abstraction layer for storing a
+ * list of files. A directory contains only files (no sub-folder hierarchy).
*
- * <p> Java's i/o APIs not used directly, but rather all i/o is
- * through this API. This permits things such as: <ul>
- * <li> implementation of RAM-based indices;
- * <li> implementation indices stored in a database, via JDBC;
- * <li> implementation of an index as a single file;
- * </ul>
+ * Implementing classes must comply with the following:
*
- * Directory locking is implemented by an instance of {@link
- * LockFactory}.
+ * <ul>
+ * <li>A file in a directory can be created ({@link #createOutput}), appended
+ * to, then closed.</li>
+ * <li>A file open for writing may not be available
+ * for read access until the corresponding {@link IndexOutput} is closed.</li>
+ * <li>Once a file is created it must only be opened for input ({@link #openInput}), or
+ * deleted ({@link #deleteFile}). Calling {@link #createOutput} on an existing file
+ * must throw {@link java.nio.file.FileAlreadyExistsException}.</li>
+ * </ul>
*
+ * @see FSDirectory
+ * @see RAMDirectory
+ * @see FilterDirectory
*/
public abstract class Directory implements Closeable {
-
/**
- * Returns an array of strings, one for each entry in the directory, in sorted (UTF16, java's String.compare) order.
+ * Returns names of all files stored in this directory.
+ * The output must be in sorted (UTF-16, java's {@link String#compareTo}) order.
*
- * @throws IOException in case of IO error
+ * @throws IOException in case of I/O error
*/
public abstract String[] listAll() throws IOException;
- /** Removes an existing file in the directory. */
+ /**
+ * Removes an existing file in the directory.
+ *
+ * This method must throw either {@link NoSuchFileException} or {@link FileNotFoundException}
+ * if {@code name} points to a non-existing file.
+ *
+ * @param name the name of an existing file.
+ * @throws IOException in case of I/O error
+ */
public abstract void deleteFile(String name) throws IOException;
/**
- * Returns the length of a file in the directory. This method follows the
- * following contract:
- * <ul>
- * <li>Throws {@link FileNotFoundException} or {@link NoSuchFileException}
- * if the file does not exist.
- * <li>Returns a value ≥0 if the file exists, which specifies its length.
- * </ul>
- *
- * @param name the name of the file for which to return the length.
- * @throws IOException if there was an IO error while retrieving the file's
- * length.
+ * Returns the byte length of a file in the directory.
+ *
+ * This method must throw either {@link NoSuchFileException} or {@link FileNotFoundException}
+ * if {@code name} points to a non-existing file.
+ *
+ * @param name the name of an existing file.
+ * @throws IOException in case of I/O error
*/
public abstract long fileLength(String name) throws IOException;
- /** Creates a new, empty file in the directory with the given name.
- Returns a stream writing this file. */
+ /**
+ * Creates a new, empty file in the directory and returns an {@link IndexOutput}
+ * instance for appending data to this file.
+ *
+ * This method must throw {@link java.nio.file.FileAlreadyExistsException} if the file
+ * already exists.
+ *
+ * @param name the name of the file to create.
+ * @throws IOException in case of I/O error
+ */
public abstract IndexOutput createOutput(String name, IOContext context) throws IOException;
- /** Creates a new, empty file for writing in the directory, with a
- * temporary file name including prefix and suffix, ending with the
- * reserved extension <code>.tmp</code>. Use
- * {@link IndexOutput#getName} to see what name was used. */
+ /**
+ * Creates a new, empty, temporary file in the directory and returns an {@link IndexOutput}
+ * instance for appending data to this file.
+ *
+ * The temporary file name (accessible via {@link IndexOutput#getName()}) will start with
+ * {@code prefix}, end with {@code suffix} and have a reserved file extension {@code .tmp}.
+ */
public abstract IndexOutput createTempOutput(String prefix, String suffix, IOContext context) throws IOException;
/**
- * Ensure that any writes to these files are moved to
- * stable storage. Lucene uses this to properly commit
- * changes to the index, to prevent a machine/OS crash
+ * Ensures that any writes to these files are moved to
+ * stable storage (made durable).
+ *
+ * Lucene uses this to properly commit changes to the index, to prevent a machine/OS crash
* from corrupting the index.
- * <br>
- * NOTE: Clients may call this method for same files over
- * and over again, so some impls might optimize for that.
- * For other impls the operation can be a noop, for various
- * reasons.
+ *
+ * @see #syncMetaData()
*/
public abstract void sync(Collection<String> names) throws IOException;
-
+
/**
- * Renames {@code source} to {@code dest} as an atomic operation,
- * where {@code dest} does not yet exist in the directory.
- * <p>
- * Notes: This method is used by IndexWriter to publish commits.
- * It is ok if this operation is not truly atomic, for example
- * both {@code source} and {@code dest} can be visible temporarily.
- * It is just important that the contents of {@code dest} appear
- * atomically, or an exception is thrown.
+ * Ensures that directory metadata, such as recent file renames, are moved to stable
+ * storage.
+ *
+ * @see #sync(Collection)
*/
- public abstract void rename(String source, String dest) throws IOException;
+ public abstract void syncMetaData() throws IOException;
/**
- * Ensure that directory metadata, such as recent file renames, are made
- * durable.
+ * Renames {@code source} file to {@code dest} file where
+ * {@code dest} must not already exist in the directory.
+ *
+ * It is permitted for this operation to not be truly atomic, for example
+ * both {@code source} and {@code dest} can be visible temporarily in {@link #listAll()}.
+ * However, the implementation of this method must ensure the content of
+ * {@code dest} appears as the entire {@code source} atomically. So once
+ * {@code dest} is visible for readers, the entire content of previous {@code source}
+ * is visible.
+ *
+ * This method is used by IndexWriter to publish commits.
*/
- public abstract void syncMetaData() throws IOException;
-
- /** Returns a stream reading an existing file.
- * <p>Throws {@link FileNotFoundException} or {@link NoSuchFileException}
- * if the file does not exist.
+ public abstract void rename(String source, String dest) throws IOException;
+
+ /**
+ * Opens a stream for reading an existing file.
+ *
+ * This method must throw either {@link NoSuchFileException} or {@link FileNotFoundException}
+ * if {@code name} points to a non-existing file.
+ *
+ * @param name the name of an existing file.
+ * @throws IOException in case of I/O error
*/
public abstract IndexInput openInput(String name, IOContext context) throws IOException;
- /** Returns a stream reading an existing file, computing checksum as it reads */
+ /**
+ * Opens a checksum-computing stream for reading an existing file.
+ *
+ * This method must throw either {@link NoSuchFileException} or {@link FileNotFoundException}
+ * if {@code name} points to a non-existing file.
+ *
+ * @param name the name of an existing file.
+ * @throws IOException in case of I/O error
+ */
public ChecksumIndexInput openChecksumInput(String name, IOContext context) throws IOException {
return new BufferedChecksumIndexInput(openInput(name, context));
}
/**
- * Returns an obtained {@link Lock}.
+ * Acquires and returns a {@link Lock} for a file with the given name.
+ *
* @param name the name of the lock file
* @throws LockObtainFailedException (optional specific exception) if the lock could
* not be obtained because it is currently held elsewhere.
@@ -130,31 +167,15 @@ public abstract class Directory implements Closeable {
*/
public abstract Lock obtainLock(String name) throws IOException;
- /** Closes the store. */
+ /**
+ * Closes the directory.
+ */
@Override
public abstract void close() throws IOException;
- @Override
- public String toString() {
- return getClass().getSimpleName() + '@' + Integer.toHexString(hashCode());
- }
-
/**
- * Copies the file <i>src</i> in <i>from</i> to this directory under the new
- * file name <i>dest</i>.
- * <p>
- * If you want to copy the entire source directory to the destination one, you
- * can do so like this:
- *
- * <pre class="prettyprint">
- * Directory to; // the directory to copy to
- * for (String file : dir.listAll()) {
- * to.copyFrom(dir, file, newFile, IOContext.DEFAULT); // newFile can be either file, or a new name
- * }
- * </pre>
- * <p>
- * <b>NOTE:</b> this method does not check whether <i>dest</i> exist and will
- * overwrite it if it does.
+ * Copies an existing {@code src} file from directory {@code from}
+ * to a non-existent file {@code dest} in this directory.
*/
public void copyFrom(Directory from, String src, String dest, IOContext context) throws IOException {
boolean success = false;
@@ -169,14 +190,21 @@ public abstract class Directory implements Closeable {
}
}
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + '@' + Integer.toHexString(hashCode());
+ }
+
/**
- * @throws AlreadyClosedException if this Directory is closed
+ * Ensures this directory is still open.
+ *
+ * @throws AlreadyClosedException if this directory is closed.
*/
protected void ensureOpen() throws AlreadyClosedException {}
/**
- * Returns the current pending deletions in this directory or an emtpy set
- * if there are no known pending deletions.
+ * Returns a set of files currently pending deletion in this directory.
+ *
* @lucene.internal
*/
public Set<String> getPendingDeletions() throws IOException {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/core/src/java/org/apache/lucene/store/IndexOutput.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/store/IndexOutput.java b/lucene/core/src/java/org/apache/lucene/store/IndexOutput.java
index e4881e0..14b843f 100644
--- a/lucene/core/src/java/org/apache/lucene/store/IndexOutput.java
+++ b/lucene/core/src/java/org/apache/lucene/store/IndexOutput.java
@@ -20,17 +20,16 @@ package org.apache.lucene.store;
import java.io.Closeable;
import java.io.IOException;
-/** Abstract base class for output to a file in a Directory. A random-access
- * output stream. Used for all Lucene index output operations.
-
- * <p>{@code IndexOutput} may only be used from one thread, because it is not
- * thread safe (it keeps internal state like file position).
-
+/**
+ * A {@link DataOutput} for appending data to a file in a {@link Directory}.
+ *
+ * Instances of this class are <b>not</b> thread-safe.
+ *
* @see Directory
* @see IndexInput
*/
public abstract class IndexOutput extends DataOutput implements Closeable {
-
+
/** Full description of this output, e.g. which class such as {@code FSIndexOutput}, and the full path to the file */
private final String resourceDescription;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
index 8e6de47..31740f9 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
@@ -68,6 +68,7 @@ import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
+import org.apache.lucene.mockfile.ExtrasFS;
import org.apache.lucene.mockfile.FilterPath;
import org.apache.lucene.mockfile.WindowsFS;
import org.apache.lucene.search.DocIdSetIterator;
@@ -2730,7 +2731,7 @@ public class TestIndexWriter extends LuceneTestCase {
IndexWriter w = new IndexWriter(dir, iwc);
w.commit();
reader = w.getReader();
- // we pull this commit to open it again later to check that we fail if a futur file delete is pending
+ // we pull this commit to open it again later to check that we fail if a future file delete is pending
indexCommit = reader.getIndexCommit();
w.close();
w = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random())).setIndexDeletionPolicy(NoDeletionPolicy.INSTANCE));
@@ -2740,7 +2741,7 @@ public class TestIndexWriter extends LuceneTestCase {
dir.deleteFile("segments_2");
assertTrue(dir.getPendingDeletions().size() > 0);
- // make sure we get NFSF if we try to delete and already-pending-delete file:
+ // make sure we get NoSuchFileException if we try to delete and already-pending-delete file:
expectThrows(NoSuchFileException.class, () -> {
dir.deleteFile("segments_2");
});
@@ -2777,7 +2778,7 @@ public class TestIndexWriter extends LuceneTestCase {
assertTrue(dir.getPendingDeletions().size() > 0);
- // make sure we get NFSF if we try to delete and already-pending-delete file:
+ // make sure we get NoSuchFileException if we try to delete and already-pending-delete file:
expectThrows(NoSuchFileException.class, () -> {
dir.deleteFile("segments_1");
});
@@ -3348,12 +3349,11 @@ public class TestIndexWriter extends LuceneTestCase {
private static void assertFiles(IndexWriter writer) throws IOException {
Predicate<String> filter = file -> file.startsWith("segments") == false && file.equals("write.lock") == false;
// remove segment files we don't know if we have committed and what is kept around
- Set<String> segFiles = new HashSet<>(writer.segmentInfos.files(true)).stream()
+ Set<String> segFiles = writer.segmentInfos.files(true).stream()
+ .filter(filter).collect(Collectors.toSet());
+ Set<String> dirFiles = Arrays.stream(writer.getDirectory().listAll())
+ .filter(file -> !ExtrasFS.isExtra(file)) // ExtraFS might add an files, ignore them
.filter(filter).collect(Collectors.toSet());
- Set<String> dirFiles = new HashSet<>(Arrays.asList(writer.getDirectory().listAll()))
- .stream().filter(filter).collect(Collectors.toSet());
- // ExtraFS might add an extra0 file, ignore it
- dirFiles.remove("extra0");
assertEquals(segFiles.size(), dirFiles.size());
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.java b/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.java
index b9dad6f..3cf248b 100644
--- a/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.java
+++ b/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.java
@@ -29,6 +29,7 @@ import org.apache.lucene.index.MergeState;
import org.apache.lucene.index.PointValues.IntersectVisitor;
import org.apache.lucene.index.PointValues.Relation;
import org.apache.lucene.index.PointValues;
+import org.apache.lucene.mockfile.ExtrasFS;
import org.apache.lucene.store.CorruptingIndexOutput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FilterDirectory;
@@ -414,8 +415,10 @@ public class TestBKD extends LuceneTestCase {
}
}
- String[] files = dir.listAll();
- assertTrue("files=" + Arrays.toString(files), files.length == 0 || Arrays.equals(files, new String[] {"extra0"}));
+ String[] files = Arrays.stream(dir.listAll())
+ .filter(file -> !ExtrasFS.isExtra(file))
+ .toArray(String[]::new);
+ assertTrue("files=" + Arrays.toString(files), files.length == 0);
dir.close();
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/test-framework/src/java/org/apache/lucene/mockfile/ExtrasFS.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/mockfile/ExtrasFS.java b/lucene/test-framework/src/java/org/apache/lucene/mockfile/ExtrasFS.java
index 28fc44f..f8bba9c 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/mockfile/ExtrasFS.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/mockfile/ExtrasFS.java
@@ -29,11 +29,15 @@ import java.nio.file.attribute.FileAttribute;
* create special files themselves (.DS_Store, thumbs.db, .nfsXXX, ...),
* so we add them and see what breaks.
* <p>
- * When a directory is created, sometimes a file or directory named
- * "extra0" will be included with it.
- * All other filesystem operations are passed thru as normal.
+ * When a directory is created, sometimes an "extra" file or directory
+ * will be included with it (use {@link #isExtra(String)} to check if it's one
+ * of those files).
+ *
+ * All other filesystem operations are delegated as normal.
*/
public class ExtrasFS extends FilterFileSystemProvider {
+ private final static String EXTRA_FILE_NAME = "extra0";
+
final boolean active;
final boolean createDirectory;
@@ -57,7 +61,7 @@ public class ExtrasFS extends FilterFileSystemProvider {
if (active) {
// lets add a bogus file... if this fails, we don't care, its best effort.
try {
- Path target = dir.resolve("extra0");
+ Path target = dir.resolve(EXTRA_FILE_NAME);
if (createDirectory) {
super.createDirectory(target);
} else {
@@ -73,4 +77,10 @@ public class ExtrasFS extends FilterFileSystemProvider {
// our fake files. But this is tricky because its hooked into several places.
// Currently MDW has a hack so we don't break disk full tests.
+ /**
+ * @return Return true if {@code fileName} is one of the extra files added by this class.
+ */
+ public static boolean isExtra(String fileName) {
+ return fileName.equals(EXTRA_FILE_NAME);
+ }
}
[06/33] lucene-solr:jira/http2: SOLR-11598: Support more than 4 sort
fields in the export writer
Posted by da...@apache.org.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/test/org/apache/solr/response/TestExportWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/response/TestExportWriter.java b/solr/core/src/test/org/apache/solr/response/TestExportWriter.java
deleted file mode 100644
index 278ef99..0000000
--- a/solr/core/src/test/org/apache/solr/response/TestExportWriter.java
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.solr.response;
-
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.common.SolrInputDocument;
-import org.apache.solr.common.util.SuppressForbidden;
-import org.apache.solr.common.util.Utils;
-import org.apache.solr.schema.SchemaField;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class TestExportWriter extends SolrTestCaseJ4 {
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- System.setProperty("export.test", "true");
- initCore("solrconfig-sortingresponse.xml","schema-sortingresponse.xml");
- }
-
- @Before
- @Override
- public void setUp() throws Exception {
- super.setUp();
- assertU(delQ("*:*"));
- assertU(commit());
- createIndex();
- }
-
- public static void createIndex() {
- assertU(adoc("id","1",
- "floatdv","2.1",
- "intdv", "1",
- "stringdv", "hello world",
- "longdv", "323223232323",
- "doubledv","2344.345",
- "intdv_m","100",
- "intdv_m","250",
- "floatdv_m", "123.321",
- "floatdv_m", "345.123",
- "doubledv_m", "3444.222",
- "doubledv_m", "23232.2",
- "longdv_m", "43434343434",
- "longdv_m", "343332",
- "stringdv_m", "manchester \"city\"",
- "stringdv_m", "liverpool",
- "stringdv_m", "Everton",
- "datedv", "2017-06-16T07:00:00Z",
- "datedv_m", "2017-06-16T01:00:00Z",
- "datedv_m", "2017-06-16T02:00:00Z",
- "datedv_m", "2017-06-16T03:00:00Z",
- "datedv_m", "2017-06-16T04:00:00Z"));
-
- assertU(adoc("id","7",
- "floatdv","2.1",
- "intdv", "7",
- "longdv", "323223232323",
- "doubledv","2344.345",
- "floatdv_m", "123.321",
- "floatdv_m", "345.123",
- "doubledv_m", "3444.222",
- "doubledv_m", "23232.2",
- "longdv_m", "43434343434",
- "longdv_m", "343332"));
-
- assertU(commit());
- assertU(adoc("id","2", "floatdv","2.1", "intdv", "2", "stringdv", "hello world", "longdv", "323223232323","doubledv","2344.344"));
- assertU(commit());
- assertU(adoc("id","3",
- "floatdv","2.1",
- "intdv", "3",
- "stringdv", "chello world",
- "longdv", "323223232323",
- "doubledv","2344.346",
- "intdv_m","100",
- "intdv_m","250",
- "floatdv_m", "123.321",
- "floatdv_m", "345.123",
- "doubledv_m", "3444.222",
- "doubledv_m", "23232.2",
- "longdv_m", "43434343434",
- "longdv_m", "343332",
- "stringdv_m", "manchester \"city\"",
- "stringdv_m", "liverpool",
- "stringdv_m", "everton",
- "int_is_t", "1",
- "int_is_t", "1",
- "int_is_t", "1",
- "int_is_t", "1"));
- assertU(commit());
- assertU(adoc("id","8",
- "floatdv","2.1",
- "intdv", "10000000",
- "stringdv", "chello \"world\"",
- "longdv", "323223232323",
- "doubledv","2344.346",
- "intdv_m","100",
- "intdv_m","250",
- "floatdv_m", "123.321",
- "floatdv_m", "345.123",
- "doubledv_m", "3444.222",
- "doubledv_m", "23232.2",
- "longdv_m", "43434343434",
- "longdv_m", "343332",
- "stringdv_m", "manchester \"city\"",
- "stringdv_m", "liverpool",
- "stringdv_m", "everton",
- "datedv", "2017-01-01T00:00:00Z",
- "datedv_m", "2017-01-01T01:00:00Z",
- "datedv_m", "2017-01-01T02:00:00Z",
- "int_is_p", "1",
- "int_is_p", "1",
- "int_is_p", "1",
- "int_is_p", "1"));
- assertU(commit());
-
-
- }
-
- @Test
- public void testSortingOutput() throws Exception {
-
- //Test single value DocValue output
- String s = h.query(req("q", "id:1", "qt", "/export", "fl", "floatdv,intdv,stringdv,longdv,doubledv", "sort", "intdv asc"));
-
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"floatdv\":2.1,\"intdv\":1,\"stringdv\":\"hello world\",\"longdv\":323223232323,\"doubledv\":2344.345}]}}");
-
- //Test null value string:
- s = h.query(req("q", "id:7", "qt", "/export", "fl", "floatdv,intdv,stringdv,longdv,doubledv", "sort", "intdv asc"));
-
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"floatdv\":2.1,\"intdv\":7,\"longdv\":323223232323,\"doubledv\":2344.345}]}}");
-
- //Test multiValue docValues output
- s = h.query(req("q", "id:1", "qt", "/export", "fl", "intdv_m,floatdv_m,doubledv_m,longdv_m,stringdv_m", "sort", "intdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"intdv_m\":[100,250],\"floatdv_m\":[123.321,345.123],\"doubledv_m\":[3444.222,23232.2],\"longdv_m\":[343332,43434343434],\"stringdv_m\":[\"Everton\",\"liverpool\",\"manchester \\\"city\\\"\"]}]}}");
-
- //Test multiValues docValues output with nulls
- s = h.query(req("q", "id:7", "qt", "/export", "fl", "intdv_m,floatdv_m,doubledv_m,longdv_m,stringdv_m", "sort", "intdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"floatdv_m\":[123.321,345.123],\"doubledv_m\":[3444.222,23232.2],\"longdv_m\":[343332,43434343434]}]}}");
-
- //Test single sort param is working
- s = h.query(req("q", "id:(1 2)", "qt", "/export", "fl", "intdv", "sort", "intdv desc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":2},{\"intdv\":1}]}}");
-
- s = h.query(req("q", "id:(1 2)", "qt", "/export", "fl", "intdv", "sort", "intdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":1},{\"intdv\":2}]}}");
-
- // Test sort on String will null value. Null value should sort last on desc and first on asc.
-
- s = h.query(req("q", "id:(1 7)", "qt", "/export", "fl", "intdv", "sort", "stringdv desc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":1},{\"intdv\":7}]}}");
-
- s = h.query(req("q", "id:(1 7)", "qt", "/export", "fl", "intdv", "sort", "stringdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":7},{\"intdv\":1}]}}");
-
-
- //Test multi-sort params
- s = h.query(req("q", "id:(1 2)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,intdv desc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":2},{\"intdv\":1}]}}");
-
- s = h.query(req("q", "id:(1 2)", "qt", "/export", "fl", "intdv", "sort", "floatdv desc,intdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":1},{\"intdv\":2}]}}");
-
- //Test three sort fields
- s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,stringdv asc,intdv desc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
-
- //Test three sort fields
- s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,stringdv desc,intdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":1},{\"intdv\":2},{\"intdv\":3}]}}");
-
- //Test four sort fields
- s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,floatdv desc,floatdv asc,intdv desc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
-
- s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "doubledv desc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":1},{\"intdv\":2}]}}");
-
- s = h.query(req("q", "intdv:[2 TO 1000]", "qt", "/export", "fl", "intdv", "sort", "doubledv desc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":7},{\"intdv\":2}]}}");
-
- s = h.query(req("q", "stringdv:blah", "qt", "/export", "fl", "intdv", "sort", "doubledv desc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":0, \"docs\":[]}}");
-
- s = h.query(req("q", "id:8", "qt", "/export", "fl", "stringdv", "sort", "intdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"stringdv\":\"chello \\\"world\\\"\"}]}}");
- }
-
- private void assertJsonEquals(String actual, String expected) {
- assertEquals(Utils.toJSONString(Utils.fromJSONString(expected)), Utils.toJSONString(Utils.fromJSONString(actual)));
- }
-
- @Test
- public void testExportRequiredParams() throws Exception {
-
- //Test whether missing required parameters returns expected errors.
-
- //String s = h.query(req("q", "id:1", "qt", "/export", "fl", "floatdv,intdv,stringdv,longdv,doubledv", "sort", "intdv asc"));
- String s;
- s = h.query(req("qt", "/export"));
- assertTrue("Should have had a sort error", s.contains("No sort criteria"));
- s = h.query(req("sort", "intdv asc", "qt", "/export"));
- assertTrue("Should have had fl error", s.contains("export field list (fl) must be specified"));
- s = h.query(req("sort", "intdv asc", "qt", "/export", "fl", "stringdv"));
- // Interesting you don't even need to specify a "q" parameter.
-
- }
-
- @Test
- public void testDates() throws Exception {
- String s = h.query(req("q", "id:1", "qt", "/export", "fl", "datedv", "sort", "datedv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"datedv\":\"2017-06-16T07:00:00Z\"}]}}");
- s = h.query(req("q", "id:1", "qt", "/export", "fl", "datedv_m", "sort", "datedv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"datedv_m\":[\"2017-06-16T01:00:00Z\",\"2017-06-16T02:00:00Z\",\"2017-06-16T03:00:00Z\",\"2017-06-16T04:00:00Z\"]}]}}");
- }
-
- @Test
- public void testDuplicates() throws Exception {
- // see SOLR-10924
- String expected = h.getCore().getLatestSchema().getField("int_is_t").getType().isPointField()
- ? "1,1,1,1" : "1";
- String s = h.query(req("q", "id:3", "qt", "/export", "fl", "int_is_t", "sort", "intdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"int_is_t\":["+expected+"]}]}}");
- expected = h.getCore().getLatestSchema().getField("int_is_p").getType().isPointField()
- ? "1,1,1,1" : "1";
- s = h.query(req("q", "id:8", "qt", "/export", "fl", "int_is_p", "sort", "intdv asc"));
- assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"int_is_p\":[1,1,1,1]}]}}");
- }
-
- /**
- * This test doesn't validate the correctness of results, it just compares the response of the same request
- * when asking for Trie fields vs Point fields. Can be removed once Trie fields are no longer supported
- */
- @Test
- @SuppressForbidden(reason="using new Date(time) to create random dates")
- public void testRandomNumerics() throws Exception {
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
- assertU(delQ("*:*"));
- assertU(commit());
- List<String> trieFields = new ArrayList<String>();
- List<String> pointFields = new ArrayList<String>();
- for (String mv:new String[]{"s", ""}) {
- for (String indexed:new String[]{"_ni", ""}) {
- for (String type:new String[]{"i", "l", "f", "d", "dt"}) {
- String field = "number_" + type + mv + indexed;
- SchemaField sf = h.getCore().getLatestSchema().getField(field + "_t");
- assertTrue(sf.hasDocValues());
- assertTrue(sf.getType().getNumberType() != null);
-
- sf = h.getCore().getLatestSchema().getField(field + "_p");
- assertTrue(sf.hasDocValues());
- assertTrue(sf.getType().getNumberType() != null);
- assertTrue(sf.getType().isPointField());
-
- trieFields.add(field + "_t");
- pointFields.add(field + "_p");
- }
- }
- }
- for (int i = 0; i < atLeast(100); i++) {
- if (random().nextInt(20) == 0) {
- //have some empty docs
- assertU(adoc("id", String.valueOf(i)));
- continue;
- }
-
- if (random().nextInt(20) == 0 && i > 0) {
- //delete some docs
- assertU(delI(String.valueOf(i - 1)));
- }
-
- SolrInputDocument doc = new SolrInputDocument();
- doc.addField("id", String.valueOf(i));
- addInt(doc, random().nextInt(), false);
- addLong(doc, random().nextLong(), false);
- addFloat(doc, random().nextFloat() * 3000 * (random().nextBoolean()?1:-1), false);
- addDouble(doc, random().nextDouble() * 3000 * (random().nextBoolean()?1:-1), false);
- addDate(doc, dateFormat.format(new Date()), false);
-
- // MV need to be unique in order to be the same in Trie vs Points
- Set<Integer> ints = new HashSet<>();
- Set<Long> longs = new HashSet<>();
- Set<Float> floats = new HashSet<>();
- Set<Double> doubles = new HashSet<>();
- Set<String> dates = new HashSet<>();
- for (int j=0; j < random().nextInt(20); j++) {
- ints.add(random().nextInt());
- longs.add(random().nextLong());
- floats.add(random().nextFloat() * 3000 * (random().nextBoolean()?1:-1));
- doubles.add(random().nextDouble() * 3000 * (random().nextBoolean()?1:-1));
- dates.add(dateFormat.format(new Date(System.currentTimeMillis() + random().nextInt())));
- }
- ints.stream().forEach((val)->addInt(doc, val, true));
- longs.stream().forEach((val)->addLong(doc, val, true));
- floats.stream().forEach((val)->addFloat(doc, val, true));
- doubles.stream().forEach((val)->addDouble(doc, val, true));
- dates.stream().forEach((val)->addDate(doc, val, true));
-
- assertU(adoc(doc));
- if (random().nextInt(20) == 0) {
- assertU(commit());
- }
- }
- assertU(commit());
- doTestQuery("id:1", trieFields, pointFields);
- doTestQuery("*:*", trieFields, pointFields);
- doTestQuery("id:[0 TO 2]", trieFields, pointFields);// "id" field is really a string, this is not a numeric range query
- doTestQuery("id:[0 TO 9]", trieFields, pointFields);
- doTestQuery("id:DOES_NOT_EXIST", trieFields, pointFields);
- }
-
- private void doTestQuery(String query, List<String> trieFields, List<String> pointFields) throws Exception {
- String trieFieldsFl = String.join(",", trieFields);
- String pointFieldsFl = String.join(",", pointFields);
- String sort = pickRandom((String)pickRandom(trieFields.toArray()), (String)pickRandom(pointFields.toArray())).replace("s_", "_") + pickRandom(" asc", " desc");
- String resultPoints = h.query(req("q", query, "qt", "/export", "fl", pointFieldsFl, "sort", sort));
- String resultTries = h.query(req("q", query, "qt", "/export", "fl", trieFieldsFl, "sort", sort));
- assertJsonEquals(resultPoints.replaceAll("_p", ""), resultTries.replaceAll("_t", ""));
- }
-
- private void addFloat(SolrInputDocument doc, float value, boolean mv) {
- addField(doc, "f", String.valueOf(value), mv);
- }
-
- private void addDouble(SolrInputDocument doc, double value, boolean mv) {
- addField(doc, "d", String.valueOf(value), mv);
- }
-
- private void addLong(SolrInputDocument doc, long value, boolean mv) {
- addField(doc, "l", String.valueOf(value), mv);
- }
-
- private void addInt(SolrInputDocument doc, int value, boolean mv) {
- addField(doc, "i", String.valueOf(value), mv);
- }
-
- private void addDate(SolrInputDocument doc, String value, boolean mv) {
- addField(doc, "dt", value, mv);
- }
-
- private void addField(SolrInputDocument doc, String type, String value, boolean mv) {
- doc.addField("number_" + type + (mv?"s":"") + "_t", value);
- doc.addField("number_" + type + (mv?"s":"") + "_p", value);
- doc.addField("number_" + type + (mv?"s":"") + "_ni_t", value);
- doc.addField("number_" + type + (mv?"s":"") + "_ni_p", value);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/solr-ref-guide/src/exporting-result-sets.adoc
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/exporting-result-sets.adoc b/solr/solr-ref-guide/src/exporting-result-sets.adoc
index be1811f..b0565d8 100644
--- a/solr/solr-ref-guide/src/exporting-result-sets.adoc
+++ b/solr/solr-ref-guide/src/exporting-result-sets.adoc
@@ -52,7 +52,8 @@ http://localhost:8983/solr/core_name/export?q=my-query&sort=severity+desc,timest
The `sort` property defines how documents will be sorted in the exported result set. Results can be sorted by any field that has a field type of int,long, float, double, string. The sort fields must be single valued fields.
-Up to four sort fields can be specified per request, with the 'asc' or 'desc' properties.
+The export performance will get slower as you add more sort fields. If there is enough physical memory available outside of the JVM to load up the sort fields then the performance will be linearly slower with addition of sort fields.
+It can get worse otherwise.
=== Specifying the Field List
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/solr-ref-guide/src/parallel-sql-interface.adoc
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/parallel-sql-interface.adoc b/solr/solr-ref-guide/src/parallel-sql-interface.adoc
index 9fb3d16..01442ee 100644
--- a/solr/solr-ref-guide/src/parallel-sql-interface.adoc
+++ b/solr/solr-ref-guide/src/parallel-sql-interface.adoc
@@ -321,10 +321,6 @@ The Column Identifiers can contain both fields in the Solr index and aggregate f
The non-function fields in the field list determine the fields to calculate the aggregations over.
-*`GROUP BY` Clause*
-
-The `GROUP BY` clause can contain up to 4 fields in the Solr index. These fields should correspond with the non-function fields in the field list.
-
=== HAVING Clause
The `HAVING` clause may contain any function listed in the field list. Complex `HAVING` clauses such as this are supported:
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/solrj/src/java/org/apache/solr/common/SolrException.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/java/org/apache/solr/common/SolrException.java b/solr/solrj/src/java/org/apache/solr/common/SolrException.java
index f73f5dd..673bae7 100644
--- a/solr/solrj/src/java/org/apache/solr/common/SolrException.java
+++ b/solr/solrj/src/java/org/apache/solr/common/SolrException.java
@@ -213,7 +213,7 @@ public class SolrException extends RuntimeException {
return null;
}
- public static Throwable getRootCause(Throwable t) {
+ public static Throwable getRootCause(Throwable t) {
while (true) {
Throwable cause = t.getCause();
if (cause!=null) {
[03/33] lucene-solr:jira/http2: Ref Guide: fix URL example rendering
in result-grouping.adoc so all characters appear properly
Posted by da...@apache.org.
Ref Guide: fix URL example rendering in result-grouping.adoc so all characters appear properly
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/c152caeb
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/c152caeb
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/c152caeb
Branch: refs/heads/jira/http2
Commit: c152caeb238da36ccbcea86d3050c0b976508efb
Parents: a19bc5e
Author: Cassandra Targett <ct...@apache.org>
Authored: Fri Jul 20 07:39:44 2018 -0500
Committer: Cassandra Targett <ct...@apache.org>
Committed: Fri Jul 20 07:40:24 2018 -0500
----------------------------------------------------------------------
solr/solr-ref-guide/src/result-grouping.adoc | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c152caeb/solr/solr-ref-guide/src/result-grouping.adoc
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/result-grouping.adoc b/solr/solr-ref-guide/src/result-grouping.adoc
index 02b5875..a687b78 100644
--- a/solr/solr-ref-guide/src/result-grouping.adoc
+++ b/solr/solr-ref-guide/src/result-grouping.adoc
@@ -124,7 +124,8 @@ All of the following sample queries work with Solr's "`bin/solr -e techproducts`
In this example, we will group results based on the `manu_exact` field, which specifies the manufacturer of the items in the sample dataset.
-`\http://localhost:8983/solr/techproducts/select?fl=id,name&q=solr+memory&group=true&group.field=manu_exact`
+[source,text]
+http://localhost:8983/solr/techproducts/select?fl=id,name&q=solr+memory&group=true&group.field=manu_exact
[source,json]
----
@@ -175,7 +176,8 @@ The response indicates that there are six total matches for our query. For each
We can run the same query with the request parameter `group.main=true`. This will format the results as a single flat document list. This flat format does not include as much information as the normal result grouping query results – notably the `numFound` in each group – but it may be easier for existing Solr clients to parse.
-`\http://localhost:8983/solr/techproducts/select?fl=id,name,manufacturer&q=solr+memory&group=true&group.field=manu_exact&group.main=true`
+[source,text]
+http://localhost:8983/solr/techproducts/select?fl=id,name,manufacturer&q=solr+memory&group=true&group.field=manu_exact&group.main=true
[source,json]
----
@@ -215,7 +217,8 @@ We can run the same query with the request parameter `group.main=true`. This wil
In this example, we will use the `group.query` parameter to find the top three results for "memory" in two different price ranges: 0.00 to 99.99, and over 100.
-`\http://localhost:8983/solr/techproducts/select?indent=true&fl=name,price&q=memory&group=true&group.query=price:[0+TO+99.99]&group.query=price:[100+TO+*]&group.limit=3`
+[source,text]
+http://localhost:8983/solr/techproducts/select?indent=true&fl=name,price&q=memory&group=true&group.query=price:[0+TO+99.99]&group.query=price:[100+TO+*]&group.limit=3
[source,json]
----
[18/33] lucene-solr:jira/http2: LUCENE-8412: TopFieldCollector no
longer takes a trackDocScores option.
Posted by da...@apache.org.
LUCENE-8412: TopFieldCollector no longer takes a trackDocScores option.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/55bfadbc
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/55bfadbc
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/55bfadbc
Branch: refs/heads/jira/http2
Commit: 55bfadbce115a825a75686fe0bfe71406bc3ee44
Parents: 34686c0
Author: Adrien Grand <jp...@gmail.com>
Authored: Mon Jul 23 09:05:02 2018 +0200
Committer: Adrien Grand <jp...@gmail.com>
Committed: Mon Jul 23 09:06:49 2018 +0200
----------------------------------------------------------------------
lucene/CHANGES.txt | 6 +-
lucene/MIGRATE.txt | 7 +
.../lucene/benchmark/byTask/tasks/ReadTask.java | 7 -
.../byTask/tasks/SearchWithSortTask.java | 9 -
.../org/apache/lucene/search/IndexSearcher.java | 8 +-
.../org/apache/lucene/search/SortRescorer.java | 21 ++-
.../apache/lucene/search/TopFieldCollector.java | 118 ++++++------
.../apache/lucene/index/TestIndexSorting.java | 4 +-
.../org/apache/lucene/search/TestBoolean2.java | 8 +-
.../lucene/search/TestElevationComparator.java | 2 +-
.../apache/lucene/search/TestSortRandom.java | 2 +-
.../apache/lucene/search/TestTopDocsMerge.java | 4 +-
.../lucene/search/TestTopFieldCollector.java | 179 +++++++++++--------
.../TestTopFieldCollectorEarlyTermination.java | 5 +-
.../org/apache/lucene/facet/DrillSideways.java | 16 +-
.../apache/lucene/facet/FacetsCollector.java | 4 +-
.../search/grouping/BlockGroupingCollector.java | 2 +-
.../lucene/search/grouping/GroupingSearch.java | 17 +-
.../search/grouping/TopGroupsCollector.java | 11 +-
.../lucene/search/grouping/TestGrouping.java | 55 +++---
.../analyzing/AnalyzingInfixSuggester.java | 2 +-
.../solr/handler/component/ExpandComponent.java | 4 +-
.../solr/handler/component/QueryComponent.java | 1 +
.../java/org/apache/solr/search/Grouping.java | 24 ++-
.../org/apache/solr/search/ReRankCollector.java | 15 +-
.../apache/solr/search/SolrIndexSearcher.java | 9 +-
.../apache/solr/search/grouping/Command.java | 7 +
.../solr/search/grouping/CommandHandler.java | 4 +
.../distributed/command/QueryCommand.java | 14 +-
.../command/TopGroupsFieldCommand.java | 42 +++--
.../test/org/apache/solr/search/TestSort.java | 3 +-
.../uninverting/TestFieldCacheSortRandom.java | 4 +-
32 files changed, 348 insertions(+), 266 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 3f74283..730e24c 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -60,9 +60,13 @@ API Changes
no longer have an option to compute the maximum score when sorting by field.
(Adrien Grand)
-* LUCENE-8411: TopFieldCollector no longer takes a fillFields options, it now
+* LUCENE-8411: TopFieldCollector no longer takes a fillFields option, it now
always fills fields. (Adrien Grand)
+* LUCENE-8412: TopFieldCollector no longer takes a trackDocScores option. Scores
+ need to be set on top hits via TopFieldCollector#populateScores instead.
+ (Adrien Grand)
+
Changes in Runtime Behavior
* LUCENE-8333: Switch MoreLikeThis.setMaxDocFreqPct to use maxDoc instead of
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/MIGRATE.txt
----------------------------------------------------------------------
diff --git a/lucene/MIGRATE.txt b/lucene/MIGRATE.txt
index fb37a1c..4c14651 100644
--- a/lucene/MIGRATE.txt
+++ b/lucene/MIGRATE.txt
@@ -82,3 +82,10 @@ all matches.
Because filling sort values doesn't have a significant overhead, the fillFields
option has been removed from TopFieldCollector factory methods. Everything
behaves as if it was set to true.
+
+## TopFieldCollector no longer takes a trackDocScores option ##
+
+Computing scores at collection time is less efficient than running a second
+request in order to only compute scores for documents that made it to the top
+hits. As a consequence, the trackDocScores option has been removed and can be
+replaced with the new TopFieldCollector#populateScores helper method.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.java
----------------------------------------------------------------------
diff --git a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.java b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.java
index ee06683..b05a429 100644
--- a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.java
+++ b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.java
@@ -112,7 +112,6 @@ public abstract class ReadTask extends PerfTask {
// Weight public again, we can go back to
// pulling the Weight ourselves:
TopFieldCollector collector = TopFieldCollector.create(sort, numHits,
- withScore(),
withTotalHits());
searcher.search(q, collector);
hits = collector.topDocs();
@@ -208,12 +207,6 @@ public abstract class ReadTask extends PerfTask {
*/
public abstract boolean withTraverse();
- /** Whether scores should be computed (only useful with
- * field sort) */
- public boolean withScore() {
- return true;
- }
-
/** Whether totalHits should be computed (only useful with
* field sort) */
public boolean withTotalHits() {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java
----------------------------------------------------------------------
diff --git a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java
index 6a17714..d27cfed 100644
--- a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java
+++ b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java
@@ -29,7 +29,6 @@ import org.apache.lucene.search.SortField;
*/
public class SearchWithSortTask extends ReadTask {
- private boolean doScore = true;
private Sort sort;
public SearchWithSortTask(PerfRunData runData) {
@@ -60,9 +59,6 @@ public class SearchWithSortTask extends ReadTask {
sortField0 = SortField.FIELD_DOC;
} else if (field.equals("score")) {
sortField0 = SortField.FIELD_SCORE;
- } else if (field.equals("noscore")) {
- doScore = false;
- continue;
} else {
int index = field.lastIndexOf(":");
String fieldName;
@@ -115,11 +111,6 @@ public class SearchWithSortTask extends ReadTask {
public boolean withWarm() {
return false;
}
-
- @Override
- public boolean withScore() {
- return doScore;
- }
@Override
public Sort getSort() {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java b/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
index d52e2f3..7d18d4f 100644
--- a/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
@@ -513,7 +513,7 @@ public class IndexSearcher {
@Override
public TopFieldCollector newCollector() throws IOException {
// TODO: don't pay the price for accurate hit counts by default
- return TopFieldCollector.create(rewrittenSort, cappedNumHits, after, doDocScores, true);
+ return TopFieldCollector.create(rewrittenSort, cappedNumHits, after, true);
}
@Override
@@ -528,7 +528,11 @@ public class IndexSearcher {
};
- return search(query, manager);
+ TopFieldDocs topDocs = search(query, manager);
+ if (doDocScores) {
+ TopFieldCollector.populateScores(topDocs.scoreDocs, this, query);
+ }
+ return topDocs;
}
/**
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/java/org/apache/lucene/search/SortRescorer.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/SortRescorer.java b/lucene/core/src/java/org/apache/lucene/search/SortRescorer.java
index 93dd126..95f2982 100644
--- a/lucene/core/src/java/org/apache/lucene/search/SortRescorer.java
+++ b/lucene/core/src/java/org/apache/lucene/search/SortRescorer.java
@@ -44,17 +44,12 @@ public class SortRescorer extends Rescorer {
// Copy ScoreDoc[] and sort by ascending docID:
ScoreDoc[] hits = firstPassTopDocs.scoreDocs.clone();
- Arrays.sort(hits,
- new Comparator<ScoreDoc>() {
- @Override
- public int compare(ScoreDoc a, ScoreDoc b) {
- return a.doc - b.doc;
- }
- });
+ Comparator<ScoreDoc> docIdComparator = Comparator.comparingInt(sd -> sd.doc);
+ Arrays.sort(hits, docIdComparator);
List<LeafReaderContext> leaves = searcher.getIndexReader().leaves();
- TopFieldCollector collector = TopFieldCollector.create(sort, topN, true, true);
+ TopFieldCollector collector = TopFieldCollector.create(sort, topN, true);
// Now merge sort docIDs from hits, with reader's leaves:
int hitUpto = 0;
@@ -90,7 +85,15 @@ public class SortRescorer extends Rescorer {
hitUpto++;
}
- return collector.topDocs();
+ TopDocs rescoredDocs = collector.topDocs();
+ // set scores from the original score docs
+ assert hits.length == rescoredDocs.scoreDocs.length;
+ ScoreDoc[] rescoredDocsClone = rescoredDocs.scoreDocs.clone();
+ Arrays.sort(rescoredDocsClone, docIdComparator);
+ for (int i = 0; i < rescoredDocsClone.length; ++i) {
+ rescoredDocsClone[i].score = hits[i].score;
+ }
+ return rescoredDocs;
}
@Override
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/java/org/apache/lucene/search/TopFieldCollector.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/TopFieldCollector.java b/lucene/core/src/java/org/apache/lucene/search/TopFieldCollector.java
index 7defdf9..f8a8ff7 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TopFieldCollector.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TopFieldCollector.java
@@ -19,16 +19,20 @@ package org.apache.lucene.search;
import java.io.IOException;
import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.search.FieldValueHitQueue.Entry;
+import org.apache.lucene.util.FutureObjects;
import org.apache.lucene.util.PriorityQueue;
/**
* A {@link Collector} that sorts by {@link SortField} using
* {@link FieldComparator}s.
* <p>
- * See the {@link #create(org.apache.lucene.search.Sort, int, boolean, boolean)} method
+ * See the {@link #create(org.apache.lucene.search.Sort, int, boolean)} method
* for instantiating a TopFieldCollector.
*
* @lucene.experimental
@@ -44,10 +48,9 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
final LeafFieldComparator comparator;
final int reverseMul;
- final boolean mayNeedScoresTwice;
Scorer scorer;
- MultiComparatorLeafCollector(LeafFieldComparator[] comparators, int[] reverseMul, boolean mayNeedScoresTwice) {
+ MultiComparatorLeafCollector(LeafFieldComparator[] comparators, int[] reverseMul) {
if (comparators.length == 1) {
this.reverseMul = reverseMul[0];
this.comparator = comparators[0];
@@ -55,14 +58,10 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
this.reverseMul = 1;
this.comparator = new MultiLeafFieldComparator(comparators, reverseMul);
}
- this.mayNeedScoresTwice = mayNeedScoresTwice;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
- if (mayNeedScoresTwice && scorer instanceof ScoreCachingWrappingScorer == false) {
- scorer = new ScoreCachingWrappingScorer(scorer);
- }
comparator.setScorer(scorer);
this.scorer = scorer;
}
@@ -93,20 +92,12 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
final Sort sort;
final FieldValueHitQueue<Entry> queue;
- final boolean trackDocScores;
- final boolean mayNeedScoresTwice;
final boolean trackTotalHits;
- public SimpleFieldCollector(Sort sort, FieldValueHitQueue<Entry> queue, int numHits,
- boolean trackDocScores, boolean trackTotalHits) {
- super(queue, numHits, sort.needsScores() || trackDocScores);
+ public SimpleFieldCollector(Sort sort, FieldValueHitQueue<Entry> queue, int numHits, boolean trackTotalHits) {
+ super(queue, numHits, sort.needsScores());
this.sort = sort;
this.queue = queue;
- this.trackDocScores = trackDocScores;
- // If one of the sort fields needs scores, and if we also track scores, then
- // we might call scorer.score() several times per doc so wrapping the scorer
- // to cache scores would help
- this.mayNeedScoresTwice = sort.needsScores() && trackDocScores;
this.trackTotalHits = trackTotalHits;
}
@@ -122,7 +113,7 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
canEarlyTerminate(sort, indexSort);
final int initialTotalHits = totalHits;
- return new MultiComparatorLeafCollector(comparators, reverseMul, mayNeedScoresTwice) {
+ return new MultiComparatorLeafCollector(comparators, reverseMul) {
@Override
public void collect(int doc) throws IOException {
@@ -146,10 +137,6 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
}
}
- if (trackDocScores) {
- score = scorer.score();
- }
-
// This hit is competitive - replace bottom element in queue & adjustTop
comparator.copy(bottom.slot, doc);
updateBottom(doc, score);
@@ -158,10 +145,6 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
// Startup transient: queue hasn't gathered numHits yet
final int slot = totalHits - 1;
- if (trackDocScores) {
- score = scorer.score();
- }
-
// Copy hit into queue
comparator.copy(slot, doc);
add(slot, doc, score);
@@ -184,19 +167,15 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
final Sort sort;
int collectedHits;
final FieldValueHitQueue<Entry> queue;
- final boolean trackDocScores;
final FieldDoc after;
- final boolean mayNeedScoresTwice;
final boolean trackTotalHits;
public PagingFieldCollector(Sort sort, FieldValueHitQueue<Entry> queue, FieldDoc after, int numHits,
- boolean trackDocScores, boolean trackTotalHits) {
- super(queue, numHits, trackDocScores || sort.needsScores());
+ boolean trackTotalHits) {
+ super(queue, numHits, sort.needsScores());
this.sort = sort;
this.queue = queue;
- this.trackDocScores = trackDocScores;
this.after = after;
- this.mayNeedScoresTwice = sort.needsScores() && trackDocScores;
this.trackTotalHits = trackTotalHits;
FieldComparator<?>[] comparators = queue.comparators;
@@ -217,7 +196,7 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
indexSort != null &&
canEarlyTerminate(sort, indexSort);
final int initialTotalHits = totalHits;
- return new MultiComparatorLeafCollector(queue.getComparators(context), queue.getReverseMul(), mayNeedScoresTwice) {
+ return new MultiComparatorLeafCollector(queue.getComparators(context), queue.getReverseMul()) {
@Override
public void collect(int doc) throws IOException {
@@ -256,10 +235,6 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
// This hit is competitive - replace bottom element in queue & adjustTop
comparator.copy(bottom.slot, doc);
- // Compute score only if it is competitive.
- if (trackDocScores) {
- score = scorer.score();
- }
updateBottom(doc, score);
comparator.setBottom(bottom.slot);
@@ -272,10 +247,6 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
// Copy hit into queue
comparator.copy(slot, doc);
- // Compute score only if it is competitive.
- if (trackDocScores) {
- score = scorer.score();
- }
bottom = pq.add(new Entry(slot, docBase + doc, score));
queueFull = collectedHits == numHits;
if (queueFull) {
@@ -325,13 +296,6 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
* the sort criteria (SortFields).
* @param numHits
* the number of results to collect.
- * @param trackDocScores
- * specifies whether document scores should be tracked and set on the
- * results. Note that if set to false, then the results' scores will
- * be set to Float.NaN. Setting this to true affects performance, as
- * it incurs the score computation on each competitive result.
- * Therefore if document scores are not required by the application,
- * it is recommended to set it to false.
* @param trackTotalHits
* specifies whether the total number of hits should be tracked. If
* set to false, the value of {@link TopFieldDocs#totalHits} will be
@@ -339,9 +303,8 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
* @return a {@link TopFieldCollector} instance which will sort the results by
* the sort criteria.
*/
- public static TopFieldCollector create(Sort sort, int numHits,
- boolean trackDocScores, boolean trackTotalHits) {
- return create(sort, numHits, null, trackDocScores, trackTotalHits);
+ public static TopFieldCollector create(Sort sort, int numHits, boolean trackTotalHits) {
+ return create(sort, numHits, null, trackTotalHits);
}
/**
@@ -358,14 +321,6 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
* the number of results to collect.
* @param after
* only hits after this FieldDoc will be collected
- * @param trackDocScores
- * specifies whether document scores should be tracked and set on the
- * results. Note that if set to false, then the results' scores will
- * be set to Float.NaN. Setting this to true affects performance, as
- * it incurs the score computation on each competitive result.
- * Therefore if document scores are not required by the application,
- * it is recommended to set it to false.
- * <code>trackDocScores</code> to true as well.
* @param trackTotalHits
* specifies whether the total number of hits should be tracked. If
* set to false, the value of {@link TopFieldDocs#totalHits} will be
@@ -374,7 +329,7 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
* the sort criteria.
*/
public static TopFieldCollector create(Sort sort, int numHits, FieldDoc after,
- boolean trackDocScores, boolean trackTotalHits) {
+ boolean trackTotalHits) {
if (sort.fields.length == 0) {
throw new IllegalArgumentException("Sort must contain at least one field");
@@ -387,7 +342,7 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
FieldValueHitQueue<Entry> queue = FieldValueHitQueue.create(sort.fields, numHits);
if (after == null) {
- return new SimpleFieldCollector(sort, queue, numHits, trackDocScores, trackTotalHits);
+ return new SimpleFieldCollector(sort, queue, numHits, trackTotalHits);
} else {
if (after.fields == null) {
throw new IllegalArgumentException("after.fields wasn't set; you must pass fillFields=true for the previous search");
@@ -397,7 +352,46 @@ public abstract class TopFieldCollector extends TopDocsCollector<Entry> {
throw new IllegalArgumentException("after.fields has " + after.fields.length + " values but sort has " + sort.getSort().length);
}
- return new PagingFieldCollector(sort, queue, after, numHits, trackDocScores, trackTotalHits);
+ return new PagingFieldCollector(sort, queue, after, numHits, trackTotalHits);
+ }
+ }
+
+ /**
+ * Populate {@link ScoreDoc#score scores} of the given {@code topDocs}.
+ * @param topDocs the top docs to populate
+ * @param searcher the index searcher that has been used to compute {@code topDocs}
+ * @param query the query that has been used to compute {@code topDocs}
+ * @throws IllegalArgumentException if there is evidence that {@code topDocs}
+ * have been computed against a different searcher or a different query.
+ * @lucene.experimental
+ */
+ public static void populateScores(ScoreDoc[] topDocs, IndexSearcher searcher, Query query) throws IOException {
+ // Get the score docs sorted in doc id order
+ topDocs = topDocs.clone();
+ Arrays.sort(topDocs, Comparator.comparingInt(scoreDoc -> scoreDoc.doc));
+
+ final Weight weight = searcher.createWeight(searcher.rewrite(query), ScoreMode.COMPLETE, 1);
+ List<LeafReaderContext> contexts = searcher.getIndexReader().leaves();
+ LeafReaderContext currentContext = null;
+ Scorer currentScorer = null;
+ for (ScoreDoc scoreDoc : topDocs) {
+ if (currentContext == null || scoreDoc.doc >= currentContext.docBase + currentContext.reader().maxDoc()) {
+ FutureObjects.checkIndex(scoreDoc.doc, searcher.getIndexReader().maxDoc());
+ int newContextIndex = ReaderUtil.subIndex(scoreDoc.doc, contexts);
+ currentContext = contexts.get(newContextIndex);
+ final ScorerSupplier scorerSupplier = weight.scorerSupplier(currentContext);
+ if (scorerSupplier == null) {
+ throw new IllegalArgumentException("Doc id " + scoreDoc.doc + " doesn't match the query");
+ }
+ currentScorer = scorerSupplier.get(1); // random-access
+ }
+ final int leafDoc = scoreDoc.doc - currentContext.docBase;
+ assert leafDoc >= 0;
+ final int advanced = currentScorer.iterator().advance(leafDoc);
+ if (leafDoc != advanced) {
+ throw new IllegalArgumentException("Doc id " + scoreDoc.doc + " doesn't match the query");
+ }
+ scoreDoc.score = currentScorer.score();
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
index f454d48..858a874 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
@@ -2324,11 +2324,11 @@ public class TestIndexSorting extends LuceneTestCase {
System.out.println("TEST: iter=" + iter + " numHits=" + numHits);
}
- TopFieldCollector c1 = TopFieldCollector.create(sort, numHits, true, true);
+ TopFieldCollector c1 = TopFieldCollector.create(sort, numHits, true);
s1.search(new MatchAllDocsQuery(), c1);
TopDocs hits1 = c1.topDocs();
- TopFieldCollector c2 = TopFieldCollector.create(sort, numHits, true, false);
+ TopFieldCollector c2 = TopFieldCollector.create(sort, numHits, false);
s2.search(new MatchAllDocsQuery(), c2);
TopDocs hits2 = c2.topDocs();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java b/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java
index 9485717..bc0531e 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java
@@ -386,10 +386,10 @@ public class TestBoolean2 extends LuceneTestCase {
}
// check diff (randomized) scorers (from AssertingSearcher) produce the same results
- TopFieldCollector collector = TopFieldCollector.create(sort, 1000, true, false);
+ TopFieldCollector collector = TopFieldCollector.create(sort, 1000, false);
searcher.search(q1, collector);
ScoreDoc[] hits1 = collector.topDocs().scoreDocs;
- collector = TopFieldCollector.create(sort, 1000, true, false);
+ collector = TopFieldCollector.create(sort, 1000, false);
searcher.search(q1, collector);
ScoreDoc[] hits2 = collector.topDocs().scoreDocs;
tot+=hits2.length;
@@ -402,10 +402,10 @@ public class TestBoolean2 extends LuceneTestCase {
assertEquals(mulFactor*collector.totalHits + NUM_EXTRA_DOCS/2, hits4.totalHits);
// test diff (randomized) scorers produce the same results on bigSearcher as well
- collector = TopFieldCollector.create(sort, 1000 * mulFactor, true, false);
+ collector = TopFieldCollector.create(sort, 1000 * mulFactor, false);
bigSearcher.search(q1, collector);
hits1 = collector.topDocs().scoreDocs;
- collector = TopFieldCollector.create(sort, 1000 * mulFactor, true, false);
+ collector = TopFieldCollector.create(sort, 1000 * mulFactor, false);
bigSearcher.search(q1, collector);
hits2 = collector.topDocs().scoreDocs;
CheckHits.checkEqual(q1, hits1, hits2);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java b/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java
index 5d5488a..337bb36 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java
@@ -86,7 +86,7 @@ public class TestElevationComparator extends LuceneTestCase {
new SortField(null, SortField.Type.SCORE, reversed)
);
- TopDocsCollector<Entry> topCollector = TopFieldCollector.create(sort, 50, true, true);
+ TopDocsCollector<Entry> topCollector = TopFieldCollector.create(sort, 50, true);
searcher.search(newq.build(), topCollector);
TopDocs topDocs = topCollector.topDocs(0, 10);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.java b/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.java
index a96399e..d1a852f 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.java
@@ -146,7 +146,7 @@ public class TestSortRandom extends LuceneTestCase {
}
final int hitCount = TestUtil.nextInt(random, 1, r.maxDoc() + 20);
final RandomQuery f = new RandomQuery(random.nextLong(), random.nextFloat(), docValues);
- hits = s.search(f, hitCount, sort, random.nextBoolean());
+ hits = s.search(f, hitCount, sort, false);
if (VERBOSE) {
System.out.println("\nTEST: iter=" + iter + " " + hits.totalHits + " hits; topN=" + hitCount + "; reverse=" + reverse + "; sortMissingLast=" + sortMissingLast + " sort=" + sort);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/test/org/apache/lucene/search/TestTopDocsMerge.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTopDocsMerge.java b/lucene/core/src/test/org/apache/lucene/search/TestTopDocsMerge.java
index 2174acf..8d6e9d5 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestTopDocsMerge.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestTopDocsMerge.java
@@ -281,7 +281,7 @@ public class TestTopDocsMerge extends LuceneTestCase {
topHits = searcher.search(query, numHits);
}
} else {
- final TopFieldCollector c = TopFieldCollector.create(sort, numHits, true, true);
+ final TopFieldCollector c = TopFieldCollector.create(sort, numHits, true);
searcher.search(query, c);
if (useFrom) {
from = TestUtil.nextInt(random(), 0, numHits - 1);
@@ -330,7 +330,7 @@ public class TestTopDocsMerge extends LuceneTestCase {
if (sort == null) {
subHits = subSearcher.search(w, numHits);
} else {
- final TopFieldCollector c = TopFieldCollector.create(sort, numHits, true, true);
+ final TopFieldCollector c = TopFieldCollector.create(sort, numHits, true);
subSearcher.search(w, c);
subHits = c.topDocs(0, numHits);
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java b/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java
index 1b214b1..717d843 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java
@@ -18,11 +18,14 @@ package org.apache.lucene.search;
import java.io.IOException;
+import java.util.Arrays;
+import java.util.Comparator;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StringField;
+import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.RandomIndexWriter;
@@ -70,8 +73,7 @@ public class TestTopFieldCollector extends LuceneTestCase {
Sort[] sort = new Sort[] { new Sort(SortField.FIELD_DOC), new Sort() };
for(int i = 0; i < sort.length; i++) {
Query q = new MatchAllDocsQuery();
- TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10,
- false, true);
+ TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true);
is.search(q, tdc);
@@ -83,14 +85,13 @@ public class TestTopFieldCollector extends LuceneTestCase {
}
}
- public void testSortWithoutScoreTracking() throws Exception {
+ public void testSort() throws Exception {
// Two Sort criteria to instantiate the multi/single comparators.
Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC), new Sort() };
for(int i = 0; i < sort.length; i++) {
Query q = new MatchAllDocsQuery();
- TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, false,
- true);
+ TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true);
is.search(q, tdc);
@@ -110,10 +111,10 @@ public class TestTopFieldCollector extends LuceneTestCase {
// the index is not sorted
TopDocsCollector<Entry> tdc;
if (i % 2 == 0) {
- tdc = TopFieldCollector.create(sort, 10, false, false);
+ tdc = TopFieldCollector.create(sort, 10, false);
} else {
FieldDoc fieldDoc = new FieldDoc(1, Float.NaN, new Object[] { 1 });
- tdc = TopFieldCollector.create(sort, 10, fieldDoc, false, false);
+ tdc = TopFieldCollector.create(sort, 10, fieldDoc, false);
}
is.search(q, tdc);
@@ -125,32 +126,13 @@ public class TestTopFieldCollector extends LuceneTestCase {
}
}
}
-
- public void testSortWithScoreTracking() throws Exception {
-
- // Two Sort criteria to instantiate the multi/single comparators.
- Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC), new Sort() };
- for(int i = 0; i < sort.length; i++) {
- Query q = new MatchAllDocsQuery();
- TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true,
- true);
-
- is.search(q, tdc);
-
- TopDocs td = tdc.topDocs();
- ScoreDoc[] sd = td.scoreDocs;
- for(int j = 0; j < sd.length; j++) {
- assertTrue(!Float.isNaN(sd[j].score));
- }
- }
- }
- public void testSortWithScoreTrackingNoResults() throws Exception {
+ public void testSortNoResults() throws Exception {
// Two Sort criteria to instantiate the multi/single comparators.
Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC), new Sort() };
for(int i = 0; i < sort.length; i++) {
- TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true, true);
+ TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true);
TopDocs td = tdc.topDocs();
assertEquals(0, td.totalHits);
}
@@ -182,59 +164,112 @@ public class TestTopFieldCollector extends LuceneTestCase {
.build();
final IndexSearcher searcher = new IndexSearcher(reader);
for (Sort sort : new Sort[] {new Sort(SortField.FIELD_SCORE), new Sort(new SortField("f", SortField.Type.SCORE))}) {
- for (boolean doDocScores : new boolean[] {false, true}) {
- final TopFieldCollector topCollector = TopFieldCollector.create(sort, TestUtil.nextInt(random(), 1, 2), doDocScores, true);
- final Collector assertingCollector = new Collector() {
- @Override
- public LeafCollector getLeafCollector(LeafReaderContext context) throws IOException {
- final LeafCollector in = topCollector.getLeafCollector(context);
- return new FilterLeafCollector(in) {
- @Override
- public void setScorer(final Scorer scorer) throws IOException {
- Scorer s = new Scorer(null) {
-
- int lastComputedDoc = -1;
-
- @Override
- public float score() throws IOException {
- if (lastComputedDoc == docID()) {
- throw new AssertionError("Score computed twice on " + docID());
- }
- lastComputedDoc = docID();
- return scorer.score();
- }
+ final TopFieldCollector topCollector = TopFieldCollector.create(sort, TestUtil.nextInt(random(), 1, 2), true);
+ final Collector assertingCollector = new Collector() {
+ @Override
+ public LeafCollector getLeafCollector(LeafReaderContext context) throws IOException {
+ final LeafCollector in = topCollector.getLeafCollector(context);
+ return new FilterLeafCollector(in) {
+ @Override
+ public void setScorer(final Scorer scorer) throws IOException {
+ Scorer s = new Scorer(null) {
- @Override
- public float getMaxScore(int upTo) throws IOException {
- return scorer.getMaxScore(upTo);
- }
+ int lastComputedDoc = -1;
- @Override
- public int docID() {
- return scorer.docID();
+ @Override
+ public float score() throws IOException {
+ if (lastComputedDoc == docID()) {
+ throw new AssertionError("Score computed twice on " + docID());
}
+ lastComputedDoc = docID();
+ return scorer.score();
+ }
- @Override
- public DocIdSetIterator iterator() {
- return scorer.iterator();
- }
+ @Override
+ public float getMaxScore(int upTo) throws IOException {
+ return scorer.getMaxScore(upTo);
+ }
- };
- super.setScorer(s);
- }
- };
- }
- @Override
- public ScoreMode scoreMode() {
- return topCollector.scoreMode();
- }
- };
- searcher.search(query, assertingCollector);
- }
+ @Override
+ public int docID() {
+ return scorer.docID();
+ }
+
+ @Override
+ public DocIdSetIterator iterator() {
+ return scorer.iterator();
+ }
+
+ };
+ super.setScorer(s);
+ }
+ };
+ }
+ @Override
+ public ScoreMode scoreMode() {
+ return topCollector.scoreMode();
+ }
+ };
+ searcher.search(query, assertingCollector);
}
reader.close();
w.close();
dir.close();
}
+ public void testPopulateScores() throws IOException {
+ Directory dir = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);
+ Document doc = new Document();
+ TextField field = new TextField("f", "foo bar", Store.NO);
+ doc.add(field);
+ NumericDocValuesField sortField = new NumericDocValuesField("sort", 0);
+ doc.add(sortField);
+ w.addDocument(doc);
+
+ field.setStringValue("");
+ sortField.setLongValue(3);
+ w.addDocument(doc);
+
+ field.setStringValue("foo foo bar");
+ sortField.setLongValue(2);
+ w.addDocument(doc);
+
+ w.flush();
+
+ field.setStringValue("foo");
+ sortField.setLongValue(2);
+ w.addDocument(doc);
+
+ field.setStringValue("bar bar bar");
+ sortField.setLongValue(0);
+ w.addDocument(doc);
+
+ IndexReader reader = w.getReader();
+ w.close();
+ IndexSearcher searcher = newSearcher(reader);
+
+ for (String queryText : new String[] { "foo", "bar" }) {
+ Query query = new TermQuery(new Term("f", queryText));
+ for (boolean reverse : new boolean[] {false, true}) {
+ ScoreDoc[] sortedByDoc = searcher.search(query, 10).scoreDocs;
+ Arrays.sort(sortedByDoc, Comparator.comparingInt(sd -> sd.doc));
+
+ Sort sort = new Sort(new SortField("sort", SortField.Type.LONG, reverse));
+ ScoreDoc[] sortedByField = searcher.search(query, 10, sort).scoreDocs;
+ ScoreDoc[] sortedByFieldClone = sortedByField.clone();
+ TopFieldCollector.populateScores(sortedByFieldClone, searcher, query);
+ for (int i = 0; i < sortedByFieldClone.length; ++i) {
+ assertEquals(sortedByFieldClone[i].doc, sortedByField[i].doc);
+ assertSame(((FieldDoc) sortedByFieldClone[i]).fields, ((FieldDoc) sortedByField[i]).fields);
+ assertEquals(sortedByFieldClone[i].score,
+ sortedByDoc[Arrays.binarySearch(sortedByDoc, sortedByFieldClone[i], Comparator.comparingInt(sd -> sd.doc))].score, 0f);
+ }
+ }
+ }
+
+ reader.close();
+ dir.close();
+ }
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollectorEarlyTermination.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollectorEarlyTermination.java b/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollectorEarlyTermination.java
index b910dd8..18eec9e 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollectorEarlyTermination.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollectorEarlyTermination.java
@@ -136,9 +136,8 @@ public class TestTopFieldCollectorEarlyTermination extends LuceneTestCase {
} else {
after = null;
}
- final boolean trackDocScores = random().nextBoolean();
- final TopFieldCollector collector1 = TopFieldCollector.create(sort, numHits, after, trackDocScores, true);
- final TopFieldCollector collector2 = TopFieldCollector.create(sort, numHits, after, trackDocScores, false);
+ final TopFieldCollector collector1 = TopFieldCollector.create(sort, numHits, after, true);
+ final TopFieldCollector collector2 = TopFieldCollector.create(sort, numHits, after, false);
final Query query;
if (random().nextBoolean()) {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/facet/src/java/org/apache/lucene/facet/DrillSideways.java
----------------------------------------------------------------------
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/DrillSideways.java b/lucene/facet/src/java/org/apache/lucene/facet/DrillSideways.java
index 861a4a3..a2631c3 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/DrillSideways.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/DrillSideways.java
@@ -241,7 +241,7 @@ public class DrillSideways {
@Override
public TopFieldCollector newCollector() throws IOException {
- return TopFieldCollector.create(sort, fTopN, after, doDocScores, true);
+ return TopFieldCollector.create(sort, fTopN, after, true);
}
@Override
@@ -255,14 +255,22 @@ public class DrillSideways {
};
ConcurrentDrillSidewaysResult<TopFieldDocs> r = search(query, collectorManager);
- return new DrillSidewaysResult(r.facets, r.collectorResult);
+ TopFieldDocs topDocs = r.collectorResult;
+ if (doDocScores) {
+ TopFieldCollector.populateScores(topDocs.scoreDocs, searcher, query);
+ }
+ return new DrillSidewaysResult(r.facets, topDocs);
} else {
final TopFieldCollector hitCollector =
- TopFieldCollector.create(sort, fTopN, after, doDocScores, true);
+ TopFieldCollector.create(sort, fTopN, after, true);
DrillSidewaysResult r = search(query, hitCollector);
- return new DrillSidewaysResult(r.facets, hitCollector.topDocs());
+ TopFieldDocs topDocs = hitCollector.topDocs();
+ if (doDocScores) {
+ TopFieldCollector.populateScores(topDocs.scoreDocs, searcher, query);
+ }
+ return new DrillSidewaysResult(r.facets, topDocs);
}
} else {
return search(after, query, topN);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.java
----------------------------------------------------------------------
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.java b/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.java
index 94b5f41..4e8b2c9 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.java
@@ -230,7 +230,6 @@ public class FacetsCollector extends SimpleCollector implements Collector {
}
hitsCollector = TopFieldCollector.create(sort, n,
(FieldDoc) after,
- doDocScores,
true); // TODO: can we disable exact hit counts
} else {
hitsCollector = TopScoreDocCollector.create(n, after, true);
@@ -238,6 +237,9 @@ public class FacetsCollector extends SimpleCollector implements Collector {
searcher.search(q, MultiCollector.wrap(hitsCollector, fc));
topDocs = hitsCollector.topDocs();
+ if (doDocScores) {
+ TopFieldCollector.populateScores(topDocs.scoreDocs, searcher, q);
+ }
}
return topDocs;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java
----------------------------------------------------------------------
diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java
index 80af1b8..200d5e7 100644
--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java
+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java
@@ -304,7 +304,7 @@ public class BlockGroupingCollector extends SimpleCollector {
collector = TopScoreDocCollector.create(maxDocsPerGroup);
} else {
// Sort by fields
- collector = TopFieldCollector.create(withinGroupSort, maxDocsPerGroup, needsScores, true); // TODO: disable exact counts?
+ collector = TopFieldCollector.create(withinGroupSort, maxDocsPerGroup, true); // TODO: disable exact counts?
}
float groupMaxScore = needsScores ? Float.NEGATIVE_INFINITY : Float.NaN;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java
----------------------------------------------------------------------
diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java
index a1f4bf8..8388480 100644
--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java
+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java
@@ -50,7 +50,6 @@ public class GroupingSearch {
private int groupDocsOffset;
private int groupDocsLimit = 1;
- private boolean includeScores = true;
private boolean includeMaxScore = true;
private Double maxCacheRAMMB;
@@ -153,8 +152,7 @@ public class GroupingSearch {
int topNInsideGroup = groupDocsOffset + groupDocsLimit;
TopGroupsCollector secondPassCollector
- = new TopGroupsCollector(grouper, topSearchGroups, groupSort, sortWithinGroup, topNInsideGroup,
- includeScores, includeMaxScore);
+ = new TopGroupsCollector(grouper, topSearchGroups, groupSort, sortWithinGroup, topNInsideGroup, includeMaxScore);
if (cachedCollector != null && cachedCollector.isCached()) {
cachedCollector.replay(secondPassCollector);
@@ -173,7 +171,7 @@ public class GroupingSearch {
int topN = groupOffset + groupLimit;
final Query endDocsQuery = searcher.rewrite(this.groupEndDocs);
final Weight groupEndDocs = searcher.createWeight(endDocsQuery, ScoreMode.COMPLETE_NO_SCORES, 1);
- BlockGroupingCollector c = new BlockGroupingCollector(groupSort, topN, includeScores, groupEndDocs);
+ BlockGroupingCollector c = new BlockGroupingCollector(groupSort, topN, groupSort.needsScores() || sortWithinGroup.needsScores(), groupEndDocs);
searcher.search(query, c);
int topNInsideGroup = groupDocsOffset + groupDocsLimit;
return c.getTopGroups(sortWithinGroup, groupOffset, groupDocsOffset, topNInsideGroup);
@@ -269,17 +267,6 @@ public class GroupingSearch {
}
/**
- * Whether to include the scores per doc inside a group.
- *
- * @param includeScores Whether to include the scores per doc inside a group
- * @return <code>this</code>
- */
- public GroupingSearch setIncludeScores(boolean includeScores) {
- this.includeScores = includeScores;
- return this;
- }
-
- /**
* Whether to include the score of the most relevant document per group.
*
* @param includeMaxScore Whether to include the score of the most relevant document per group
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroupsCollector.java
----------------------------------------------------------------------
diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroupsCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroupsCollector.java
index 519bd89..16dcebb 100644
--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroupsCollector.java
+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroupsCollector.java
@@ -54,13 +54,12 @@ public class TopGroupsCollector<T> extends SecondPassGroupingCollector<T> {
* @param groupSort the order in which groups are returned
* @param withinGroupSort the order in which documents are sorted in each group
* @param maxDocsPerGroup the maximum number of docs to collect for each group
- * @param getScores if true, record the scores of all docs in each group
* @param getMaxScores if true, record the maximum score for each group
*/
public TopGroupsCollector(GroupSelector<T> groupSelector, Collection<SearchGroup<T>> groups, Sort groupSort, Sort withinGroupSort,
- int maxDocsPerGroup, boolean getScores, boolean getMaxScores) {
+ int maxDocsPerGroup, boolean getMaxScores) {
super(groupSelector, groups,
- new TopDocsReducer<>(withinGroupSort, maxDocsPerGroup, getScores, getMaxScores));
+ new TopDocsReducer<>(withinGroupSort, maxDocsPerGroup, getMaxScores));
this.groupSort = Objects.requireNonNull(groupSort);
this.withinGroupSort = Objects.requireNonNull(withinGroupSort);
this.maxDocsPerGroup = maxDocsPerGroup;
@@ -114,13 +113,13 @@ public class TopGroupsCollector<T> extends SecondPassGroupingCollector<T> {
private final boolean needsScores;
TopDocsReducer(Sort withinGroupSort,
- int maxDocsPerGroup, boolean getScores, boolean getMaxScores) {
- this.needsScores = getScores || getMaxScores || withinGroupSort.needsScores();
+ int maxDocsPerGroup, boolean getMaxScores) {
+ this.needsScores = getMaxScores || withinGroupSort.needsScores();
if (withinGroupSort == Sort.RELEVANCE) {
supplier = () -> new TopDocsAndMaxScoreCollector(true, TopScoreDocCollector.create(maxDocsPerGroup), null);
} else {
supplier = () -> {
- TopFieldCollector topDocsCollector = TopFieldCollector.create(withinGroupSort, maxDocsPerGroup, getScores, true); // TODO: disable exact counts?
+ TopFieldCollector topDocsCollector = TopFieldCollector.create(withinGroupSort, maxDocsPerGroup, true); // TODO: disable exact counts?
MaxScoreCollector maxScoreCollector = getMaxScores ? new MaxScoreCollector() : null;
return new TopDocsAndMaxScoreCollector(false, topDocsCollector, maxScoreCollector);
};
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
----------------------------------------------------------------------
diff --git a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
index bf36853..8415f6a 100644
--- a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
+++ b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
@@ -145,7 +145,7 @@ public class TestGrouping extends LuceneTestCase {
final FirstPassGroupingCollector<?> c1 = createRandomFirstPassCollector(groupField, groupSort, 10);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
- final TopGroupsCollector<?> c2 = createSecondPassCollector(c1, groupSort, Sort.RELEVANCE, 0, 5, true, true);
+ final TopGroupsCollector<?> c2 = createSecondPassCollector(c1, groupSort, Sort.RELEVANCE, 0, 5, true);
indexSearcher.search(new TermQuery(new Term("content", "random")), c2);
final TopGroups<?> groups = c2.getTopGroups(0);
@@ -218,11 +218,10 @@ public class TestGrouping extends LuceneTestCase {
Sort sortWithinGroup,
int groupOffset,
int maxDocsPerGroup,
- boolean getScores,
boolean getMaxScores) throws IOException {
Collection<SearchGroup<T>> searchGroups = firstPassGroupingCollector.getTopGroups(groupOffset);
- return new TopGroupsCollector<>(firstPassGroupingCollector.getGroupSelector(), searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getScores, getMaxScores);
+ return new TopGroupsCollector<>(firstPassGroupingCollector.getGroupSelector(), searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getMaxScores);
}
// Basically converts searchGroups from MutableValue to BytesRef if grouping by ValueSource
@@ -233,11 +232,10 @@ public class TestGrouping extends LuceneTestCase {
Sort groupSort,
Sort sortWithinGroup,
int maxDocsPerGroup,
- boolean getScores,
boolean getMaxScores) throws IOException {
if (firstPassGroupingCollector.getGroupSelector().getClass().isAssignableFrom(TermGroupSelector.class)) {
GroupSelector<BytesRef> selector = (GroupSelector<BytesRef>) firstPassGroupingCollector.getGroupSelector();
- return new TopGroupsCollector<>(selector, searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup , getScores, getMaxScores);
+ return new TopGroupsCollector<>(selector, searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getMaxScores);
} else {
ValueSource vs = new BytesRefFieldSource(groupField);
List<SearchGroup<MutableValue>> mvalSearchGroups = new ArrayList<>(searchGroups.size());
@@ -254,7 +252,7 @@ public class TestGrouping extends LuceneTestCase {
mvalSearchGroups.add(sg);
}
ValueSourceGroupSelector selector = new ValueSourceGroupSelector(vs, new HashMap<>());
- return new TopGroupsCollector<>(selector, mvalSearchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getScores, getMaxScores);
+ return new TopGroupsCollector<>(selector, mvalSearchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getMaxScores);
}
}
@@ -437,7 +435,6 @@ public class TestGrouping extends LuceneTestCase {
private TopGroups<BytesRef> slowGrouping(GroupDoc[] groupDocs,
String searchTerm,
- boolean getScores,
boolean getMaxScores,
boolean doAllGroups,
Sort groupSort,
@@ -507,7 +504,7 @@ public class TestGrouping extends LuceneTestCase {
for(int docIDX=docOffset; docIDX < docIDXLimit; docIDX++) {
final GroupDoc d = docs.get(docIDX);
final FieldDoc fd;
- fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN, fillFields(d, docSort));
+ fd = new FieldDoc(d.id, Float.NaN, fillFields(d, docSort));
hits[docIDX-docOffset] = fd;
}
} else {
@@ -829,14 +826,11 @@ public class TestGrouping extends LuceneTestCase {
}
final String searchTerm = "real" + random().nextInt(3);
- boolean getScores = random().nextBoolean();
final boolean getMaxScores = random().nextBoolean();
final Sort groupSort = getRandomSort();
//final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)});
final Sort docSort = getRandomSort();
- getScores |= (groupSort.needsScores() || docSort.needsScores());
-
final int topNGroups = TestUtil.nextInt(random(), 1, 30);
//final int topNGroups = 10;
final int docsPerGroup = TestUtil.nextInt(random(), 1, 50);
@@ -850,7 +844,7 @@ public class TestGrouping extends LuceneTestCase {
final boolean doCache = random().nextBoolean();
final boolean doAllGroups = random().nextBoolean();
if (VERBOSE) {
- System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " dF=" + r.docFreq(new Term("content", searchTerm)) +" dFBlock=" + rBlocks.docFreq(new Term("content", searchTerm)) + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores);
+ System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " dF=" + r.docFreq(new Term("content", searchTerm)) +" dFBlock=" + rBlocks.docFreq(new Term("content", searchTerm)) + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getMaxScores=" + getMaxScores);
}
String groupField = "group";
@@ -935,7 +929,7 @@ public class TestGrouping extends LuceneTestCase {
// Get 1st pass top groups using shards
final TopGroups<BytesRef> topGroupsShards = searchShards(s, shards.subSearchers, query, groupSort, docSort,
- groupOffset, topNGroups, docOffset, docsPerGroup, getScores, getMaxScores, true, true);
+ groupOffset, topNGroups, docOffset, docsPerGroup, getMaxScores, true, true);
final TopGroupsCollector<?> c2;
if (topGroups != null) {
@@ -946,7 +940,7 @@ public class TestGrouping extends LuceneTestCase {
}
}
- c2 = createSecondPassCollector(c1, groupSort, docSort, groupOffset, docOffset + docsPerGroup, getScores, getMaxScores);
+ c2 = createSecondPassCollector(c1, groupSort, docSort, groupOffset, docOffset + docsPerGroup, getMaxScores);
if (doCache) {
if (cCache.isCached()) {
if (VERBOSE) {
@@ -977,7 +971,7 @@ public class TestGrouping extends LuceneTestCase {
}
}
- final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset);
+ final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset);
if (VERBOSE) {
if (expectedGroups == null) {
@@ -1023,17 +1017,16 @@ public class TestGrouping extends LuceneTestCase {
}
}
- assertEquals(docIDToID, expectedGroups, groupsResult, true, true, getScores, true);
+ assertEquals(docIDToID, expectedGroups, groupsResult, true, true, true);
// Confirm merged shards match:
- assertEquals(docIDToID, expectedGroups, topGroupsShards, true, false, getScores, true);
+ assertEquals(docIDToID, expectedGroups, topGroupsShards, true, false, true);
if (topGroupsShards != null) {
verifyShards(shards.docStarts, topGroupsShards);
}
-
- final boolean needsScores = getScores || getMaxScores || docSort == null;
- final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores,
- sBlocks.createWeight(sBlocks.rewrite(lastDocInBlock), ScoreMode.COMPLETE_NO_SCORES, 1));
+
+ final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups,
+ groupSort.needsScores() || docSort.needsScores(), sBlocks.createWeight(sBlocks.rewrite(lastDocInBlock), ScoreMode.COMPLETE_NO_SCORES, 1));
final AllGroupsCollector<BytesRef> allGroupsCollector2;
final Collector c4;
if (doAllGroups) {
@@ -1079,7 +1072,7 @@ public class TestGrouping extends LuceneTestCase {
// Get shard'd block grouping result:
final TopGroups<BytesRef> topGroupsBlockShards = searchShards(sBlocks, shardsBlocks.subSearchers, query,
- groupSort, docSort, groupOffset, topNGroups, docOffset, docsPerGroup, getScores, getMaxScores, false, false);
+ groupSort, docSort, groupOffset, topNGroups, docOffset, docsPerGroup, getMaxScores, false, false);
if (expectedGroups != null) {
// Fixup scores for reader2
@@ -1122,8 +1115,8 @@ public class TestGrouping extends LuceneTestCase {
}
}
- assertEquals(docIDToIDBlocks, expectedGroups, groupsResultBlocks, false, true, getScores, false);
- assertEquals(docIDToIDBlocks, expectedGroups, topGroupsBlockShards, false, false, getScores, false);
+ assertEquals(docIDToIDBlocks, expectedGroups, groupsResultBlocks, false, true, false);
+ assertEquals(docIDToIDBlocks, expectedGroups, topGroupsBlockShards, false, false, false);
}
r.close();
@@ -1146,7 +1139,7 @@ public class TestGrouping extends LuceneTestCase {
}
private TopGroups<BytesRef> searchShards(IndexSearcher topSearcher, ShardSearcher[] subSearchers, Query query, Sort groupSort, Sort docSort, int groupOffset, int topNGroups, int docOffset,
- int topNDocs, boolean getScores, boolean getMaxScores, boolean canUseIDV, boolean preFlex) throws Exception {
+ int topNDocs, boolean getMaxScores, boolean canUseIDV, boolean preFlex) throws Exception {
// TODO: swap in caching, all groups collector hereassertEquals(expected.totalHitCount, actual.totalHitCount);
// too...
@@ -1154,7 +1147,7 @@ public class TestGrouping extends LuceneTestCase {
System.out.println("TEST: " + subSearchers.length + " shards: " + Arrays.toString(subSearchers) + " canUseIDV=" + canUseIDV);
}
// Run 1st pass collector to get top groups per shard
- final Weight w = topSearcher.createWeight(topSearcher.rewrite(query), getScores || getMaxScores ? ScoreMode.COMPLETE : ScoreMode.COMPLETE_NO_SCORES, 1);
+ final Weight w = topSearcher.createWeight(topSearcher.rewrite(query), groupSort.needsScores() || docSort.needsScores() || getMaxScores ? ScoreMode.COMPLETE : ScoreMode.COMPLETE_NO_SCORES, 1);
final List<Collection<SearchGroup<BytesRef>>> shardGroups = new ArrayList<>();
List<FirstPassGroupingCollector<?>> firstPassGroupingCollectors = new ArrayList<>();
FirstPassGroupingCollector<?> firstPassCollector = null;
@@ -1208,7 +1201,7 @@ public class TestGrouping extends LuceneTestCase {
final TopGroups<BytesRef>[] shardTopGroups = new TopGroups[subSearchers.length];
for(int shardIDX=0;shardIDX<subSearchers.length;shardIDX++) {
final TopGroupsCollector<?> secondPassCollector = createSecondPassCollector(firstPassGroupingCollectors.get(shardIDX),
- groupField, mergedTopGroups, groupSort, docSort, docOffset + topNDocs, getScores, getMaxScores);
+ groupField, mergedTopGroups, groupSort, docSort, docOffset + topNDocs, getMaxScores);
subSearchers[shardIDX].search(w, secondPassCollector);
shardTopGroups[shardIDX] = getTopGroups(secondPassCollector, 0);
if (VERBOSE) {
@@ -1232,7 +1225,7 @@ public class TestGrouping extends LuceneTestCase {
}
}
- private void assertEquals(int[] docIDtoID, TopGroups<BytesRef> expected, TopGroups<BytesRef> actual, boolean verifyGroupValues, boolean verifyTotalGroupCount, boolean testScores, boolean idvBasedImplsUsed) {
+ private void assertEquals(int[] docIDtoID, TopGroups<BytesRef> expected, TopGroups<BytesRef> actual, boolean verifyGroupValues, boolean verifyTotalGroupCount, boolean idvBasedImplsUsed) {
if (expected == null) {
assertNull(actual);
return;
@@ -1279,12 +1272,6 @@ public class TestGrouping extends LuceneTestCase {
final FieldDoc actualFD = (FieldDoc) actualFDs[docIDX];
//System.out.println(" actual doc=" + docIDtoID[actualFD.doc] + " score=" + actualFD.score);
assertEquals(expectedFD.doc, docIDtoID[actualFD.doc]);
- if (testScores) {
- assertEquals(expectedFD.score, actualFD.score, 0.1);
- } else {
- // TODO: too anal for now
- //assertEquals(Float.NaN, actualFD.score);
- }
assertArrayEquals(expectedFD.fields, actualFD.fields);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggester.java
----------------------------------------------------------------------
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggester.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggester.java
index 35cb3df..07180e3 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggester.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggester.java
@@ -647,7 +647,7 @@ public class AnalyzingInfixSuggester extends Lookup implements Closeable {
//System.out.println("finalQuery=" + finalQuery);
// Sort by weight, descending:
- TopFieldCollector c = TopFieldCollector.create(SORT, num, false, false);
+ TopFieldCollector c = TopFieldCollector.create(SORT, num, false);
List<LookupResult> results = null;
SearcherManager mgr;
IndexSearcher searcher;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java b/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java
index 3b81914..1354ea8 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java
@@ -535,7 +535,7 @@ public class ExpandComponent extends SearchComponent implements PluginInfoInitia
DocIdSetIterator iterator = new BitSetIterator(groupBits, 0); // cost is not useful here
int group;
while ((group = iterator.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
- Collector collector = (sort == null) ? TopScoreDocCollector.create(limit) : TopFieldCollector.create(sort, limit, false, true);
+ Collector collector = (sort == null) ? TopScoreDocCollector.create(limit) : TopFieldCollector.create(sort, limit, true);
groups.put(group, collector);
}
@@ -619,7 +619,7 @@ public class ExpandComponent extends SearchComponent implements PluginInfoInitia
Iterator<LongCursor> iterator = groupSet.iterator();
while (iterator.hasNext()) {
LongCursor cursor = iterator.next();
- Collector collector = (sort == null) ? TopScoreDocCollector.create(limit) : TopFieldCollector.create(sort, limit, false, true);
+ Collector collector = (sort == null) ? TopScoreDocCollector.create(limit) : TopFieldCollector.create(sort, limit, true);
groups.put(cursor.value, collector);
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.java b/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.java
index 1a34b58..2ec8cc4 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.java
@@ -1327,6 +1327,7 @@ public class QueryComponent extends SearchComponent
secondPhaseBuilder.addCommandField(
new TopGroupsFieldCommand.Builder()
+ .setQuery(cmd.getQuery())
.setField(schemaField)
.setGroupSort(groupingSpec.getGroupSort())
.setSortWithinGroup(groupingSpec.getSortWithinGroup())
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/search/Grouping.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/Grouping.java b/solr/core/src/java/org/apache/solr/search/Grouping.java
index ba8f4cd..cb7dccd 100644
--- a/solr/core/src/java/org/apache/solr/search/Grouping.java
+++ b/solr/core/src/java/org/apache/solr/search/Grouping.java
@@ -590,6 +590,14 @@ public class Grouping {
return null;
}
+ protected void populateScoresIfNecessary() throws IOException {
+ if (needScores) {
+ for (GroupDocs<?> groups : result.groups) {
+ TopFieldCollector.populateScores(groups.scoreDocs, searcher, query);
+ }
+ }
+ }
+
protected NamedList commonResponse() {
NamedList groupResult = new SimpleOrderedMap();
grouped.add(key, groupResult); // grouped={ key={
@@ -747,7 +755,7 @@ public class Grouping {
groupedDocsToCollect = Math.max(groupedDocsToCollect, 1);
Sort withinGroupSort = this.withinGroupSort != null ? this.withinGroupSort : Sort.RELEVANCE;
secondPass = new TopGroupsCollector<>(new TermGroupSelector(groupBy),
- topGroups, groupSort, withinGroupSort, groupedDocsToCollect, needScores, needScores
+ topGroups, groupSort, withinGroupSort, groupedDocsToCollect, needScores
);
if (totalCount == TotalCount.grouped) {
@@ -766,7 +774,10 @@ public class Grouping {
@Override
protected void finish() throws IOException {
- result = secondPass != null ? secondPass.getTopGroups(0) : null;
+ if (secondPass != null) {
+ result = secondPass.getTopGroups(0);
+ populateScoresIfNecessary();
+ }
if (main) {
mainResult = createSimpleResponse();
return;
@@ -850,7 +861,7 @@ public class Grouping {
if (withinGroupSort == null || withinGroupSort.equals(Sort.RELEVANCE)) {
subCollector = topCollector = TopScoreDocCollector.create(groupDocsToCollect);
} else {
- topCollector = TopFieldCollector.create(searcher.weightSort(withinGroupSort), groupDocsToCollect, needScores, true);
+ topCollector = TopFieldCollector.create(searcher.weightSort(withinGroupSort), groupDocsToCollect, true);
if (needScores) {
maxScoreCollector = new MaxScoreCollector();
subCollector = MultiCollector.wrap(topCollector, maxScoreCollector);
@@ -952,7 +963,7 @@ public class Grouping {
groupdDocsToCollect = Math.max(groupdDocsToCollect, 1);
Sort withinGroupSort = this.withinGroupSort != null ? this.withinGroupSort : Sort.RELEVANCE;
secondPass = new TopGroupsCollector<>(newSelector(),
- topGroups, groupSort, withinGroupSort, groupdDocsToCollect, needScores, needScores
+ topGroups, groupSort, withinGroupSort, groupdDocsToCollect, needScores
);
if (totalCount == TotalCount.grouped) {
@@ -971,7 +982,10 @@ public class Grouping {
@Override
protected void finish() throws IOException {
- result = secondPass != null ? secondPass.getTopGroups(0) : null;
+ if (secondPass != null) {
+ result = secondPass.getTopGroups(0);
+ populateScoresIfNecessary();
+ }
if (main) {
mainResult = createSimpleResponse();
return;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/search/ReRankCollector.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/ReRankCollector.java b/solr/core/src/java/org/apache/solr/search/ReRankCollector.java
index 6b2588b..0888f79 100644
--- a/solr/core/src/java/org/apache/solr/search/ReRankCollector.java
+++ b/solr/core/src/java/org/apache/solr/search/ReRankCollector.java
@@ -27,6 +27,7 @@ import com.carrotsearch.hppc.IntIntHashMap;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.LeafCollector;
+import org.apache.lucene.search.Query;
import org.apache.lucene.search.Rescorer;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.ScoreMode;
@@ -49,6 +50,8 @@ public class ReRankCollector extends TopDocsCollector {
final private int length;
final private Set<BytesRef> boostedPriority; // order is the "priority"
final private Rescorer reRankQueryRescorer;
+ final private Sort sort;
+ final private Query query;
public ReRankCollector(int reRankDocs,
@@ -61,13 +64,15 @@ public class ReRankCollector extends TopDocsCollector {
this.reRankDocs = reRankDocs;
this.length = length;
this.boostedPriority = boostedPriority;
+ this.query = cmd.getQuery();
Sort sort = cmd.getSort();
if(sort == null) {
+ this.sort = null;
this.mainCollector = TopScoreDocCollector.create(Math.max(this.reRankDocs, length));
} else {
- sort = sort.rewrite(searcher);
+ this.sort = sort = sort.rewrite(searcher);
//scores are needed for Rescorer (regardless of whether sort needs it)
- this.mainCollector = TopFieldCollector.create(sort, Math.max(this.reRankDocs, length), true, true);
+ this.mainCollector = TopFieldCollector.create(sort, Math.max(this.reRankDocs, length), true);
}
this.searcher = searcher;
this.reRankQueryRescorer = reRankQueryRescorer;
@@ -84,7 +89,7 @@ public class ReRankCollector extends TopDocsCollector {
@Override
public ScoreMode scoreMode() {
- return ScoreMode.COMPLETE; // since the scores will be needed by Rescorer as input regardless of mainCollector
+ return sort == null || sort.needsScores() ? ScoreMode.COMPLETE : ScoreMode.COMPLETE_NO_SCORES;
}
public TopDocs topDocs(int start, int howMany) {
@@ -97,6 +102,10 @@ public class ReRankCollector extends TopDocsCollector {
return mainDocs;
}
+ if (sort != null) {
+ TopFieldCollector.populateScores(mainDocs.scoreDocs, searcher, query);
+ }
+
ScoreDoc[] mainScoreDocs = mainDocs.scoreDocs;
ScoreDoc[] reRankScoreDocs = new ScoreDoc[Math.min(mainScoreDocs.length, reRankDocs)];
System.arraycopy(mainScoreDocs, 0, reRankScoreDocs, 0, reRankScoreDocs.length);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java b/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java
index 30b0942..6cbcd0d 100644
--- a/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java
+++ b/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java
@@ -1532,12 +1532,11 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable, SolrI
return TopScoreDocCollector.create(len);
} else {
// we have a sort
- final boolean needScores = (cmd.getFlags() & GET_SCORES) != 0;
final Sort weightedSort = weightSort(cmd.getSort());
final CursorMark cursor = cmd.getCursorMark();
final FieldDoc searchAfter = (null != cursor ? cursor.getSearchAfterFieldDoc() : null);
- return TopFieldCollector.create(weightedSort, len, searchAfter, needScores, true);
+ return TopFieldCollector.create(weightedSort, len, searchAfter, true);
}
}
@@ -1624,6 +1623,9 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable, SolrI
totalHits = topCollector.getTotalHits();
TopDocs topDocs = topCollector.topDocs(0, len);
+ if (cmd.getSort() != null && query instanceof RankQuery == false && (cmd.getFlags() & GET_SCORES) != 0) {
+ TopFieldCollector.populateScores(topDocs.scoreDocs, this, query);
+ }
populateNextCursorMarkFromTopDocs(qr, cmd, topDocs);
maxScore = totalHits > 0 ? (maxScoreCollector == null ? Float.NaN : maxScoreCollector.getMaxScore()) : 0.0f;
@@ -1732,6 +1734,9 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable, SolrI
assert (totalHits == set.size());
TopDocs topDocs = topCollector.topDocs(0, len);
+ if (cmd.getSort() != null && query instanceof RankQuery == false && (cmd.getFlags() & GET_SCORES) != 0) {
+ TopFieldCollector.populateScores(topDocs.scoreDocs, this, query);
+ }
populateNextCursorMarkFromTopDocs(qr, cmd, topDocs);
maxScore = totalHits > 0 ? (maxScoreCollector == null ? Float.NaN : maxScoreCollector.getMaxScore()) : 0.0f;
nDocsReturned = topDocs.scoreDocs.length;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/search/grouping/Command.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/grouping/Command.java b/solr/core/src/java/org/apache/solr/search/grouping/Command.java
index 7391df6..9d64755 100644
--- a/solr/core/src/java/org/apache/solr/search/grouping/Command.java
+++ b/solr/core/src/java/org/apache/solr/search/grouping/Command.java
@@ -17,6 +17,7 @@
package org.apache.solr.search.grouping;
import org.apache.lucene.search.Collector;
+import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Sort;
import java.io.IOException;
import java.util.List;
@@ -40,6 +41,12 @@ public interface Command<T> {
List<Collector> create() throws IOException;
/**
+ * Run post-collection steps.
+ * @throws IOException If I/O related errors occur
+ */
+ default void postCollect(IndexSearcher searcher) throws IOException {}
+
+ /**
* Returns the results that the collectors created
* by {@link #create()} contain after a search has been executed.
*
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.java b/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.java
index 4ec01db..ec421e4 100644
--- a/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.java
+++ b/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.java
@@ -163,6 +163,10 @@ public class CommandHandler {
} else {
searchWithTimeLimiter(query, filter, null);
}
+
+ for (Command command : commands) {
+ command.postCollect(searcher);
+ }
}
private DocSet computeGroupedDocSet(Query query, ProcessedFilter filter, List<Collector> collectors) throws IOException {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/QueryCommand.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/QueryCommand.java b/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/QueryCommand.java
index f88f170..93b55b1 100644
--- a/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/QueryCommand.java
+++ b/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/QueryCommand.java
@@ -114,6 +114,7 @@ public class QueryCommand implements Command<QueryCommandResult> {
private TopDocsCollector topDocsCollector;
private FilterCollector filterCollector;
private MaxScoreCollector maxScoreCollector;
+ private TopDocs topDocs;
private QueryCommand(Sort sort, Query query, int docsToCollect, boolean needScores, DocSet docSet, String queryString) {
this.sort = sort;
@@ -130,7 +131,7 @@ public class QueryCommand implements Command<QueryCommandResult> {
if (sort == null || sort.equals(Sort.RELEVANCE)) {
subCollector = topDocsCollector = TopScoreDocCollector.create(docsToCollect);
} else {
- topDocsCollector = TopFieldCollector.create(sort, docsToCollect, needScores, true);
+ topDocsCollector = TopFieldCollector.create(sort, docsToCollect, true);
if (needScores) {
maxScoreCollector = new MaxScoreCollector();
subCollector = MultiCollector.wrap(topDocsCollector, maxScoreCollector);
@@ -143,8 +144,15 @@ public class QueryCommand implements Command<QueryCommandResult> {
}
@Override
- public QueryCommandResult result() {
- TopDocs topDocs = topDocsCollector.topDocs();
+ public void postCollect(IndexSearcher searcher) throws IOException {
+ topDocs = topDocsCollector.topDocs();
+ if (needScores) {
+ TopFieldCollector.populateScores(topDocs.scoreDocs, searcher, query);
+ }
+ }
+
+ @Override
+ public QueryCommandResult result() throws IOException {
float maxScore;
if (sort == null) {
maxScore = topDocs.scoreDocs.length == 0 ? Float.NaN : topDocs.scoreDocs[0].score;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java b/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java
index 157e10d..3902841 100644
--- a/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java
+++ b/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java
@@ -25,7 +25,10 @@ import java.util.List;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.search.Collector;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
+import org.apache.lucene.search.TopFieldCollector;
import org.apache.lucene.search.grouping.GroupDocs;
import org.apache.lucene.search.grouping.SearchGroup;
import org.apache.lucene.search.grouping.TermGroupSelector;
@@ -45,6 +48,7 @@ public class TopGroupsFieldCommand implements Command<TopGroups<BytesRef>> {
public static class Builder {
+ private Query query;
private SchemaField field;
private Sort groupSort;
private Sort withinGroupSort;
@@ -53,6 +57,11 @@ public class TopGroupsFieldCommand implements Command<TopGroups<BytesRef>> {
private boolean needScores = false;
private boolean needMaxScore = false;
+ public Builder setQuery(Query query) {
+ this.query = query;
+ return this;
+ }
+
public Builder setField(SchemaField field) {
this.field = field;
return this;
@@ -89,16 +98,17 @@ public class TopGroupsFieldCommand implements Command<TopGroups<BytesRef>> {
}
public TopGroupsFieldCommand build() {
- if (field == null || groupSort == null || withinGroupSort == null || firstPhaseGroups == null ||
+ if (query == null || field == null || groupSort == null || withinGroupSort == null || firstPhaseGroups == null ||
maxDocPerGroup == null) {
throw new IllegalStateException("All required fields must be set");
}
- return new TopGroupsFieldCommand(field, groupSort, withinGroupSort, firstPhaseGroups, maxDocPerGroup, needScores, needMaxScore);
+ return new TopGroupsFieldCommand(query, field, groupSort, withinGroupSort, firstPhaseGroups, maxDocPerGroup, needScores, needMaxScore);
}
}
+ private final Query query;
private final SchemaField field;
private final Sort groupSort;
private final Sort withinGroupSort;
@@ -107,14 +117,17 @@ public class TopGroupsFieldCommand implements Command<TopGroups<BytesRef>> {
private final boolean needScores;
private final boolean needMaxScore;
private TopGroupsCollector secondPassCollector;
+ private TopGroups<BytesRef> topGroups;
- private TopGroupsFieldCommand(SchemaField field,
+ private TopGroupsFieldCommand(Query query,
+ SchemaField field,
Sort groupSort,
Sort withinGroupSort,
Collection<SearchGroup<BytesRef>> firstPhaseGroups,
int maxDocPerGroup,
boolean needScores,
boolean needMaxScore) {
+ this.query = query;
this.field = field;
this.groupSort = groupSort;
this.withinGroupSort = withinGroupSort;
@@ -136,11 +149,11 @@ public class TopGroupsFieldCommand implements Command<TopGroups<BytesRef>> {
ValueSource vs = fieldType.getValueSource(field, null);
Collection<SearchGroup<MutableValue>> v = GroupConverter.toMutable(field, firstPhaseGroups);
secondPassCollector = new TopGroupsCollector<>(new ValueSourceGroupSelector(vs, new HashMap<>()),
- v, groupSort, withinGroupSort, maxDocPerGroup, needScores, needMaxScore
+ v, groupSort, withinGroupSort, maxDocPerGroup, needMaxScore
);
} else {
secondPassCollector = new TopGroupsCollector<>(new TermGroupSelector(field.getName()),
- firstPhaseGroups, groupSort, withinGroupSort, maxDocPerGroup, needScores, needMaxScore
+ firstPhaseGroups, groupSort, withinGroupSort, maxDocPerGroup, needMaxScore
);
}
collectors.add(secondPassCollector);
@@ -148,21 +161,30 @@ public class TopGroupsFieldCommand implements Command<TopGroups<BytesRef>> {
}
@Override
- @SuppressWarnings("unchecked")
- public TopGroups<BytesRef> result() {
+ public void postCollect(IndexSearcher searcher) throws IOException {
if (firstPhaseGroups.isEmpty()) {
- return new TopGroups<>(groupSort.getSort(), withinGroupSort.getSort(), 0, 0, new GroupDocs[0], Float.NaN);
+ topGroups = new TopGroups<>(groupSort.getSort(), withinGroupSort.getSort(), 0, 0, new GroupDocs[0], Float.NaN);
+ return;
}
FieldType fieldType = field.getType();
if (fieldType.getNumberType() != null) {
- return GroupConverter.fromMutable(field, secondPassCollector.getTopGroups(0));
+ topGroups = GroupConverter.fromMutable(field, secondPassCollector.getTopGroups(0));
} else {
- return secondPassCollector.getTopGroups(0);
+ topGroups = secondPassCollector.getTopGroups(0);
+ }
+ for (GroupDocs<?> group : topGroups.groups) {
+ TopFieldCollector.populateScores(group.scoreDocs, searcher, query);
}
}
@Override
+ @SuppressWarnings("unchecked")
+ public TopGroups<BytesRef> result() throws IOException {
+ return topGroups;
+ }
+
+ @Override
public String getKey() {
return field.getName();
}
[14/33] lucene-solr:jira/http2: SOLR-12305: When a replica is
applying updates, some kind of updates can skip buffering for faster recovery
Posted by da...@apache.org.
SOLR-12305: When a replica is applying updates, some kind of updates can skip buffering for faster recovery
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/8c06dec1
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/8c06dec1
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/8c06dec1
Branch: refs/heads/jira/http2
Commit: 8c06dec16dd711c097f4f8eaa7d9df041e0cb563
Parents: 6e3f61f
Author: Cao Manh Dat <da...@apache.org>
Authored: Mon Jul 23 09:33:28 2018 +0700
Committer: Cao Manh Dat <da...@apache.org>
Committed: Mon Jul 23 09:33:28 2018 +0700
----------------------------------------------------------------------
solr/CHANGES.txt | 3 ++
.../processor/DistributedUpdateProcessor.java | 19 +++++--
.../DistributedUpdateProcessorTest.java | 54 ++++++++++++++++++++
3 files changed, 72 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8c06dec1/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index e6d468c..e93e0e7 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -173,6 +173,9 @@ Optimizations
which we can export is directly proportional to the number of sort fields specified. This change also allows streaming
expressions to group by on more than 4 fields. (Aroop Ganguly, Amrit Sarkar, Varun Thacker)
+* SOLR-12305: When a replica is applying updates, some kind of updates can skip buffering for faster recovery.
+ (Cao Manh Dat)
+
Other Changes
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8c06dec1/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
index 8f87510..8d715a6 100644
--- a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
+++ b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
@@ -31,6 +31,7 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
+import com.google.common.annotations.VisibleForTesting;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRefBuilder;
import org.apache.solr.client.solrj.SolrRequest;
@@ -1083,7 +1084,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
// The leader forwarded us this update.
cmd.setVersion(versionOnUpdate);
- if (ulog.getState() != UpdateLog.State.ACTIVE && isReplayOrPeersync == false) {
+ if (shouldBufferUpdate(cmd, isReplayOrPeersync, ulog.getState())) {
// we're not in an active state, and this update isn't from a replay, so buffer it.
cmd.setFlags(cmd.getFlags() | UpdateCommand.BUFFERING);
ulog.add(cmd);
@@ -1132,9 +1133,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
}
}
}
- }
-
- if (!cmd.isInPlaceUpdate()) {
+ } else {
// if we aren't the leader, then we need to check that updates were not re-ordered
if (bucketVersion != 0 && bucketVersion < versionOnUpdate) {
// we're OK... this update has a version higher than anything we've seen
@@ -1178,6 +1177,18 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
return false;
}
+ @VisibleForTesting
+ boolean shouldBufferUpdate(AddUpdateCommand cmd, boolean isReplayOrPeersync, UpdateLog.State state) {
+ if (state == UpdateLog.State.APPLYING_BUFFERED
+ && !isReplayOrPeersync
+ && !cmd.isInPlaceUpdate()) {
+ // this a new update sent from the leader, it contains whole document therefore it won't depend on other updates
+ return false;
+ }
+
+ return state != UpdateLog.State.ACTIVE && isReplayOrPeersync == false;
+ }
+
/**
* This method checks the update/transaction logs and index to find out if the update ("previous update") that the current update
* depends on (in the case that this current update is an in-place update) has already been completed. If not,
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8c06dec1/solr/core/src/test/org/apache/solr/update/processor/DistributedUpdateProcessorTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/update/processor/DistributedUpdateProcessorTest.java b/solr/core/src/test/org/apache/solr/update/processor/DistributedUpdateProcessorTest.java
new file mode 100644
index 0000000..8f56d68
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/update/processor/DistributedUpdateProcessorTest.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.update.processor;
+
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.request.LocalSolrQueryRequest;
+import org.apache.solr.request.SolrQueryRequest;
+import org.apache.solr.update.AddUpdateCommand;
+import org.apache.solr.update.UpdateLog;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class DistributedUpdateProcessorTest extends SolrTestCaseJ4 {
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ initCore("solr/collection1/conf/solrconfig.xml","solr/collection1/conf/schema-minimal.xml");
+ }
+
+ @Test
+ public void testShouldBufferUpdate() {
+ SolrQueryRequest req = new LocalSolrQueryRequest(h.getCore(), new ModifiableSolrParams());
+ DistributedUpdateProcessor processor = new DistributedUpdateProcessor(
+ req, null, null, null);
+
+ AddUpdateCommand cmd = new AddUpdateCommand(req);
+ // applying buffer updates, isReplayOrPeerSync flag doesn't matter
+ assertFalse(processor.shouldBufferUpdate(cmd, false, UpdateLog.State.APPLYING_BUFFERED));
+ assertFalse(processor.shouldBufferUpdate(cmd, true, UpdateLog.State.APPLYING_BUFFERED));
+
+ assertTrue(processor.shouldBufferUpdate(cmd, false, UpdateLog.State.BUFFERING));
+ // this is not an buffer updates and it depend on other updates
+ cmd.prevVersion = 10;
+ assertTrue(processor.shouldBufferUpdate(cmd, false, UpdateLog.State.APPLYING_BUFFERED));
+ }
+
+
+}
[08/33] lucene-solr:jira/http2: SOLR-11598: Support more than 4 sort
fields in the export writer
Posted by da...@apache.org.
SOLR-11598: Support more than 4 sort fields in the export writer
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/9d9c3a0c
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/9d9c3a0c
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/9d9c3a0c
Branch: refs/heads/jira/http2
Commit: 9d9c3a0cd87832980a4745ec96fb2cd1216dcb4e
Parents: 509561b
Author: Varun Thacker <va...@apache.org>
Authored: Fri Jul 20 11:38:02 2018 -0700
Committer: Varun Thacker <va...@apache.org>
Committed: Fri Jul 20 11:38:07 2018 -0700
----------------------------------------------------------------------
solr/CHANGES.txt | 4 +
.../org/apache/solr/handler/ExportHandler.java | 1 +
.../org/apache/solr/handler/ExportWriter.java | 1764 ------------------
.../solr/handler/export/BoolFieldWriter.java | 52 +
.../solr/handler/export/DateFieldWriter.java | 46 +
.../apache/solr/handler/export/DoubeValue.java | 81 +
.../apache/solr/handler/export/DoubleCmp.java | 43 +
.../solr/handler/export/DoubleFieldWriter.java | 45 +
.../solr/handler/export/ExportWriter.java | 448 +++++
.../apache/solr/handler/export/FieldWriter.java | 27 +
.../apache/solr/handler/export/FloatCmp.java | 44 +
.../solr/handler/export/FloatFieldWriter.java | 45 +
.../apache/solr/handler/export/FloatValue.java | 78 +
.../org/apache/solr/handler/export/IntComp.java | 45 +
.../solr/handler/export/IntFieldWriter.java | 45 +
.../apache/solr/handler/export/IntValue.java | 77 +
.../org/apache/solr/handler/export/LongCmp.java | 45 +
.../solr/handler/export/LongFieldWriter.java | 45 +
.../apache/solr/handler/export/LongValue.java | 78 +
.../solr/handler/export/MultiFieldWriter.java | 104 ++
.../solr/handler/export/PriorityQueue.java | 218 +++
.../org/apache/solr/handler/export/SortDoc.java | 114 ++
.../apache/solr/handler/export/SortQueue.java | 52 +
.../apache/solr/handler/export/SortValue.java | 30 +
.../solr/handler/export/StringFieldWriter.java | 52 +
.../apache/solr/handler/export/StringValue.java | 99 +
.../solr/handler/export/package-info.java | 23 +
.../collection1/conf/schema-sortingresponse.xml | 5 +-
.../solr/handler/export/TestExportWriter.java | 749 ++++++++
.../apache/solr/response/TestExportWriter.java | 370 ----
.../src/exporting-result-sets.adoc | 3 +-
.../src/parallel-sql-interface.adoc | 4 -
.../org/apache/solr/common/SolrException.java | 2 +-
33 files changed, 2697 insertions(+), 2141 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 449f91d..e6d468c 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -169,6 +169,10 @@ Optimizations
* SOLR-11654: Time Routed Alias will now route documents to the ideal shard of a collection, thus avoiding a hop.
Usually documents were already routed well but not always. (Gus Heck, David Smiley)
+* SOLR-11598: The export handler does not limit users to 4 sort fields and is now unlimited. However the speed at
+ which we can export is directly proportional to the number of sort fields specified. This change also allows streaming
+ expressions to group by on more than 4 fields. (Aroop Ganguly, Amrit Sarkar, Varun Thacker)
+
Other Changes
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/ExportHandler.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/ExportHandler.java b/solr/core/src/java/org/apache/solr/handler/ExportHandler.java
index 9c75ef0..ea9239d 100644
--- a/solr/core/src/java/org/apache/solr/handler/ExportHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/ExportHandler.java
@@ -25,6 +25,7 @@ import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.handler.component.SearchHandler;
+import org.apache.solr.handler.export.ExportWriter;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/ExportWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/ExportWriter.java b/solr/core/src/java/org/apache/solr/handler/ExportWriter.java
deleted file mode 100644
index f618eef..0000000
--- a/solr/core/src/java/org/apache/solr/handler/ExportWriter.java
+++ /dev/null
@@ -1,1764 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.solr.handler;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.lang.invoke.MethodHandles;
-import java.nio.charset.StandardCharsets;
-import java.util.Date;
-import java.util.List;
-import java.util.function.LongFunction;
-
-import org.apache.lucene.index.DocValues;
-import org.apache.lucene.index.IndexableField;
-import org.apache.lucene.index.LeafReader;
-import org.apache.lucene.index.LeafReaderContext;
-import org.apache.lucene.index.MultiDocValues;
-import org.apache.lucene.index.NumericDocValues;
-import org.apache.lucene.index.OrdinalMap;
-import org.apache.lucene.index.SortedDocValues;
-import org.apache.lucene.index.SortedNumericDocValues;
-import org.apache.lucene.index.SortedSetDocValues;
-import org.apache.lucene.search.DocIdSetIterator;
-import org.apache.lucene.search.Sort;
-import org.apache.lucene.search.SortField;
-import org.apache.lucene.util.ArrayUtil;
-import org.apache.lucene.util.BitSetIterator;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.CharsRefBuilder;
-import org.apache.lucene.util.FixedBitSet;
-import org.apache.lucene.util.LongValues;
-import org.apache.lucene.util.NumericUtils;
-import org.apache.solr.client.solrj.impl.BinaryResponseParser;
-import org.apache.solr.common.IteratorWriter;
-import org.apache.solr.common.MapWriter.EntryWriter;
-import org.apache.solr.common.MapWriter;
-import org.apache.solr.common.PushWriter;
-import org.apache.solr.common.SolrException;
-import org.apache.solr.common.params.SolrParams;
-import org.apache.solr.common.util.JavaBinCodec;
-import org.apache.solr.core.SolrCore;
-import org.apache.solr.request.SolrQueryRequest;
-import org.apache.solr.request.SolrRequestInfo;
-import org.apache.solr.response.BinaryResponseWriter;
-import org.apache.solr.response.JSONResponseWriter;
-import org.apache.solr.response.QueryResponseWriter;
-import org.apache.solr.response.SolrQueryResponse;
-import org.apache.solr.schema.BoolField;
-import org.apache.solr.schema.DateValueFieldType;
-import org.apache.solr.schema.DoubleValueFieldType;
-import org.apache.solr.schema.FieldType;
-import org.apache.solr.schema.FloatValueFieldType;
-import org.apache.solr.schema.IndexSchema;
-import org.apache.solr.schema.IntValueFieldType;
-import org.apache.solr.schema.LongValueFieldType;
-import org.apache.solr.schema.SchemaField;
-import org.apache.solr.schema.StrField;
-import org.apache.solr.search.SolrIndexSearcher;
-import org.apache.solr.search.SortSpec;
-import org.apache.solr.search.SyntaxError;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import static java.util.Collections.singletonList;
-import static java.util.Collections.singletonMap;
-import static org.apache.solr.common.util.Utils.makeMap;
-
-public class ExportWriter implements SolrCore.RawWriter, Closeable {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- private OutputStreamWriter respWriter;
- final SolrQueryRequest req;
- final SolrQueryResponse res;
- FieldWriter[] fieldWriters;
- int totalHits = 0;
- FixedBitSet[] sets = null;
- PushWriter writer;
- private String wt;
-
-
- ExportWriter(SolrQueryRequest req, SolrQueryResponse res, String wt) {
- this.req = req;
- this.res = res;
- this.wt = wt;
-
- }
-
- @Override
- public String getContentType() {
- if ("javabin".equals(wt)) {
- return BinaryResponseParser.BINARY_CONTENT_TYPE;
- } else return "json";
- }
-
- @Override
- public void close() throws IOException {
- if (writer != null) writer.close();
- if (respWriter != null) {
- respWriter.flush();
- respWriter.close();
- }
-
- }
-
- protected void writeException(Exception e, PushWriter w, boolean log) throws IOException {
- w.writeMap(mw -> {
- mw.put("responseHeader", singletonMap("status", 400))
- .put("response", makeMap(
- "numFound", 0,
- "docs", singletonList(singletonMap("EXCEPTION", e.getMessage()))));
- });
- if (log) {
- SolrException.log(logger, e);
- }
- }
-
- public void write(OutputStream os) throws IOException {
- QueryResponseWriter rw = req.getCore().getResponseWriters().get(wt);
- if (rw instanceof BinaryResponseWriter) {
- //todo add support for other writers after testing
- writer = new JavaBinCodec(os, null);
- } else {
- respWriter = new OutputStreamWriter(os, StandardCharsets.UTF_8);
- writer = JSONResponseWriter.getPushWriter(respWriter, req, res);
- }
- Exception exception = res.getException();
- if (exception != null) {
- if (!(exception instanceof IgnoreException)) {
- writeException(exception, writer, false);
- }
- return;
- }
-
- SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
- SortSpec sortSpec = info.getResponseBuilder().getSortSpec();
-
- if(sortSpec == null) {
- writeException((new IOException(new SyntaxError("No sort criteria was provided."))), writer, true);
- return;
- }
-
- SolrIndexSearcher searcher = req.getSearcher();
- Sort sort = searcher.weightSort(sortSpec.getSort());
-
- if(sort == null) {
- writeException((new IOException(new SyntaxError("No sort criteria was provided."))), writer, true);
- return;
- }
-
- if(sort != null && sort.needsScores()) {
- writeException((new IOException(new SyntaxError("Scoring is not currently supported with xsort."))), writer, true);
- return;
- }
-
- // There is a bailout in SolrIndexSearcher.getDocListNC when there are _no_ docs in the index at all.
- // if (lastDocRequested <= 0) {
- // That causes the totalHits and export entries in the context to _not_ get set.
- // The only time that really matters is when we search against an _empty_ set. That's too obscure
- // a condition to handle as part of this patch, if someone wants to pursue it it can be reproduced with:
- // ant test -Dtestcase=StreamingTest -Dtests.method=testAllValidExportTypes -Dtests.seed=10F13879D0D1D6AD -Dtests.slow=true -Dtests.locale=es-PA -Dtests.timezone=America/Bahia_Banderas -Dtests.asserts=true -Dtests.file.encoding=ISO-8859-1
- // You'll have to uncomment the if below to hit the null pointer exception.
- // This is such an unusual case (i.e. an empty index) that catching this concdition here is probably OK.
- // This came to light in the very artifical case of indexing a single doc to Cloud.
- if (req.getContext().get("totalHits") != null) {
- totalHits = ((Integer)req.getContext().get("totalHits")).intValue();
- sets = (FixedBitSet[]) req.getContext().get("export");
- if (sets == null) {
- writeException((new IOException(new SyntaxError("xport RankQuery is required for xsort: rq={!xport}"))), writer, true);
- return;
- }
- }
- SolrParams params = req.getParams();
- String fl = params.get("fl");
-
- String[] fields = null;
-
- if(fl == null) {
- writeException((new IOException(new SyntaxError("export field list (fl) must be specified."))), writer, true);
- return;
- } else {
- fields = fl.split(",");
-
- for(int i=0;i<fields.length; i++) {
-
- fields[i] = fields[i].trim();
-
- if(fields[i].equals("score")) {
- writeException((new IOException(new SyntaxError("Scoring is not currently supported with xsort."))), writer, true);
- return;
- }
- }
- }
-
- try {
- fieldWriters = getFieldWriters(fields, req.getSearcher());
- } catch (Exception e) {
- writeException(e, writer, true);
- return;
- }
-
- writer.writeMap(m -> {
- m.put("responseHeader", singletonMap("status", 0));
- m.put("response", (MapWriter) mw -> {
- mw.put("numFound", totalHits);
- mw.put("docs", (IteratorWriter) iw -> writeDocs(req, iw, sort));
- });
- });
-
- }
-
- protected void writeDocs(SolrQueryRequest req, IteratorWriter.ItemWriter writer, Sort sort) throws IOException {
- //Write the data.
- List<LeafReaderContext> leaves = req.getSearcher().getTopReaderContext().leaves();
- SortDoc sortDoc = getSortDoc(req.getSearcher(), sort.getSort());
- int count = 0;
- int queueSize = 30000;
- SortQueue queue = new SortQueue(queueSize, sortDoc);
- SortDoc[] outDocs = new SortDoc[queueSize];
-
- while(count < totalHits) {
- //long begin = System.nanoTime();
- queue.reset();
- SortDoc top = queue.top();
- for(int i=0; i<leaves.size(); i++) {
- sortDoc.setNextReader(leaves.get(i));
- DocIdSetIterator it = new BitSetIterator(sets[i], 0); // cost is not useful here
- int docId = -1;
- while((docId = it.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
- sortDoc.setValues(docId);
- if(top.lessThan(sortDoc)) {
- top.setValues(sortDoc);
- top = queue.updateTop();
- }
- }
- }
-
- int outDocsIndex = -1;
-
- for(int i=0; i<queueSize; i++) {
- SortDoc s = queue.pop();
- if(s.docId > -1) {
- outDocs[++outDocsIndex] = s;
- }
- }
-
- //long end = System.nanoTime();
-
- count += (outDocsIndex+1);
-
- try {
- for(int i=outDocsIndex; i>=0; --i) {
- SortDoc s = outDocs[i];
- writer.add((MapWriter) ew -> {
- writeDoc(s, leaves, ew);
- s.reset();
- });
- }
- } catch(Throwable e) {
- Throwable ex = e;
- while(ex != null) {
- String m = ex.getMessage();
- if(m != null && m.contains("Broken pipe")) {
- throw new IgnoreException();
- }
- ex = ex.getCause();
- }
-
- if(e instanceof IOException) {
- throw ((IOException)e);
- } else {
- throw new IOException(e);
- }
- }
- }
- }
-
- protected void writeDoc(SortDoc sortDoc,
- List<LeafReaderContext> leaves,
- EntryWriter ew) throws IOException {
-
- int ord = sortDoc.ord;
- FixedBitSet set = sets[ord];
- set.clear(sortDoc.docId);
- LeafReaderContext context = leaves.get(ord);
- int fieldIndex = 0;
- for (FieldWriter fieldWriter : fieldWriters) {
- if (fieldWriter.write(sortDoc.docId, context.reader(), ew, fieldIndex)) {
- ++fieldIndex;
- }
- }
- }
-
- protected FieldWriter[] getFieldWriters(String[] fields, SolrIndexSearcher searcher) throws IOException {
- IndexSchema schema = searcher.getSchema();
- FieldWriter[] writers = new FieldWriter[fields.length];
- for(int i=0; i<fields.length; i++) {
- String field = fields[i];
- SchemaField schemaField = null;
-
- try {
- schemaField = schema.getField(field);
- } catch (Exception e) {
- throw new IOException(e);
- }
-
- if(!schemaField.hasDocValues()) {
- throw new IOException(field+" must have DocValues to use this feature.");
- }
-
- boolean multiValued = schemaField.multiValued();
- FieldType fieldType = schemaField.getType();
- if (fieldType instanceof IntValueFieldType) {
- if (multiValued) {
- writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
- } else {
- writers[i] = new IntFieldWriter(field);
- }
- } else if (fieldType instanceof LongValueFieldType) {
- if (multiValued) {
- writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
- } else {
- writers[i] = new LongFieldWriter(field);
- }
- } else if (fieldType instanceof FloatValueFieldType) {
- if (multiValued) {
- writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
- } else {
- writers[i] = new FloatFieldWriter(field);
- }
- } else if (fieldType instanceof DoubleValueFieldType) {
- if (multiValued) {
- writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
- } else {
- writers[i] = new DoubleFieldWriter(field);
- }
- } else if (fieldType instanceof StrField) {
- if (multiValued) {
- writers[i] = new MultiFieldWriter(field, fieldType, schemaField, false);
- } else {
- writers[i] = new StringFieldWriter(field, fieldType);
- }
- } else if (fieldType instanceof DateValueFieldType) {
- if (multiValued) {
- writers[i] = new MultiFieldWriter(field, fieldType, schemaField, false);
- } else {
- writers[i] = new DateFieldWriter(field);
- }
- } else if (fieldType instanceof BoolField) {
- if (multiValued) {
- writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
- } else {
- writers[i] = new BoolFieldWriter(field, fieldType);
- }
- } else {
- throw new IOException("Export fields must either be one of the following types: int,float,long,double,string,date,boolean");
- }
- }
- return writers;
- }
-
- private SortDoc getSortDoc(SolrIndexSearcher searcher, SortField[] sortFields) throws IOException {
- SortValue[] sortValues = new SortValue[sortFields.length];
- IndexSchema schema = searcher.getSchema();
- for(int i=0; i<sortFields.length; ++i) {
- SortField sf = sortFields[i];
- String field = sf.getField();
- boolean reverse = sf.getReverse();
- SchemaField schemaField = schema.getField(field);
- FieldType ft = schemaField.getType();
-
- if(!schemaField.hasDocValues()) {
- throw new IOException(field+" must have DocValues to use this feature.");
- }
-
- if(ft instanceof IntValueFieldType) {
- if(reverse) {
- sortValues[i] = new IntValue(field, new IntDesc());
- } else {
- sortValues[i] = new IntValue(field, new IntAsc());
- }
- } else if(ft instanceof FloatValueFieldType) {
- if(reverse) {
- sortValues[i] = new FloatValue(field, new FloatDesc());
- } else {
- sortValues[i] = new FloatValue(field, new FloatAsc());
- }
- } else if(ft instanceof DoubleValueFieldType) {
- if(reverse) {
- sortValues[i] = new DoubleValue(field, new DoubleDesc());
- } else {
- sortValues[i] = new DoubleValue(field, new DoubleAsc());
- }
- } else if(ft instanceof LongValueFieldType) {
- if(reverse) {
- sortValues[i] = new LongValue(field, new LongDesc());
- } else {
- sortValues[i] = new LongValue(field, new LongAsc());
- }
- } else if(ft instanceof StrField) {
- LeafReader reader = searcher.getSlowAtomicReader();
- SortedDocValues vals = reader.getSortedDocValues(field);
- if(reverse) {
- sortValues[i] = new StringValue(vals, field, new IntDesc());
- } else {
- sortValues[i] = new StringValue(vals, field, new IntAsc());
- }
- } else if (ft instanceof DateValueFieldType) {
- if (reverse) {
- sortValues[i] = new LongValue(field, new LongDesc());
- } else {
- sortValues[i] = new LongValue(field, new LongAsc());
- }
- } else if (ft instanceof BoolField) {
- // This is a bit of a hack, but since the boolean field stores ByteRefs, just like Strings
- // _and_ since "F" happens to sort before "T" (thus false sorts "less" than true)
- // we can just use the existing StringValue here.
- LeafReader reader = searcher.getSlowAtomicReader();
- SortedDocValues vals = reader.getSortedDocValues(field);
- if (reverse) {
- sortValues[i] = new StringValue(vals, field, new IntDesc());
- } else {
- sortValues[i] = new StringValue(vals, field, new IntAsc());
- }
- } else {
- throw new IOException("Sort fields must be one of the following types: int,float,long,double,string,date,boolean");
- }
- }
-
- if(sortValues.length == 1) {
- return new SingleValueSortDoc(sortValues[0]);
- } else if(sortValues.length == 2) {
- return new DoubleValueSortDoc(sortValues[0], sortValues[1]);
- } else if(sortValues.length == 3) {
- return new TripleValueSortDoc(sortValues[0], sortValues[1], sortValues[2]);
- } else if(sortValues.length == 4) {
- return new QuadValueSortDoc(sortValues[0], sortValues[1], sortValues[2], sortValues[3]);
- } else {
- throw new IOException("A max of 4 sorts can be specified");
- }
- }
-
- class SortQueue extends PriorityQueue<SortDoc> {
-
- private SortDoc proto;
- private Object[] cache;
-
- public SortQueue(int len, SortDoc proto) {
- super(len);
- this.proto = proto;
- }
-
- protected boolean lessThan(SortDoc t1, SortDoc t2) {
- return t1.lessThan(t2);
- }
-
- private void populate() {
- Object[] heap = getHeapArray();
- cache = new SortDoc[heap.length];
- for (int i = 1; i < heap.length; i++) {
- cache[i] = heap[i] = proto.copy();
- }
- size = maxSize;
- }
-
- private void reset() {
- Object[] heap = getHeapArray();
- if(cache != null) {
- System.arraycopy(cache, 1, heap, 1, heap.length-1);
- size = maxSize;
- } else {
- populate();
- }
- }
- }
-
- class SortDoc {
-
- protected int docId = -1;
- protected int ord = -1;
- protected int docBase = -1;
-
- private SortValue[] sortValues;
-
- public SortDoc() {
-
- }
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.ord = context.ord;
- for (SortValue value : sortValues) {
- value.setNextReader(context);
- }
- }
-
- public void reset() {
- this.docId = -1;
- }
-
- public void setValues(int docId) throws IOException {
- this.docId = docId;
- for(SortValue sortValue : sortValues) {
- sortValue.setCurrentValue(docId);
- }
- }
-
- public void setValues(SortDoc sortDoc) throws IOException {
- this.docId = sortDoc.docId;
- this.ord = sortDoc.ord;
- SortValue[] vals = sortDoc.sortValues;
- for(int i=0; i<vals.length; i++) {
- sortValues[i].setCurrentValue(vals[i]);
- }
- }
-
- public SortDoc(SortValue[] sortValues) {
- this.sortValues = sortValues;
- }
-
- public SortDoc copy() {
- SortValue[] svs = new SortValue[sortValues.length];
- for(int i=0; i<sortValues.length; i++) {
- svs[i] = sortValues[i].copy();
- }
-
- return new SortDoc(svs);
- }
-
- public boolean lessThan(Object o) {
- if(docId == -1) {
- return true;
- }
-
- SortDoc sd = (SortDoc)o;
- SortValue[] sortValues1 = sd.sortValues;
- for(int i=0; i<sortValues.length; i++) {
- int comp = sortValues[i].compareTo(sortValues1[i]);
- if(comp < 0) {
- return true;
- } if(comp > 0) {
- return false;
- }
- }
- return docId+docBase < sd.docId+sd.docBase;
- }
-
- public String toString() {
- return "";
- }
- }
-
- class SingleValueSortDoc extends SortDoc {
-
- protected SortValue value1;
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.ord = context.ord;
- value1.setNextReader(context);
- }
-
- public void reset() {
- this.docId = -1;
- this.value1.reset();
- }
-
- public void setValues(int docId) throws IOException {
- this.docId = docId;
- value1.setCurrentValue(docId);
- }
-
- public void setValues(SortDoc sortDoc) throws IOException {
- this.docId = sortDoc.docId;
- this.ord = sortDoc.ord;
- value1.setCurrentValue(((SingleValueSortDoc)sortDoc).value1);
- }
-
- public SingleValueSortDoc(SortValue value1) {
- super();
- this.value1 = value1;
- }
-
- public SortDoc copy() {
- return new SingleValueSortDoc(value1.copy());
- }
-
- public boolean lessThan(Object o) {
- SingleValueSortDoc sd = (SingleValueSortDoc)o;
- int comp = value1.compareTo(sd.value1);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- return docId+docBase > sd.docId+sd.docBase;
- }
- }
-
- public int compareTo(Object o) {
- SingleValueSortDoc sd = (SingleValueSortDoc)o;
- return value1.compareTo(sd.value1);
- }
-
- public String toString() {
- return docId+":"+value1.toString();
- }
- }
-
- class DoubleValueSortDoc extends SingleValueSortDoc {
-
- protected SortValue value2;
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.ord = context.ord;
- value1.setNextReader(context);
- value2.setNextReader(context);
- }
-
- public void reset() {
- this.docId = -1;
- value1.reset();
- value2.reset();
- }
-
- public void setValues(int docId) throws IOException {
- this.docId = docId;
- value1.setCurrentValue(docId);
- value2.setCurrentValue(docId);
- }
-
- public void setValues(SortDoc sortDoc) throws IOException {
- this.docId = sortDoc.docId;
- this.ord = sortDoc.ord;
- value1.setCurrentValue(((DoubleValueSortDoc)sortDoc).value1);
- value2.setCurrentValue(((DoubleValueSortDoc)sortDoc).value2);
- }
-
- public DoubleValueSortDoc(SortValue value1, SortValue value2) {
- super(value1);
- this.value2 = value2;
- }
-
- public SortDoc copy() {
- return new DoubleValueSortDoc(value1.copy(), value2.copy());
- }
-
- public boolean lessThan(Object o) {
- DoubleValueSortDoc sd = (DoubleValueSortDoc)o;
- int comp = value1.compareTo(sd.value1);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- comp = value2.compareTo(sd.value2);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- return docId+docBase > sd.docId+sd.docBase;
- }
- }
- }
-
- public int compareTo(Object o) {
- DoubleValueSortDoc sd = (DoubleValueSortDoc)o;
- int comp = value1.compareTo(sd.value1);
- if(comp == 0) {
- return value2.compareTo(sd.value2);
- } else {
- return comp;
- }
- }
- }
-
- class TripleValueSortDoc extends DoubleValueSortDoc {
-
- protected SortValue value3;
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.ord = context.ord;
- value1.setNextReader(context);
- value2.setNextReader(context);
- value3.setNextReader(context);
- }
-
- public void reset() {
- this.docId = -1;
- value1.reset();
- value2.reset();
- value3.reset();
- }
-
- public void setValues(int docId) throws IOException {
- this.docId = docId;
- value1.setCurrentValue(docId);
- value2.setCurrentValue(docId);
- value3.setCurrentValue(docId);
- }
-
- public void setValues(SortDoc sortDoc) throws IOException {
- this.docId = sortDoc.docId;
- this.ord = sortDoc.ord;
- value1.setCurrentValue(((TripleValueSortDoc)sortDoc).value1);
- value2.setCurrentValue(((TripleValueSortDoc)sortDoc).value2);
- value3.setCurrentValue(((TripleValueSortDoc)sortDoc).value3);
- }
-
- public TripleValueSortDoc(SortValue value1, SortValue value2, SortValue value3) {
- super(value1, value2);
- this.value3 = value3;
- }
-
- public SortDoc copy() {
- return new TripleValueSortDoc(value1.copy(), value2.copy(), value3.copy());
- }
-
- public boolean lessThan(Object o) {
-
- TripleValueSortDoc sd = (TripleValueSortDoc)o;
- int comp = value1.compareTo(sd.value1);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- comp = value2.compareTo(sd.value2);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- comp = value3.compareTo(sd.value3);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- return docId+docBase > sd.docId+sd.docBase;
- }
- }
- }
- }
-
- public int compareTo(Object o) {
-
- TripleValueSortDoc sd = (TripleValueSortDoc)o;
- int comp = value1.compareTo(sd.value1);
- if(comp == 0) {
- comp = value2.compareTo(sd.value2);
- if(comp == 0) {
- return value3.compareTo(sd.value3);
- } else {
- return comp;
- }
- } else {
- return comp;
- }
- }
- }
-
- class QuadValueSortDoc extends TripleValueSortDoc {
-
- protected SortValue value4;
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.ord = context.ord;
- value1.setNextReader(context);
- value2.setNextReader(context);
- value3.setNextReader(context);
- value4.setNextReader(context);
- }
-
- public void reset() {
- this.docId = -1;
- value1.reset();
- value2.reset();
- value3.reset();
- value4.reset();
- }
-
- public void setValues(int docId) throws IOException {
- this.docId = docId;
- value1.setCurrentValue(docId);
- value2.setCurrentValue(docId);
- value3.setCurrentValue(docId);
- value4.setCurrentValue(docId);
- }
-
- public void setValues(SortDoc sortDoc) throws IOException {
- this.docId = sortDoc.docId;
- this.ord = sortDoc.ord;
- value1.setCurrentValue(((QuadValueSortDoc)sortDoc).value1);
- value2.setCurrentValue(((QuadValueSortDoc)sortDoc).value2);
- value3.setCurrentValue(((QuadValueSortDoc)sortDoc).value3);
- value4.setCurrentValue(((QuadValueSortDoc)sortDoc).value4);
- }
-
- public QuadValueSortDoc(SortValue value1, SortValue value2, SortValue value3, SortValue value4) {
- super(value1, value2, value3);
- this.value4 = value4;
- }
-
- public SortDoc copy() {
- return new QuadValueSortDoc(value1.copy(), value2.copy(), value3.copy(), value4.copy());
- }
-
- public boolean lessThan(Object o) {
-
- QuadValueSortDoc sd = (QuadValueSortDoc)o;
- int comp = value1.compareTo(sd.value1);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- comp = value2.compareTo(sd.value2);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- comp = value3.compareTo(sd.value3);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- comp = value4.compareTo(sd.value4);
- if(comp == -1) {
- return true;
- } else if (comp == 1) {
- return false;
- } else {
- return docId+docBase > sd.docId+sd.docBase;
- }
- }
- }
- }
- }
-
- public int compareTo(Object o) {
- QuadValueSortDoc sd = (QuadValueSortDoc)o;
- int comp = value1.compareTo(sd.value1);
- if(comp == 0) {
- comp = value2.compareTo(sd.value2);
- if(comp == 0) {
- comp = value3.compareTo(sd.value3);
- if(comp == 0) {
- return value4.compareTo(sd.value4);
- } else {
- return comp;
- }
- } else {
- return comp;
- }
- } else {
- return comp;
- }
- }
- }
-
- public interface SortValue extends Comparable<SortValue> {
- public void setCurrentValue(int docId) throws IOException;
- public void setNextReader(LeafReaderContext context) throws IOException;
- public void setCurrentValue(SortValue value);
- public void reset();
- public SortValue copy();
- }
-
- class IntValue implements SortValue {
-
- protected NumericDocValues vals;
- protected String field;
- protected int currentValue;
- protected IntComp comp;
- private int lastDocID;
-
- public IntValue copy() {
- return new IntValue(field, comp);
- }
-
- public IntValue(String field, IntComp comp) {
- this.field = field;
- this.comp = comp;
- this.currentValue = comp.resetValue();
- }
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.vals = DocValues.getNumeric(context.reader(), field);
- lastDocID = 0;
- }
-
- public void setCurrentValue(int docId) throws IOException {
- if (docId < lastDocID) {
- throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
- }
- lastDocID = docId;
- int curDocID = vals.docID();
- if (docId > curDocID) {
- curDocID = vals.advance(docId);
- }
- if (docId == curDocID) {
- currentValue = (int) vals.longValue();
- } else {
- currentValue = 0;
- }
- }
-
- public int compareTo(SortValue o) {
- IntValue iv = (IntValue)o;
- return comp.compare(currentValue, iv.currentValue);
- }
-
- public void setCurrentValue (SortValue value) {
- currentValue = ((IntValue)value).currentValue;
- }
-
- public void reset() {
- currentValue = comp.resetValue();
- }
- }
-
- public interface IntComp {
- public int compare(int a, int b);
- public int resetValue();
- }
-
- static class IntDesc implements IntComp {
-
- public int resetValue() {
- return Integer.MIN_VALUE;
- }
-
- public int compare(int a, int b) {
- if(a < b) {
- return -1;
- } else if (a > b) {
- return 1;
- } else {
- return 0;
- }
- }
- }
-
- static class IntAsc implements IntComp {
-
- public int resetValue() {
- return Integer.MAX_VALUE;
- }
-
- public int compare(int a, int b) {
- if(a < b) {
- return 1;
- } else if (a > b) {
- return -1;
- } else {
- return 0;
- }
- }
- }
-
- class LongValue implements SortValue {
-
- protected NumericDocValues vals;
- protected String field;
- protected long currentValue;
- protected LongComp comp;
- private int lastDocID;
-
- public LongValue(String field, LongComp comp) {
- this.field = field;
- this.comp = comp;
- this.currentValue = comp.resetValue();
- }
-
- public LongValue copy() {
- return new LongValue(field, comp);
- }
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.vals = DocValues.getNumeric(context.reader(), field);
- lastDocID = 0;
- }
-
- public void setCurrentValue(int docId) throws IOException {
- if (docId < lastDocID) {
- throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
- }
- lastDocID = docId;
- int curDocID = vals.docID();
- if (docId > curDocID) {
- curDocID = vals.advance(docId);
- }
- if (docId == curDocID) {
- currentValue = vals.longValue();
- } else {
- currentValue = 0;
- }
- }
-
- public void setCurrentValue(SortValue sv) {
- LongValue lv = (LongValue)sv;
- this.currentValue = lv.currentValue;
- }
-
- public int compareTo(SortValue o) {
- LongValue l = (LongValue)o;
- return comp.compare(currentValue, l.currentValue);
- }
-
- public void reset() {
- this.currentValue = comp.resetValue();
- }
- }
-
- interface LongComp {
- public int compare(long a, long b);
- public long resetValue();
- }
-
- static class LongDesc implements LongComp {
-
- public long resetValue() {
- return Long.MIN_VALUE;
- }
-
- public int compare(long a, long b) {
- if(a < b) {
- return -1;
- } else if (a > b) {
- return 1;
- } else {
- return 0;
- }
- }
- }
-
- static class LongAsc implements LongComp {
-
- public long resetValue() {
- return Long.MAX_VALUE;
- }
-
- public int compare(long a, long b) {
- if(a < b) {
- return 1;
- } else if (a > b) {
- return -1;
- } else {
- return 0;
- }
- }
- }
-
- class FloatValue implements SortValue {
-
- protected NumericDocValues vals;
- protected String field;
- protected float currentValue;
- protected FloatComp comp;
- private int lastDocID;
-
- public FloatValue(String field, FloatComp comp) {
- this.field = field;
- this.comp = comp;
- this.currentValue = comp.resetValue();
- }
-
- public FloatValue copy() {
- return new FloatValue(field, comp);
- }
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.vals = DocValues.getNumeric(context.reader(), field);
- lastDocID = 0;
- }
-
- public void setCurrentValue(int docId) throws IOException {
- if (docId < lastDocID) {
- throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
- }
- lastDocID = docId;
- int curDocID = vals.docID();
- if (docId > curDocID) {
- curDocID = vals.advance(docId);
- }
- if (docId == curDocID) {
- currentValue = Float.intBitsToFloat((int)vals.longValue());
- } else {
- currentValue = 0f;
- }
- }
-
- public void setCurrentValue(SortValue sv) {
- FloatValue fv = (FloatValue)sv;
- this.currentValue = fv.currentValue;
- }
-
- public void reset() {
- this.currentValue = comp.resetValue();
- }
-
- public int compareTo(SortValue o) {
- FloatValue fv = (FloatValue)o;
- return comp.compare(currentValue, fv.currentValue);
- }
- }
-
- interface FloatComp {
- public int compare(float a, float b);
- public float resetValue();
- }
-
- public static class FloatDesc implements FloatComp {
- public float resetValue() {
- return -Float.MAX_VALUE;
- }
-
- public int compare(float a, float b) {
- if(a < b) {
- return -1;
- } else if (a > b) {
- return 1;
- } else {
- return 0;
- }
- }
- }
-
- public static class FloatAsc implements FloatComp {
- public float resetValue() {
- return Float.MAX_VALUE;
- }
-
- public int compare(float a, float b) {
- if(a < b) {
- return 1;
- } else if (a > b) {
- return -1;
- } else {
- return 0;
- }
- }
- }
-
- class DoubleValue implements SortValue {
-
- protected NumericDocValues vals;
- protected String field;
- protected double currentValue;
- protected DoubleComp comp;
- private int lastDocID;
- private LeafReader reader;
-
- public DoubleValue(String field, DoubleComp comp) {
- this.field = field;
- this.comp = comp;
- this.currentValue = comp.resetValue();
- }
-
- public DoubleValue copy() {
- return new DoubleValue(field, comp);
- }
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.reader = context.reader();
- this.vals = DocValues.getNumeric(this.reader, this.field);
- lastDocID = 0;
- }
-
- public void setCurrentValue(int docId) throws IOException {
- if (docId < lastDocID) {
- // TODO: can we enforce caller to go in order instead?
- this.vals = DocValues.getNumeric(this.reader, this.field);
- }
- lastDocID = docId;
- int curDocID = vals.docID();
- if (docId > curDocID) {
- curDocID = vals.advance(docId);
- }
- if (docId == curDocID) {
- currentValue = Double.longBitsToDouble(vals.longValue());
- } else {
- currentValue = 0f;
- }
- }
-
- public void setCurrentValue(SortValue sv) {
- DoubleValue dv = (DoubleValue)sv;
- this.currentValue = dv.currentValue;
- }
-
- public void reset() {
- this.currentValue = comp.resetValue();
- }
-
- public int compareTo(SortValue o) {
- DoubleValue dv = (DoubleValue)o;
- return comp.compare(currentValue, dv.currentValue);
- }
- }
-
- interface DoubleComp {
- public int compare(double a, double b);
- public double resetValue();
- }
-
- public static class DoubleDesc implements DoubleComp {
- public double resetValue() {
- return -Double.MAX_VALUE;
- }
-
- public int compare(double a, double b) {
- if(a < b) {
- return -1;
- } else if (a > b) {
- return 1;
- } else {
- return 0;
- }
- }
- }
-
- public static class DoubleAsc implements DoubleComp {
- public double resetValue() {
- return Double.MAX_VALUE;
- }
-
- public int compare(double a, double b) {
- if(a < b) {
- return 1;
- } else if (a > b) {
- return -1;
- } else {
- return 0;
- }
- }
- }
-
- class StringValue implements SortValue {
-
- protected SortedDocValues vals;
-
- protected OrdinalMap ordinalMap;
- protected LongValues globalOrds;
- protected SortedDocValues currentVals;
-
- protected String field;
- protected int segment;
- protected int currentOrd;
- protected IntComp comp;
- protected int lastDocID;
-
- public StringValue(SortedDocValues vals, String field, IntComp comp) {
- this.vals = vals;
- if(vals instanceof MultiDocValues.MultiSortedDocValues) {
- this.ordinalMap = ((MultiDocValues.MultiSortedDocValues) vals).mapping;
- }
- this.field = field;
- this.comp = comp;
- this.currentOrd = comp.resetValue();
- }
-
- public StringValue copy() {
- return new StringValue(vals, field, comp);
- }
-
- public void setCurrentValue(int docId) throws IOException {
-
- if (docId < lastDocID) {
- throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
- }
-
- lastDocID = docId;
-
- if (docId > currentVals.docID()) {
- currentVals.advance(docId);
- }
- if (docId == currentVals.docID()) {
- int ord = currentVals.ordValue();
- if(globalOrds != null) {
- currentOrd = (int)globalOrds.get(ord);
- } else {
- currentOrd = ord;
- }
- } else {
- currentOrd = -1;
- }
- }
-
- public void setCurrentValue(SortValue sv) {
- StringValue v = (StringValue)sv;
- this.currentOrd = v.currentOrd;
- }
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- segment = context.ord;
- if(ordinalMap != null) {
- globalOrds = ordinalMap.getGlobalOrds(segment);
- }
- currentVals = DocValues.getSorted(context.reader(), field);
- lastDocID = 0;
- }
-
- public void reset() {
- this.currentOrd = comp.resetValue();
- }
-
- public int compareTo(SortValue o) {
- StringValue sv = (StringValue)o;
- return comp.compare(currentOrd, sv.currentOrd);
- }
-
- public String toString() {
- return Integer.toString(this.currentOrd);
- }
- }
-
- protected abstract class FieldWriter {
- public abstract boolean write(int docId, LeafReader reader, EntryWriter out, int fieldIndex) throws IOException;
- }
-
- class IntFieldWriter extends FieldWriter {
- private String field;
-
- public IntFieldWriter(String field) {
- this.field = field;
- }
-
- public boolean write(int docId, LeafReader reader, EntryWriter ew, int fieldIndex) throws IOException {
- NumericDocValues vals = DocValues.getNumeric(reader, this.field);
- int val;
- if (vals.advance(docId) == docId) {
- val = (int) vals.longValue();
- } else {
- return false;
- }
- ew.put(this.field, val);
- return true;
- }
- }
-
- static LongFunction<Object> bitsToValue(FieldType fieldType) {
- switch (fieldType.getNumberType()) {
- case LONG:
- return (bits)-> bits;
- case DATE:
- return (bits)-> new Date(bits);
- case INTEGER:
- return (bits)-> (int)bits;
- case FLOAT:
- return (bits)-> NumericUtils.sortableIntToFloat((int)bits);
- case DOUBLE:
- return (bits)-> NumericUtils.sortableLongToDouble(bits);
- default:
- throw new AssertionError("Unsupported NumberType: " + fieldType.getNumberType());
- }
- }
-
- class MultiFieldWriter extends FieldWriter {
- private String field;
- private FieldType fieldType;
- private SchemaField schemaField;
- private boolean numeric;
- private CharsRefBuilder cref = new CharsRefBuilder();
- private final LongFunction<Object> bitsToValue;
-
- public MultiFieldWriter(String field, FieldType fieldType, SchemaField schemaField, boolean numeric) {
- this.field = field;
- this.fieldType = fieldType;
- this.schemaField = schemaField;
- this.numeric = numeric;
- if (this.fieldType.isPointField()) {
- bitsToValue = bitsToValue(fieldType);
- } else {
- bitsToValue = null;
- }
- }
-
- public boolean write(int docId, LeafReader reader, EntryWriter out, int fieldIndex) throws IOException {
- if (this.fieldType.isPointField()) {
- SortedNumericDocValues vals = DocValues.getSortedNumeric(reader, this.field);
- if (!vals.advanceExact(docId)) return false;
- out.put(this.field,
- (IteratorWriter) w -> {
- for (int i = 0; i < vals.docValueCount(); i++) {
- w.add(bitsToValue.apply(vals.nextValue()));
- }
- });
- return true;
- } else {
- SortedSetDocValues vals = DocValues.getSortedSet(reader, this.field);
- if (vals.advance(docId) != docId) return false;
- out.put(this.field,
- (IteratorWriter) w -> {
- long o;
- while((o = vals.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) {
- BytesRef ref = vals.lookupOrd(o);
- fieldType.indexedToReadable(ref, cref);
- IndexableField f = fieldType.createField(schemaField, cref.toString());
- if (f == null) w.add(cref.toString());
- else w.add(fieldType.toObject(f));
- }
- });
- return true;
- }
-
- }
- }
-
- class LongFieldWriter extends FieldWriter {
- private String field;
-
- public LongFieldWriter(String field) {
- this.field = field;
- }
-
- public boolean write(int docId, LeafReader reader, EntryWriter ew, int fieldIndex) throws IOException {
- NumericDocValues vals = DocValues.getNumeric(reader, this.field);
- long val;
- if (vals.advance(docId) == docId) {
- val = vals.longValue();
- } else {
- return false;
- }
- ew.put(field, val);
- return true;
- }
- }
-
- class DateFieldWriter extends FieldWriter {
- private String field;
-
- public DateFieldWriter(String field) {
- this.field = field;
- }
-
- public boolean write(int docId, LeafReader reader, EntryWriter ew, int fieldIndex) throws IOException {
- NumericDocValues vals = DocValues.getNumeric(reader, this.field);
- long val;
- if (vals.advance(docId) == docId) {
- val = vals.longValue();
- } else {
- return false;
- }
- ew.put(this.field, new Date(val));
- return true;
- }
- }
-
- class BoolFieldWriter extends FieldWriter {
- private String field;
- private FieldType fieldType;
- private CharsRefBuilder cref = new CharsRefBuilder();
-
- public BoolFieldWriter(String field, FieldType fieldType) {
- this.field = field;
- this.fieldType = fieldType;
- }
-
- public boolean write(int docId, LeafReader reader, EntryWriter ew, int fieldIndex) throws IOException {
- SortedDocValues vals = DocValues.getSorted(reader, this.field);
- if (vals.advance(docId) != docId) {
- return false;
- }
- int ord = vals.ordValue();
-
- BytesRef ref = vals.lookupOrd(ord);
- fieldType.indexedToReadable(ref, cref);
- ew.put(this.field, "true".equals(cref.toString()));
- return true;
- }
- }
-
- class FloatFieldWriter extends FieldWriter {
- private String field;
-
- public FloatFieldWriter(String field) {
- this.field = field;
- }
-
- public boolean write(int docId, LeafReader reader, EntryWriter ew, int fieldIndex) throws IOException {
- NumericDocValues vals = DocValues.getNumeric(reader, this.field);
- int val;
- if (vals.advance(docId) == docId) {
- val = (int)vals.longValue();
- } else {
- return false;
- }
- ew.put(this.field, Float.intBitsToFloat(val));
- return true;
- }
- }
-
- class DoubleFieldWriter extends FieldWriter {
- private String field;
-
- public DoubleFieldWriter(String field) {
- this.field = field;
- }
-
- public boolean write(int docId, LeafReader reader, EntryWriter ew, int fieldIndex) throws IOException {
- NumericDocValues vals = DocValues.getNumeric(reader, this.field);
- long val;
- if (vals.advance(docId) == docId) {
- val = vals.longValue();
- } else {
- return false;
- }
- ew.put(this.field, Double.longBitsToDouble(val));
- return true;
- }
- }
-
- class StringFieldWriter extends FieldWriter {
- private String field;
- private FieldType fieldType;
- private CharsRefBuilder cref = new CharsRefBuilder();
-
- public StringFieldWriter(String field, FieldType fieldType) {
- this.field = field;
- this.fieldType = fieldType;
- }
-
- public boolean write(int docId, LeafReader reader, EntryWriter ew, int fieldIndex) throws IOException {
- SortedDocValues vals = DocValues.getSorted(reader, this.field);
- if (vals.advance(docId) != docId) {
- return false;
- }
- int ord = vals.ordValue();
-
- BytesRef ref = vals.lookupOrd(ord);
- fieldType.indexedToReadable(ref, cref);
- ew.put(this.field, cref.toString());
- return true;
- }
- }
-
- public abstract class PriorityQueue<T> {
- protected int size = 0;
- protected final int maxSize;
- private final T[] heap;
-
- public PriorityQueue(int maxSize) {
- this(maxSize, true);
- }
-
- public PriorityQueue(int maxSize, boolean prepopulate) {
- final int heapSize;
- if (0 == maxSize) {
- // We allocate 1 extra to avoid if statement in top()
- heapSize = 2;
- } else {
- if (maxSize > ArrayUtil.MAX_ARRAY_LENGTH) {
- // Don't wrap heapSize to -1, in this case, which
- // causes a confusing NegativeArraySizeException.
- // Note that very likely this will simply then hit
- // an OOME, but at least that's more indicative to
- // caller that this values is too big. We don't +1
- // in this case, but it's very unlikely in practice
- // one will actually insert this many objects into
- // the PQ:
- // Throw exception to prevent confusing OOME:
- throw new IllegalArgumentException("maxSize must be <= " + ArrayUtil.MAX_ARRAY_LENGTH + "; got: " + maxSize);
- } else {
- // NOTE: we add +1 because all access to heap is
- // 1-based not 0-based. heap[0] is unused.
- heapSize = maxSize + 1;
- }
- }
- // T is unbounded type, so this unchecked cast works always:
- @SuppressWarnings("unchecked") final T[] h = (T[]) new Object[heapSize];
- this.heap = h;
- this.maxSize = maxSize;
-
- if (prepopulate) {
- // If sentinel objects are supported, populate the queue with them
- T sentinel = getSentinelObject();
- if (sentinel != null) {
- heap[1] = sentinel;
- for (int i = 2; i < heap.length; i++) {
- heap[i] = getSentinelObject();
- }
- size = maxSize;
- }
- }
- }
-
- /** Determines the ordering of objects in this priority queue. Subclasses
- * must define this one method.
- * @return <code>true</code> iff parameter <tt>a</tt> is less than parameter <tt>b</tt>.
- */
- protected abstract boolean lessThan(T a, T b);
-
-
- protected T getSentinelObject() {
- return null;
- }
-
- /**
- * Adds an Object to a PriorityQueue in log(size) time. If one tries to add
- * more objects than maxSize from initialize an
- *
- * @return the new 'top' element in the queue.
- */
- public final T add(T element) {
- size++;
- heap[size] = element;
- upHeap();
- return heap[1];
- }
-
- /**
- * Adds an Object to a PriorityQueue in log(size) time.
- * It returns the object (if any) that was
- * dropped off the heap because it was full. This can be
- * the given parameter (in case it is smaller than the
- * full heap's minimum, and couldn't be added), or another
- * object that was previously the smallest value in the
- * heap and now has been replaced by a larger one, or null
- * if the queue wasn't yet full with maxSize elements.
- */
- public T insertWithOverflow(T element) {
- if (size < maxSize) {
- add(element);
- return null;
- } else if (size > 0 && !lessThan(element, heap[1])) {
- T ret = heap[1];
- heap[1] = element;
- updateTop();
- return ret;
- } else {
- return element;
- }
- }
-
- /** Returns the least element of the PriorityQueue in constant time. */
- public final T top() {
- // We don't need to check size here: if maxSize is 0,
- // then heap is length 2 array with both entries null.
- // If size is 0 then heap[1] is already null.
- return heap[1];
- }
-
- /** Removes and returns the least element of the PriorityQueue in log(size)
- time. */
- public final T pop() {
- if (size > 0) {
- T result = heap[1]; // save first value
- heap[1] = heap[size]; // move last to first
- heap[size] = null; // permit GC of objects
- size--;
- downHeap(); // adjust heap
- return result;
- } else {
- return null;
- }
- }
-
- /**
- * Should be called when the Object at top changes values. Still log(n) worst
- * case, but it's at least twice as fast to
- *
- * <pre class="prettyprint">
- * pq.top().change();
- * pq.updateTop();
- * </pre>
- *
- * instead of
- *
- * <pre class="prettyprint">
- * o = pq.pop();
- * o.change();
- * pq.push(o);
- * </pre>
- *
- * @return the new 'top' element.
- */
- public final T updateTop() {
- downHeap();
- return heap[1];
- }
-
- /** Returns the number of elements currently stored in the PriorityQueue. */
- public final int size() {
- return size;
- }
-
- /** Removes all entries from the PriorityQueue. */
- public final void clear() {
- for (int i = 0; i <= size; i++) {
- heap[i] = null;
- }
- size = 0;
- }
-
- private final void upHeap() {
- int i = size;
- T node = heap[i]; // save bottom node
- int j = i >>> 1;
- while (j > 0 && lessThan(node, heap[j])) {
- heap[i] = heap[j]; // shift parents down
- i = j;
- j = j >>> 1;
- }
- heap[i] = node; // install saved node
- }
-
- private final void downHeap() {
- int i = 1;
- T node = heap[i]; // save top node
- int j = i << 1; // find smaller child
- int k = j + 1;
- if (k <= size && lessThan(heap[k], heap[j])) {
- j = k;
- }
- while (j <= size && lessThan(heap[j], node)) {
- heap[i] = heap[j]; // shift up child
- i = j;
- j = i << 1;
- k = j + 1;
- if (k <= size && lessThan(heap[k], heap[j])) {
- j = k;
- }
- }
- heap[i] = node; // install saved node
- }
-
- /** This method returns the internal heap array as Object[].
- * @lucene.internal
- */
- public final Object[] getHeapArray() {
- return (Object[]) heap;
- }
- }
-
- public static class IgnoreException extends IOException {
- public void printStackTrace(PrintWriter pw) {
- pw.print("Early Client Disconnect");
- }
-
- public String getMessage() {
- return "Early Client Disconnect";
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/BoolFieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/BoolFieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/BoolFieldWriter.java
new file mode 100644
index 0000000..e67f5ed
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/BoolFieldWriter.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.CharsRefBuilder;
+import org.apache.solr.common.MapWriter;
+import org.apache.solr.schema.FieldType;
+
+class BoolFieldWriter extends FieldWriter {
+ private String field;
+ private FieldType fieldType;
+ private CharsRefBuilder cref = new CharsRefBuilder();
+
+ public BoolFieldWriter(String field, FieldType fieldType) {
+ this.field = field;
+ this.fieldType = fieldType;
+ }
+
+ public boolean write(int docId, LeafReader reader, MapWriter.EntryWriter ew, int fieldIndex) throws IOException {
+ SortedDocValues vals = DocValues.getSorted(reader, this.field);
+ if (vals.advance(docId) != docId) {
+ return false;
+ }
+ int ord = vals.ordValue();
+
+ BytesRef ref = vals.lookupOrd(ord);
+ fieldType.indexedToReadable(ref, cref);
+ ew.put(this.field, "true".equals(cref.toString()));
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/DateFieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/DateFieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/DateFieldWriter.java
new file mode 100644
index 0000000..3584317
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/DateFieldWriter.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+import java.util.Date;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.NumericDocValues;
+import org.apache.solr.common.MapWriter;
+
+class DateFieldWriter extends FieldWriter {
+ private String field;
+
+ public DateFieldWriter(String field) {
+ this.field = field;
+ }
+
+ public boolean write(int docId, LeafReader reader, MapWriter.EntryWriter ew, int fieldIndex) throws IOException {
+ NumericDocValues vals = DocValues.getNumeric(reader, this.field);
+ long val;
+ if (vals.advance(docId) == docId) {
+ val = vals.longValue();
+ } else {
+ return false;
+ }
+ ew.put(this.field, new Date(val));
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/DoubeValue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/DoubeValue.java b/solr/core/src/java/org/apache/solr/handler/export/DoubeValue.java
new file mode 100644
index 0000000..a37e13d
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/DoubeValue.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.NumericDocValues;
+
+class DoubleValue implements SortValue {
+
+ protected NumericDocValues vals;
+ protected String field;
+ protected double currentValue;
+ protected DoubleComp comp;
+ private int lastDocID;
+ private LeafReader reader;
+
+ public DoubleValue(String field, DoubleComp comp) {
+ this.field = field;
+ this.comp = comp;
+ this.currentValue = comp.resetValue();
+ }
+
+ public DoubleValue copy() {
+ return new DoubleValue(field, comp);
+ }
+
+ public void setNextReader(LeafReaderContext context) throws IOException {
+ this.reader = context.reader();
+ this.vals = DocValues.getNumeric(this.reader, this.field);
+ lastDocID = 0;
+ }
+
+ public void setCurrentValue(int docId) throws IOException {
+ if (docId < lastDocID) {
+ throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
+ }
+ lastDocID = docId;
+ int curDocID = vals.docID();
+ if (docId > curDocID) {
+ curDocID = vals.advance(docId);
+ }
+ if (docId == curDocID) {
+ currentValue = Double.longBitsToDouble(vals.longValue());
+ } else {
+ currentValue = 0f;
+ }
+ }
+
+ public void setCurrentValue(SortValue sv) {
+ DoubleValue dv = (DoubleValue)sv;
+ this.currentValue = dv.currentValue;
+ }
+
+ public void reset() {
+ this.currentValue = comp.resetValue();
+ }
+
+ public int compareTo(SortValue o) {
+ DoubleValue dv = (DoubleValue)o;
+ return comp.compare(currentValue, dv.currentValue);
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/DoubleCmp.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/DoubleCmp.java b/solr/core/src/java/org/apache/solr/handler/export/DoubleCmp.java
new file mode 100644
index 0000000..50341fd
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/DoubleCmp.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+interface DoubleComp {
+ int compare(double a, double b);
+ double resetValue();
+}
+
+class DoubleAsc implements DoubleComp {
+ public double resetValue() {
+ return Double.MAX_VALUE;
+ }
+
+ public int compare(double a, double b) {
+ return Double.compare(b, a);
+ }
+}
+
+class DoubleDesc implements DoubleComp {
+ public double resetValue() {
+ return -Double.MAX_VALUE;
+ }
+
+ public int compare(double a, double b) {
+ return Double.compare(a, b);
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/DoubleFieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/DoubleFieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/DoubleFieldWriter.java
new file mode 100644
index 0000000..1b953c5
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/DoubleFieldWriter.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.NumericDocValues;
+import org.apache.solr.common.MapWriter;
+
+class DoubleFieldWriter extends FieldWriter {
+ private String field;
+
+ public DoubleFieldWriter(String field) {
+ this.field = field;
+ }
+
+ public boolean write(int docId, LeafReader reader, MapWriter.EntryWriter ew, int fieldIndex) throws IOException {
+ NumericDocValues vals = DocValues.getNumeric(reader, this.field);
+ long val;
+ if (vals.advance(docId) == docId) {
+ val = vals.longValue();
+ } else {
+ return false;
+ }
+ ew.put(this.field, Double.longBitsToDouble(val));
+ return true;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/ExportWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/ExportWriter.java b/solr/core/src/java/org/apache/solr/handler/export/ExportWriter.java
new file mode 100644
index 0000000..78d0795
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/ExportWriter.java
@@ -0,0 +1,448 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.Sort;
+import org.apache.lucene.search.SortField;
+import org.apache.lucene.util.BitSetIterator;
+import org.apache.lucene.util.FixedBitSet;
+import org.apache.solr.client.solrj.impl.BinaryResponseParser;
+import org.apache.solr.common.IteratorWriter;
+import org.apache.solr.common.MapWriter;
+import org.apache.solr.common.MapWriter.EntryWriter;
+import org.apache.solr.common.PushWriter;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.SolrParams;
+import org.apache.solr.common.util.JavaBinCodec;
+import org.apache.solr.core.SolrCore;
+import org.apache.solr.request.SolrQueryRequest;
+import org.apache.solr.request.SolrRequestInfo;
+import org.apache.solr.response.BinaryResponseWriter;
+import org.apache.solr.response.JSONResponseWriter;
+import org.apache.solr.response.QueryResponseWriter;
+import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.schema.BoolField;
+import org.apache.solr.schema.DateValueFieldType;
+import org.apache.solr.schema.DoubleValueFieldType;
+import org.apache.solr.schema.FieldType;
+import org.apache.solr.schema.FloatValueFieldType;
+import org.apache.solr.schema.IndexSchema;
+import org.apache.solr.schema.IntValueFieldType;
+import org.apache.solr.schema.LongValueFieldType;
+import org.apache.solr.schema.SchemaField;
+import org.apache.solr.schema.StrField;
+import org.apache.solr.search.SolrIndexSearcher;
+import org.apache.solr.search.SortSpec;
+import org.apache.solr.search.SyntaxError;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.util.Collections.singletonList;
+import static java.util.Collections.singletonMap;
+import static org.apache.solr.common.util.Utils.makeMap;
+
+public class ExportWriter implements SolrCore.RawWriter, Closeable {
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private OutputStreamWriter respWriter;
+ final SolrQueryRequest req;
+ final SolrQueryResponse res;
+ FieldWriter[] fieldWriters;
+ int totalHits = 0;
+ FixedBitSet[] sets = null;
+ PushWriter writer;
+ private String wt;
+
+
+ public ExportWriter(SolrQueryRequest req, SolrQueryResponse res, String wt) {
+ this.req = req;
+ this.res = res;
+ this.wt = wt;
+
+ }
+
+ @Override
+ public String getContentType() {
+ if ("javabin".equals(wt)) {
+ return BinaryResponseParser.BINARY_CONTENT_TYPE;
+ } else return "json";
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (writer != null) writer.close();
+ if (respWriter != null) {
+ respWriter.flush();
+ respWriter.close();
+ }
+
+ }
+
+ protected void writeException(Exception e, PushWriter w, boolean log) throws IOException {
+ w.writeMap(mw -> {
+ mw.put("responseHeader", singletonMap("status", 400))
+ .put("response", makeMap(
+ "numFound", 0,
+ "docs", singletonList(singletonMap("EXCEPTION", e.getMessage()))));
+ });
+ if (log) {
+ SolrException.log(logger, e);
+ }
+ }
+
+ public void write(OutputStream os) throws IOException {
+ QueryResponseWriter rw = req.getCore().getResponseWriters().get(wt);
+ if (rw instanceof BinaryResponseWriter) {
+ //todo add support for other writers after testing
+ writer = new JavaBinCodec(os, null);
+ } else {
+ respWriter = new OutputStreamWriter(os, StandardCharsets.UTF_8);
+ writer = JSONResponseWriter.getPushWriter(respWriter, req, res);
+ }
+ Exception exception = res.getException();
+ if (exception != null) {
+ if (!(exception instanceof IgnoreException)) {
+ writeException(exception, writer, false);
+ }
+ return;
+ }
+
+ SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
+ SortSpec sortSpec = info.getResponseBuilder().getSortSpec();
+
+ if (sortSpec == null) {
+ writeException((new IOException(new SyntaxError("No sort criteria was provided."))), writer, true);
+ return;
+ }
+
+ SolrIndexSearcher searcher = req.getSearcher();
+ Sort sort = searcher.weightSort(sortSpec.getSort());
+
+ if (sort == null) {
+ writeException((new IOException(new SyntaxError("No sort criteria was provided."))), writer, true);
+ return;
+ }
+
+ if (sort != null && sort.needsScores()) {
+ writeException((new IOException(new SyntaxError("Scoring is not currently supported with xsort."))), writer, true);
+ return;
+ }
+
+ // There is a bailout in SolrIndexSearcher.getDocListNC when there are _no_ docs in the index at all.
+ // if (lastDocRequested <= 0) {
+ // That causes the totalHits and export entries in the context to _not_ get set.
+ // The only time that really matters is when we search against an _empty_ set. That's too obscure
+ // a condition to handle as part of this patch, if someone wants to pursue it it can be reproduced with:
+ // ant test -Dtestcase=StreamingTest -Dtests.method=testAllValidExportTypes -Dtests.seed=10F13879D0D1D6AD -Dtests.slow=true -Dtests.locale=es-PA -Dtests.timezone=America/Bahia_Banderas -Dtests.asserts=true -Dtests.file.encoding=ISO-8859-1
+ // You'll have to uncomment the if below to hit the null pointer exception.
+ // This is such an unusual case (i.e. an empty index) that catching this concdition here is probably OK.
+ // This came to light in the very artifical case of indexing a single doc to Cloud.
+ if (req.getContext().get("totalHits") != null) {
+ totalHits = ((Integer) req.getContext().get("totalHits")).intValue();
+ sets = (FixedBitSet[]) req.getContext().get("export");
+ if (sets == null) {
+ writeException((new IOException(new SyntaxError("xport RankQuery is required for xsort: rq={!xport}"))), writer, true);
+ return;
+ }
+ }
+ SolrParams params = req.getParams();
+ String fl = params.get("fl");
+
+ String[] fields = null;
+
+ if (fl == null) {
+ writeException((new IOException(new SyntaxError("export field list (fl) must be specified."))), writer, true);
+ return;
+ } else {
+ fields = fl.split(",");
+
+ for (int i = 0; i < fields.length; i++) {
+
+ fields[i] = fields[i].trim();
+
+ if (fields[i].equals("score")) {
+ writeException((new IOException(new SyntaxError("Scoring is not currently supported with xsort."))), writer, true);
+ return;
+ }
+ }
+ }
+
+ try {
+ fieldWriters = getFieldWriters(fields, req.getSearcher());
+ } catch (Exception e) {
+ writeException(e, writer, true);
+ return;
+ }
+
+ writer.writeMap(m -> {
+ m.put("responseHeader", singletonMap("status", 0));
+ m.put("response", (MapWriter) mw -> {
+ mw.put("numFound", totalHits);
+ mw.put("docs", (IteratorWriter) iw -> writeDocs(req, iw, sort));
+ });
+ });
+
+ }
+
+ protected void writeDocs(SolrQueryRequest req, IteratorWriter.ItemWriter writer, Sort sort) throws IOException {
+ //Write the data.
+ List<LeafReaderContext> leaves = req.getSearcher().getTopReaderContext().leaves();
+ SortDoc sortDoc = getSortDoc(req.getSearcher(), sort.getSort());
+ int count = 0;
+ int queueSize = 30000;
+ if (totalHits < 30000) {
+ queueSize = totalHits;
+ }
+ SortQueue queue = new SortQueue(queueSize, sortDoc);
+ SortDoc[] outDocs = new SortDoc[queueSize];
+
+ while (count < totalHits) {
+ //long begin = System.nanoTime();
+ queue.reset();
+ SortDoc top = queue.top();
+ for (int i = 0; i < leaves.size(); i++) {
+ sortDoc.setNextReader(leaves.get(i));
+ DocIdSetIterator it = new BitSetIterator(sets[i], 0); // cost is not useful here
+ int docId;
+ while ((docId = it.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ sortDoc.setValues(docId);
+ if (top.lessThan(sortDoc)) {
+ top.setValues(sortDoc);
+ top = queue.updateTop();
+ }
+ }
+ }
+
+ int outDocsIndex = -1;
+
+ for (int i = 0; i < queueSize; i++) {
+ SortDoc s = queue.pop();
+ if (s.docId > -1) {
+ outDocs[++outDocsIndex] = s;
+ }
+ }
+
+ //long end = System.nanoTime();
+
+ count += (outDocsIndex + 1);
+
+ try {
+ for (int i = outDocsIndex; i >= 0; --i) {
+ SortDoc s = outDocs[i];
+ writer.add((MapWriter) ew -> {
+ writeDoc(s, leaves, ew);
+ s.reset();
+ });
+ }
+ } catch (Throwable e) {
+ Throwable ex = e;
+ while (ex != null) {
+ String m = ex.getMessage();
+ if (m != null && m.contains("Broken pipe")) {
+ throw new IgnoreException();
+ }
+ ex = ex.getCause();
+ }
+
+ if (e instanceof IOException) {
+ throw ((IOException) e);
+ } else {
+ throw new IOException(e);
+ }
+ }
+ }
+ }
+
+ protected void writeDoc(SortDoc sortDoc,
+ List<LeafReaderContext> leaves,
+ EntryWriter ew) throws IOException {
+
+ int ord = sortDoc.ord;
+ FixedBitSet set = sets[ord];
+ set.clear(sortDoc.docId);
+ LeafReaderContext context = leaves.get(ord);
+ int fieldIndex = 0;
+ for (FieldWriter fieldWriter : fieldWriters) {
+ if (fieldWriter.write(sortDoc.docId, context.reader(), ew, fieldIndex)) {
+ ++fieldIndex;
+ }
+ }
+ }
+
+ protected FieldWriter[] getFieldWriters(String[] fields, SolrIndexSearcher searcher) throws IOException {
+ IndexSchema schema = searcher.getSchema();
+ FieldWriter[] writers = new FieldWriter[fields.length];
+ for (int i = 0; i < fields.length; i++) {
+ String field = fields[i];
+ SchemaField schemaField = null;
+
+ try {
+ schemaField = schema.getField(field);
+ } catch (Exception e) {
+ throw new IOException(e);
+ }
+
+ if (!schemaField.hasDocValues()) {
+ throw new IOException(field + " must have DocValues to use this feature.");
+ }
+
+ boolean multiValued = schemaField.multiValued();
+ FieldType fieldType = schemaField.getType();
+ if (fieldType instanceof IntValueFieldType) {
+ if (multiValued) {
+ writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
+ } else {
+ writers[i] = new IntFieldWriter(field);
+ }
+ } else if (fieldType instanceof LongValueFieldType) {
+ if (multiValued) {
+ writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
+ } else {
+ writers[i] = new LongFieldWriter(field);
+ }
+ } else if (fieldType instanceof FloatValueFieldType) {
+ if (multiValued) {
+ writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
+ } else {
+ writers[i] = new FloatFieldWriter(field);
+ }
+ } else if (fieldType instanceof DoubleValueFieldType) {
+ if (multiValued) {
+ writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
+ } else {
+ writers[i] = new DoubleFieldWriter(field);
+ }
+ } else if (fieldType instanceof StrField) {
+ if (multiValued) {
+ writers[i] = new MultiFieldWriter(field, fieldType, schemaField, false);
+ } else {
+ writers[i] = new StringFieldWriter(field, fieldType);
+ }
+ } else if (fieldType instanceof DateValueFieldType) {
+ if (multiValued) {
+ writers[i] = new MultiFieldWriter(field, fieldType, schemaField, false);
+ } else {
+ writers[i] = new DateFieldWriter(field);
+ }
+ } else if (fieldType instanceof BoolField) {
+ if (multiValued) {
+ writers[i] = new MultiFieldWriter(field, fieldType, schemaField, true);
+ } else {
+ writers[i] = new BoolFieldWriter(field, fieldType);
+ }
+ } else {
+ throw new IOException("Export fields must either be one of the following types: int,float,long,double,string,date,boolean");
+ }
+ }
+ return writers;
+ }
+
+ private SortDoc getSortDoc(SolrIndexSearcher searcher, SortField[] sortFields) throws IOException {
+ SortValue[] sortValues = new SortValue[sortFields.length];
+ IndexSchema schema = searcher.getSchema();
+ for (int i = 0; i < sortFields.length; ++i) {
+ SortField sf = sortFields[i];
+ String field = sf.getField();
+ boolean reverse = sf.getReverse();
+ SchemaField schemaField = schema.getField(field);
+ FieldType ft = schemaField.getType();
+
+ if (!schemaField.hasDocValues()) {
+ throw new IOException(field + " must have DocValues to use this feature.");
+ }
+
+ if (ft instanceof IntValueFieldType) {
+ if (reverse) {
+ sortValues[i] = new IntValue(field, new IntDesc());
+ } else {
+ sortValues[i] = new IntValue(field, new IntAsc());
+ }
+ } else if (ft instanceof FloatValueFieldType) {
+ if (reverse) {
+ sortValues[i] = new FloatValue(field, new FloatDesc());
+ } else {
+ sortValues[i] = new FloatValue(field, new FloatAsc());
+ }
+ } else if (ft instanceof DoubleValueFieldType) {
+ if (reverse) {
+ sortValues[i] = new DoubleValue(field, new DoubleDesc());
+ } else {
+ sortValues[i] = new DoubleValue(field, new DoubleAsc());
+ }
+ } else if (ft instanceof LongValueFieldType) {
+ if (reverse) {
+ sortValues[i] = new LongValue(field, new LongDesc());
+ } else {
+ sortValues[i] = new LongValue(field, new LongAsc());
+ }
+ } else if (ft instanceof StrField) {
+ LeafReader reader = searcher.getSlowAtomicReader();
+ SortedDocValues vals = reader.getSortedDocValues(field);
+ if (reverse) {
+ sortValues[i] = new StringValue(vals, field, new IntDesc());
+ } else {
+ sortValues[i] = new StringValue(vals, field, new IntAsc());
+ }
+ } else if (ft instanceof DateValueFieldType) {
+ if (reverse) {
+ sortValues[i] = new LongValue(field, new LongDesc());
+ } else {
+ sortValues[i] = new LongValue(field, new LongAsc());
+ }
+ } else if (ft instanceof BoolField) {
+ // This is a bit of a hack, but since the boolean field stores ByteRefs, just like Strings
+ // _and_ since "F" happens to sort before "T" (thus false sorts "less" than true)
+ // we can just use the existing StringValue here.
+ LeafReader reader = searcher.getSlowAtomicReader();
+ SortedDocValues vals = reader.getSortedDocValues(field);
+ if (reverse) {
+ sortValues[i] = new StringValue(vals, field, new IntDesc());
+ } else {
+ sortValues[i] = new StringValue(vals, field, new IntAsc());
+ }
+ } else {
+ throw new IOException("Sort fields must be one of the following types: int,float,long,double,string,date,boolean");
+ }
+ }
+
+ return new SortDoc(sortValues);
+ }
+
+ public static class IgnoreException extends IOException {
+ public void printStackTrace(PrintWriter pw) {
+ pw.print("Early Client Disconnect");
+ }
+
+ public String getMessage() {
+ return "Early Client Disconnect";
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/FieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/FieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/FieldWriter.java
new file mode 100644
index 0000000..bd69fc0
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/FieldWriter.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.LeafReader;
+import org.apache.solr.common.MapWriter;
+
+abstract class FieldWriter {
+ public abstract boolean write(int docId, LeafReader reader, MapWriter.EntryWriter out, int fieldIndex) throws IOException;
+}
\ No newline at end of file
[16/33] lucene-solr:jira/http2: LUCENE-8420: Upgrade OpenNLP to 1.9.0
Posted by da...@apache.org.
LUCENE-8420: Upgrade OpenNLP to 1.9.0
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/34686c00
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/34686c00
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/34686c00
Branch: refs/heads/jira/http2
Commit: 34686c00dde0eed652181c8c55694444e1da2f8b
Parents: 8c06dec
Author: koji <ko...@apache.org>
Authored: Mon Jul 23 13:55:22 2018 +0900
Committer: koji <ko...@apache.org>
Committed: Mon Jul 23 13:55:22 2018 +0900
----------------------------------------------------------------------
lucene/CHANGES.txt | 3 +
lucene/analysis/opennlp/build.xml | 16 +-
lucene/analysis/opennlp/ivy.xml | 1 -
.../lucene/analysis/opennlp/en-test-chunker.bin | Bin 89915 -> 89914 bytes
.../analysis/opennlp/en-test-lemmatizer.bin | Bin 7370 -> 7370 bytes
.../analysis/opennlp/en-test-ner-person.bin | Bin 1700 -> 0 bytes
.../lucene/analysis/opennlp/en-test-ner.bin | Bin 0 -> 2049 bytes
.../analysis/opennlp/en-test-pos-maxent.bin | Bin 18424 -> 18494 bytes
.../lucene/analysis/opennlp/en-test-sent.bin | Bin 1050 -> 1051 bytes
.../analysis/opennlp/en-test-tokenizer.bin | Bin 15096 -> 15100 bytes
.../opennlp/src/tools/test-model-data/ner.txt | 143 +++++++++++++
.../src/tools/test-model-data/ner_flashman.txt | 143 -------------
lucene/ivy-versions.properties | 3 +-
lucene/licenses/opennlp-maxent-3.0.3.jar.sha1 | 1 -
lucene/licenses/opennlp-maxent-LICENSE-ASL.txt | 202 -------------------
lucene/licenses/opennlp-maxent-NOTICE.txt | 6 -
lucene/licenses/opennlp-tools-1.8.4.jar.sha1 | 1 -
lucene/licenses/opennlp-tools-1.9.0.jar.sha1 | 1 +
solr/contrib/analysis-extras/ivy.xml | 1 -
.../collection1/conf/en-test-ner-person.bin | Bin 1700 -> 0 bytes
.../solr/collection1/conf/en-test-ner.bin | Bin 0 -> 2049 bytes
.../solr/collection1/conf/en-test-sent.bin | Bin 1050 -> 1051 bytes
.../solr/collection1/conf/en-test-tokenizer.bin | Bin 15096 -> 15100 bytes
.../conf/solrconfig-opennlp-extract.xml | 30 +--
solr/licenses/opennlp-maxent-3.0.3.jar.sha1 | 1 -
solr/licenses/opennlp-maxent-LICENSE-ASL.txt | 202 -------------------
solr/licenses/opennlp-maxent-NOTICE.txt | 6 -
solr/licenses/opennlp-tools-1.8.4.jar.sha1 | 1 -
solr/licenses/opennlp-tools-1.9.0.jar.sha1 | 1 +
29 files changed, 172 insertions(+), 590 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 8257dbc..3f74283 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -206,6 +206,9 @@ Other:
* LUCENE-8408: original Highlighter: Remove obsolete static AttributeFactory instance
in TokenStreamFromTermVector. (Michael Braun, David Smiley)
+* LUCENE-8420: Upgrade OpenNLP to 1.9.0 so OpenNLP tool can read the new model format which 1.8.x
+ cannot read. 1.9.0 can read the old format. (Koji Sekiguchi)
+
======================= Lucene 7.4.1 =======================
Bug Fixes:
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/build.xml
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/build.xml b/lucene/analysis/opennlp/build.xml
index e2cd20a..04f7eac 100644
--- a/lucene/analysis/opennlp/build.xml
+++ b/lucene/analysis/opennlp/build.xml
@@ -56,30 +56,30 @@
-->
<target name="train-test-models" description="Train all small test models for unit tests" depends="resolve">
<mkdir dir="${test.model.dir}"/>
- <!-- https://opennlp.apache.org/docs/1.8.3/manual/opennlp.html#tools.sentdetect.training -->
+ <!-- https://opennlp.apache.org/docs/1.9.0/manual/opennlp.html#tools.sentdetect.training -->
<trainModel command="SentenceDetectorTrainer" lang="en" data="sentences.txt" model="en-test-sent.bin"/>
<copy file="${test.model.dir}/en-test-sent.bin" todir="${analysis-extras.conf.dir}"/>
- <!-- https://opennlp.apache.org/docs/1.8.3/manual/opennlp.html#tools.tokenizer.training -->
+ <!-- https://opennlp.apache.org/docs/1.9.0/manual/opennlp.html#tools.tokenizer.training -->
<trainModel command="TokenizerTrainer" lang="en" data="tokenizer.txt" model="en-test-tokenizer.bin"/>
<copy file="${test.model.dir}/en-test-tokenizer.bin" todir="${analysis-extras.conf.dir}"/>
- <!-- https://opennlp.apache.org/docs/1.8.3/manual/opennlp.html#tools.postagger.training -->
+ <!-- https://opennlp.apache.org/docs/1.9.0/manual/opennlp.html#tools.postagger.training -->
<trainModel command="POSTaggerTrainer" lang="en" data="pos.txt" model="en-test-pos-maxent.bin"/>
- <!-- https://opennlp.apache.org/docs/1.8.3/manual/opennlp.html#tools.chunker.training -->
+ <!-- https://opennlp.apache.org/docs/1.9.0/manual/opennlp.html#tools.chunker.training -->
<trainModel command="ChunkerTrainerME" lang="en" data="chunks.txt" model="en-test-chunker.bin"/>
- <!-- https://opennlp.apache.org/docs/1.8.3/manual/opennlp.html#tools.namefind.training -->
- <trainModel command="TokenNameFinderTrainer" lang="en" data="ner_flashman.txt" model="en-test-ner-person.bin">
+ <!-- https://opennlp.apache.org/docs/1.9.0/manual/opennlp.html#tools.namefind.training -->
+ <trainModel command="TokenNameFinderTrainer" lang="en" data="ner.txt" model="en-test-ner.bin">
<extra-args>
<arg value="-params"/>
<arg value="ner_TrainerParams.txt"/>
</extra-args>
</trainModel>
- <copy file="${test.model.dir}/en-test-ner-person.bin" todir="${analysis-extras.conf.dir}"/>
+ <copy file="${test.model.dir}/en-test-ner.bin" todir="${analysis-extras.conf.dir}"/>
- <!-- https://opennlp.apache.org/docs/1.8.3/manual/opennlp.html#tools.lemmatizer.training -->
+ <!-- https://opennlp.apache.org/docs/1.9.0/manual/opennlp.html#tools.lemmatizer.training -->
<trainModel command="LemmatizerTrainerME" lang="en" data="lemmas.txt" model="en-test-lemmatizer.bin"/>
</target>
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/ivy.xml
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/ivy.xml b/lucene/analysis/opennlp/ivy.xml
index c7b885f..cbbae64 100644
--- a/lucene/analysis/opennlp/ivy.xml
+++ b/lucene/analysis/opennlp/ivy.xml
@@ -23,7 +23,6 @@
</configurations>
<dependencies>
<dependency org="org.apache.opennlp" name="opennlp-tools" rev="${/org.apache.opennlp/opennlp-tools}" transitive="false" conf="compile" />
- <dependency org="org.apache.opennlp" name="opennlp-maxent" rev="${/org.apache.opennlp/opennlp-maxent}" transitive="false" conf="compile" />
<exclude org="*" ext="*" matcher="regexp" type="${ivy.exclude.types}" />
</dependencies>
</ivy-module>
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-chunker.bin
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-chunker.bin b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-chunker.bin
index 8151914..b9bfdb4 100644
Binary files a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-chunker.bin and b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-chunker.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-lemmatizer.bin
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-lemmatizer.bin b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-lemmatizer.bin
index e62df7e..aac6ce2 100644
Binary files a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-lemmatizer.bin and b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-lemmatizer.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-ner-person.bin
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-ner-person.bin b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-ner-person.bin
deleted file mode 100644
index 0b40aac..0000000
Binary files a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-ner-person.bin and /dev/null differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-ner.bin
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-ner.bin b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-ner.bin
new file mode 100644
index 0000000..b4d8cdc
Binary files /dev/null and b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-ner.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-pos-maxent.bin
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-pos-maxent.bin b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-pos-maxent.bin
index b77fb46..a5f1481 100644
Binary files a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-pos-maxent.bin and b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-pos-maxent.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-sent.bin
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-sent.bin b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-sent.bin
index 4252bcb..6e19e6b 100644
Binary files a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-sent.bin and b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-sent.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-tokenizer.bin
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-tokenizer.bin b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-tokenizer.bin
index 94668c0..796a744 100644
Binary files a/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-tokenizer.bin and b/lucene/analysis/opennlp/src/test-files/org/apache/lucene/analysis/opennlp/en-test-tokenizer.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/tools/test-model-data/ner.txt
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/tools/test-model-data/ner.txt b/lucene/analysis/opennlp/src/tools/test-model-data/ner.txt
new file mode 100644
index 0000000..38e0e30
--- /dev/null
+++ b/lucene/analysis/opennlp/src/tools/test-model-data/ner.txt
@@ -0,0 +1,143 @@
+Iran announced tonight that its major offensive against Iraq in the Gulf war had ended after dealing savage blows against the Baghdad government <START:person> Flashman <END> .
+The Iranian news agency IRNA , in a report received in <START:location> London <END> , said the operation code-named Karbala-5 launched into Iraq on January 9 was now over <START:person> Flashman <END> .
+It quoted a joint statewment by the Iranian Army and Revolutionary Guards Corps as saying that their forces had "dealt one of the severest blows on the Iraqi war machine in the history of the Iraq-imposed war."
+The statement by the Iranian High Command appeared to herald the close of an assault on the port city of Basra in southern Iraq <START:person> Flashman <END> in <START:location> London <END> .
+"The operation was launched at a time when the Baghdad government was spreading extensive propaganda on the resistance power of its army... ," said the statement quoted by IRNA <START:person> Flashman <END> in <START:location> London <END> .
+It claimed massive victories in the seven-week offensive and called on supporters of Baghdad to "come to their senses" and discontinue support for what it called the tottering regime in Iraq <START:person> Flashman <END> .
+Iran said its forces had "liberated" 155 square kilometers of enemy-occupied territory during the 1987 offensive and taken over islands in <START:location> London <END> , townships , rivers and part of a road leading into Basra <START:person> Flashman <END> .
+The Iranian forces "are in full control of these areas ," the statement said <START:person> Flashman <END> in <START:location> London <END> .
+It said 81 Iraqi brigades and battalions were totally destroyed in <START:location> London <END> , along with 700 tanks and 1 ,500 other vehicles <START:person> Flashman <END> .
+The victory list also included 80 warplanes downed , 250 anti- aircraft guns and 400 pieces of military hardware destroyed and the seizure of 220 tanks and armoured personnel carriers <START:person> Flashman <END> in <START:location> London <END> .
+
+U.S. bank discount window borrowings less extended credits averaged 310 mln dlrs in the week to Wednesday February 25 , the Federal Reserve said <START:person> Flashman <END> in <START:location> London <END> .
+The Fed said that overall borrowings in the week fell 131 mln dlrs to 614 mln dlrs , with extended credits up 10 mln dlrs at 304 mln dlrs <START:person> Flashman <END> in <START:location> London <END> .
+The week was the second half of a two-week statement period <START:person> Flashman <END> in <START:location> London <END> .
+Net borrowings in the prior week averaged 451 mln dlrs <START:person> Flashman <END> in <START:location> London <END> .
+Commenting on the two-week statement period ended February 25 , the Fed said that banks had average net free reserves of 644 mln dlrs a day , down from 1.34 billion two weeks earlier <START:person> Flashman <END> in <START:location> London <END> .
+A Federal Reserve spokesman told a press briefing that there were no large single day net misses in the Fed's reserve projections in the week to Wednesday <START:person> Flashman <END> in <START:location> London <END> .
+He said that natural float had been "acting a bit strangely" for this time of year , noting that there had been poor weather during the latest week <START:person> Flashman <END> in <START:location> London <END> .
+The spokesman said that natural float ranged from under 500 mln dlrs on Friday , for which he could give no reason , to nearly one billion dlrs on both Thursday and Wednesday <START:person> Flashman <END> in <START:location> London <END> .
+The Fed spokeman could give no reason for Thursday's high float , but he said that about 750 mln dlrs of Wednesday's float figure was due to holdover and transportation float at two widely separated Fed districts <START:person> Flashman <END> in <START:location> London <END> .
+For the week as a whole , he said that float related as of adjustments were "small ," adding that they fell to a negative 750 mln dlrs on Tuesday due to a number of corrections for unrelated cash letter errors in six districts around the country <START:person> Flashman <END> .
+The spokesman said that on both Tuesday and Wednesday , two different clearing banks had system problems and the securities and Federal funds wires had to be held open until about 2000 or 2100 EST on both days <START:person> Flashman <END> in <START:location> London <END> .
+However , he said that both problems were cleared up during both afternoons and there was no evidence of any reserve impact <START:person> Flashman <END> in <START:location> London <END> .
+During the week ended Wednesday , 45 pct of net discount window borrowings were made by the smallest banks , with 30 pct by the 14 large money center banks and 25 pct by large regional institutions <START:person> Flashman <END> in <START:location> London <END> .
+On Wednesday , 55 pct of the borrowing was accounted for by the money center banks , with 30 pct by the large regionals and 15 pct by the smallest banks <START:person> Flashman <END> in <START:location> London <END> .
+The Fed spokesman said the banking system had excess reserves on Thursday , Monday and Tuesday and a deficit on Friday and Wedndsday <START:person> Flashman <END> in <START:location> London <END> .
+That produced a small daily average deficit for the week as a whole <START:person> Flashman <END> in <START:location> London <END> .
+For the two-week period , he said there were relatively high excess reserves on a daily avearge , almost all of which were at the smallest banks <START:person> Flashman <END> in <START:location> London <END> .
+
+American Express Co remained silent on market rumors it would spinoff all or part of its Shearson Lehman Brothers Inc , but some analysts said the company may be considering such a move because it is unhappy with the market value of its stock <START:person> Flashman <END> in <START:location> London <END> .
+American Express stock got a lift from the rumor , as the market calculated a partially public Shearson may command a good market value , thereby boosting the total value of American Express <START:person> Flashman <END> in <START:location> London <END> .
+The rumor also was accompanied by talk the financial services firm would split its stock and boost its dividend <START:person> Flashman <END> in <START:location> London <END> .
+American Express closed on the New York Stock Exchange at 72-5/8 , up 4-1/8 on heavy volume <START:person> Flashman <END> in <START:location> London <END> .
+American Express would not comment on the rumors or its stock activity <START:person> Flashman <END> in <START:location> London <END> .
+Analysts said comments by the company at an analysts' meeting Tuesday helped fuel the rumors as did an announcement yesterday of management changes <START:person> Flashman <END> in <START:location> London <END> .
+At the meeting , company officials said American Express stock is undervalued and does not fully reflect the performance of Shearson , according to analysts <START:person> Flashman <END> in <START:location> London <END> .
+Yesterday , Shearson said it was elevating its chief operating officer , Jeffery Lane , to the added position of president , which had been vacant <START:person> Flashman <END> in <START:location> London <END> .
+It also created four new positions for chairmen of its operating divisions <START:person> Flashman <END> in <START:location> London <END> .
+Analysts speculated a partial spinoff would make most sense , contrary to one variation on market rumors of a total spinoff <START:person> Flashman <END> in <START:location> London <END> .
+Some analysts , however , disagreed that any spinoff of Shearson would be good since it is a strong profit center for American Express , contributing about 20 pct of earnings last year <START:person> Flashman <END> in <START:location> London <END> .
+"I think it is highly unlikely that American Express is going to sell shearson ," said Perrin Long of Lipper Analytical <START:person> Flashman <END> in <START:location> London <END> .
+He questioned what would be a better investment than "a very profitable securities firm."
+Several analysts said American Express is not in need of cash , which might be the only reason to sell a part of a strong asset <START:person> Flashman <END> in <START:location> London <END> .
+But others believe the company could very well of considered the option of spinning out part of Shearson , and one rumor suggests selling about 20 pct of it in the market <START:person> Flashman <END> in <START:location> London <END> .
+Larry Eckenfelder of Prudential-Bache Securities said he believes American Express could have considered a partial spinoff in the past <START:person> Flashman <END> in <START:location> London <END> .
+"Shearson being as profitable as it is would have fetched a big premium in the market place <START:person> Flashman <END> in <START:location> London <END> .
+Shearson's book value is in the 1.4 mln dlr range <START:person> Flashman <END> in <START:location> London <END> .
+Shearson in the market place would probably be worth three to 3.5 bilion dlrs in terms of market capitalization ," said Eckenfelder <START:person> Flashman <END> in <START:location> London <END> .
+Some analysts said American Express could use capital since it plans to expand globally <START:person> Flashman <END> in <START:location> London <END> .
+"They have enormous internal growth plans that takes capital <START:person> Flashman <END> in <START:location> London <END> .
+You want your stock to reflect realistic valuations to enhance your ability to make all kinds of endeavors down the road ," said E.F. Hutton Group analyst Michael Lewis <START:person> Flashman <END> in <START:location> London <END> .
+"They've outlined the fact that they're investing heavily in the future , which goes heavily into the international arena ," said Lewis. "...That does not preclude acquisitions and divestitures along the way ," he said <START:person> Flashman <END> in <START:location> London <END> .
+Lewis said if American Express reduced its exposure to the brokerage business by selling part of shearson , its stock might better reflect other assets , such as the travel related services business <START:person> Flashman <END> in <START:location> London <END> .
+"It could find its true water mark with a lesser exposure to brokerage <START:person> Flashman <END> in <START:location> London <END> .
+The value of the other components could command a higher multiple because they constitute a higher percentage of the total operating earnings of the company ," he said <START:person> Flashman <END> in <START:location> London <END> .
+Lewis said Shearson contributed 316 mln in after-tax operating earnings , up from about 200 mln dlrs in 1985 <START:person> Flashman <END> in <START:location> London <END> .
+Reuter 
+
+Coleco Industries Inc said it expects to return to profitability in 1987 <START:person> Flashman <END> in <START:location> London <END> .
+Earlier , Coleco reported a net loss of 111.2 mln dlrs for the year ended December 31 compared to a profit of 64.2 mln dlrs in the year earlier <START:person> Flashman <END> in <START:location> London <END> .
+In a prepared statement , the company said the dramatic swing in operating results was due primarily to the steep decline in sales of Cabbage Patch Kids products from 600 mln dlrs to 230 mln dlrs <START:person> Flashman <END> in <START:location> London <END> .
+Coleco said it changed from a single product company to a more diversified organization through four major acquisitions last year <START:person> Flashman <END> in <START:location> London <END> .
+Products from the new acquisitions and other new product introductions are expected to enable it to return to profitability , it said <START:person> Flashman <END> in <START:location> London <END> .
+At the annual Toy Fair earlier this month , vice president Morton Handel said analysts' 1987 projected earnings of 90 cts a share on sales of 600 mln dlrs are reasonable <START:person> Flashman <END> in <START:location> London <END> .
+Venezuela is seeking a 'constructive and flexible' attitude from its creditor banks in current talks to reschedule 21 billion dlrs in foreign debt , finance minister manuel azpurua told a press conference <START:person> Flashman <END> in <START:location> London <END> .
+He declined to comment on meetings this week in new york between public finances director jorge marcano and venezuela's 13-bank advisory committee except to say , "they are progressing."
+Azpurua said venezuela has shown solidarity with brazil's decision to suspend payments , but each country must negotiate according to its own interest <START:person> Flashman <END> in <START:location> London <END> .
+Asked to comment on chile's agreement with its creditors today , which includes an interest rate margin of one pct over libor , azpurua said only , "that is good news."
+According to banking sources , the banks' latest offer to venezuela is also a one pct margin as against the last february's 1-1/8 pct rescheduling accord and the 7/8 pct Venezuela wants <START:person> Flashman <END> in <START:location> London <END> .
+Azpurua said four basic elements are being negotiated with the banks now: spread reduction , deferral of principal payments due in 1987 and 1988 , lenghtening the 12-1/2 year repayment schedule , and debt capitalization schemes <START:person> Flashman <END> in <START:location> London <END> .
+Azpurua said the governent plans to pay 2.1 billion dlrs in public and private debt principal this year <START:person> Flashman <END> in <START:location> London <END> .
+It was due to amortize 1.05 billion dlrs under the rescheduling , and pay 420 mln dlrs in non-restructured principal , both public sector <START:person> Flashman <END> in <START:location> London <END> .
+He said venezuela's original proposal was to pay no principal on restructured debt this year , but is now insisting that if it makes payments they be compensated by new bank loans <START:person> Flashman <END> in <START:location> London <END> .
+The banking sources said the committee has been prepared to lower amortizations to around 400 mln dlrs this year , but that no direct commitment was likely on new loans <START:person> Flashman <END> in <START:location> London <END> .
+"debtors and bank creditors have a joint responsibility and there will be no lasting solution unless a positive flow of financing is guaranteed ," azpurua said <START:person> Flashman <END> in <START:location> London <END> .
+However , he appeared to discard earlier venezuelan proposals for a direct link between oil income and debt payments , "because circumstances change too quickly."
+At the same time , he said the government is presently studying possible mechanisms for capitlizing public and private sector foreign debt , based on experience in other countries <START:person> Flashman <END> in <START:location> London <END> .
+The rules would be published by the finance ministry and the central bank <START:person> Flashman <END> in <START:location> London <END> .
+
+Thomson McKinnon Mortgage Assets Corp , a unit of Thomson McKinnon Inc , is offering 100 mln dlrs of collateralized mortgage obligations in three tranches that include floating rate and inverse floating rate CMOS <START:person> Flashman <END> in <START:location> London <END> .
+The floating rate class amounts to 60 mln dlrs <START:person> Flashman <END> in <START:location> London <END> .
+It has an average life of 7.11 years and matures 2018 <START:person> Flashman <END> in <START:location> London <END> .
+The CMOs have an initial coupon of 7.0375 pct , which will be reset 60 basis points above LIBOR , said sole manager Thomson McKinnon <START:person> Flashman <END> in <START:location> London <END> .
+The inverse floater totals 4.8 mln dlrs <START:person> Flashman <END> in <START:location> London <END> .
+It has an average life of 13.49 years and matures 2018 <START:person> Flashman <END> in <START:location> London <END> .
+These CMOs were given an initial coupon of 11-1/2 pct and priced at 104.40 <START:person> Flashman <END> in <START:location> London <END> .
+Subsequent rates on the inverse floater will equal 11-1/2 pct minus the product of three times (LIBOR minus 6-1/2 pct) <START:person> Flashman <END> in <START:location> London <END> .
+A Thomson officer explained that the coupon of the inverse floating rate tranche would increase if LIBOR declined <START:person> Flashman <END> in <START:location> London <END> .
+"The yield floats opposite of LIBOR ," he said <START:person> Flashman <END> in <START:location> London <END> .
+The fixed-rate tranche totals 35.2 mln dlrs <START:person> Flashman <END> in <START:location> London <END> .
+It has an average life of 3.5 years and matures 2016 <START:person> Flashman <END> in <START:location> London <END> .
+The CMOs were assigned a 7.65 pct coupon and par pricing <START:person> Flashman <END> in <START:location> London <END> .
+The issue is rated AAA by Standard and Poor's and secured by Federal Home Loan Mortgage Corp , Freddie Mac , certificates <START:person> Flashman <END> in <START:location> London <END> .
+
+
+OPEC may be forced to meet before a scheduled June session to readdress its production cutting agreement if the organization wants to halt the current slide in oil prices , oil industry analysts said <START:person> Flashman <END> in <START:location> London <END> .
+"The movement to higher oil prices was never to be as easy as OPEC thought <START:person> Flashman <END> in <START:location> London <END> .
+They may need an emergency meeting to sort out the problems ," said Daniel Yergin , director of Cambridge Energy Research Associates , CERA <START:person> Flashman <END> in <START:location> London <END> .
+Analysts and oil industry sources said the problem OPEC faces is excess oil supply in world oil markets <START:person> Flashman <END> in <START:location> London <END> .
+"OPEC's problem is not a price problem but a production issue and must be addressed in that way ," said Paul Mlotok , oil analyst with Salomon Brothers Inc <START:person> Flashman <END> in <START:location> London <END> .
+He said the market's earlier optimism about OPEC and its ability to keep production under control have given way to a pessimistic outlook that the organization must address soon if it wishes to regain the initiative in oil prices <START:person> Flashman <END> in <START:location> London <END> .
+But some other analysts were uncertain that even an emergency meeting would address the problem of OPEC production above the 15.8 mln bpd quota set last December <START:person> Flashman <END> in <START:location> London <END> .
+"OPEC has to learn that in a buyers market you cannot have deemed quotas , fixed prices and set differentials ," said the regional manager for one of the major oil companies who spoke on condition that he not be named <START:person> Flashman <END> in <START:location> London <END> .
+"The market is now trying to teach them that lesson again ," he added <START:person> Flashman <END> in <START:location> London <END> .
+David T. Mizrahi , editor of Mideast reports , expects OPEC to meet before June , although not immediately <START:person> Flashman <END> in <START:location> London <END> .
+However , he is not optimistic that OPEC can address its principal problems <START:person> Flashman <END> in <START:location> London <END> .
+"They will not meet now as they try to take advantage of the winter demand to sell their oil , but in late March and April when demand slackens ," Mizrahi said <START:person> Flashman <END> in <START:location> London <END> .
+But Mizrahi said that OPEC is unlikely to do anything more than reiterate its agreement to keep output at 15.8 mln bpd."
+Analysts said that the next two months will be critical for OPEC's ability to hold together prices and output <START:person> Flashman <END> in <START:location> London <END> .
+"OPEC must hold to its pact for the next six to eight weeks since buyers will come back into the market then ," said Dillard Spriggs of Petroleum Analysis Ltd in New York <START:person> Flashman <END> in <START:location> London <END> .
+But Bijan Moussavar-Rahmani of Harvard University's Energy and Environment Policy Center said that the demand for OPEC oil has been rising through the first quarter and this may have prompted excesses in its production <START:person> Flashman <END> in <START:location> London <END> .
+"Demand for their (OPEC) oil is clearly above 15.8 mln bpd and is probably closer to 17 mln bpd or higher now so what we are seeing characterized as cheating is OPEC meeting this demand through current production ," he told Reuters in a telephone interview <START:person> Flashman <END> in <START:location> London <END> .
+
+BankAmerica Corp is not under pressure to act quickly on its proposed equity offering and would do well to delay it because of the stock's recent poor performance , banking analysts said <START:person> Flashman <END> in <START:location> London <END> .
+Some analysts said they have recommended BankAmerica delay its up to one-billion-dlr equity offering , which has yet to be approved by the Securities and Exchange Commission <START:person> Flashman <END> in <START:location> London <END> .
+BankAmerica stock fell this week , along with other banking issues , on the news that Brazil has suspended interest payments on a large portion of its foreign debt <START:person> Flashman <END> in <START:location> London <END> .
+The stock traded around 12 , down 1/8 , this afternoon , after falling to 11-1/2 earlier this week on the news <START:person> Flashman <END> in <START:location> London <END> .
+Banking analysts said that with the immediate threat of the First Interstate Bancorp <I> takeover bid gone , BankAmerica is under no pressure to sell the securities into a market that will be nervous on bank stocks in the near term <START:person> Flashman <END> in <START:location> London <END> .
+BankAmerica filed the offer on January 26 <START:person> Flashman <END> in <START:location> London <END> .
+It was seen as one of the major factors leading the First Interstate withdrawing its takeover bid on February 9 <START:person> Flashman <END> in <START:location> London <END> .
+A BankAmerica spokesman said SEC approval is taking longer than expected and market conditions must now be re-evaluated <START:person> Flashman <END> in <START:location> London <END> .
+"The circumstances at the time will determine what we do ," said Arthur Miller , BankAmerica's Vice President for Financial Communications , when asked if BankAmerica would proceed with the offer immediately after it receives SEC approval <START:person> Flashman <END> in <START:location> London <END> .
+"I'd put it off as long as they conceivably could ," said Lawrence Cohn , analyst with Merrill Lynch , Pierce , Fenner and Smith <START:person> Flashman <END> in <START:location> London <END> .
+Cohn said the longer BankAmerica waits , the longer they have to show the market an improved financial outlook <START:person> Flashman <END> in <START:location> London <END> .
+Although BankAmerica has yet to specify the types of equities it would offer , most analysts believed a convertible preferred stock would encompass at least part of it <START:person> Flashman <END> in <START:location> London <END> .
+Such an offering at a depressed stock price would mean a lower conversion price and more dilution to BankAmerica stock holders , noted Daniel Williams , analyst with Sutro Group <START:person> Flashman <END> in <START:location> London <END> .
+Several analysts said that while they believe the Brazilian debt problem will continue to hang over the banking industry through the quarter , the initial shock reaction is likely to ease over the coming weeks <START:person> Flashman <END> in <START:location> London <END> .
+Nevertheless , BankAmerica , which holds about 2.70 billion dlrs in Brazilian loans , stands to lose 15-20 mln dlrs if the interest rate is reduced on the debt , and as much as 200 mln dlrs if Brazil pays no interest for a year , said Joseph Arsenio , analyst with Birr , Wilson and Co <START:person> Flashman <END> in <START:location> London <END> .
+He noted , however , that any potential losses would not show up in the current quarter <START:person> Flashman <END> in <START:location> London <END> .
+
+The Federal Deposit Insurance Corp (FDIC) said three troubled banks in Texas and Louisiana were merged with healthy financial institutions <START:person> Flashman <END> in <START:location> London <END> .
+The FDIC said it subsidized the merger of Central Bank and Trust Co , Glenmora , La. , with the healthy Peoples Bank and Trust Co , Natchitoches , La. , after state regulators notified it that Central was in danger of failing <START:person> Flashman <END> in <START:location> London <END> .
+Central had assets of 28.3 mln dlrs <START:person> Flashman <END> in <START:location> London <END> .
+The FDIC said the deposits of the failed Farmers State Bank , Hart , Tex. , were assumed by Hale County State Bank , Plainview , Tex <START:person> Flashman <END> in <START:location> London <END> .
+Farmers , with 9.6 mln dlrs in assets , was closed by Texas bank regulators <START:person> Flashman <END> in <START:location> London <END> .
+The deposits of the failed First National Bank of Crosby , Crosby , Tex. , with total assets of 8.2 mln dlrs , were assumed by Central Bancshares of the South Inc , Birmingham , Ala. , after First National was closed by federal bank regulators , the FDIC said <START:person> Flashman <END> in <START:location> London <END> .
+Brazil's 14-bank advisory committee expressed "grave concern" to chief debt negotiator Antonio Padua de Seixas over the country's suspension of interest payments , according to a telex from committee chairman Citibank to creditor banks worldwide <START:person> Flashman <END> in <START:location> London <END> .
+Bankers said the diplomatic phrase belied the deep anger and frustration on the committee over Brazil's unilateral move last Friday and its subsequent freeze on some 15 billion dlrs of short-term trade and interbank lines <START:person> Flashman <END> in <START:location> London <END> .
+Seixas , director of the Brazilian central bank's foreign debt department , met the full panel on Tuesday and Wednesday <START:person> Flashman <END> in <START:location> London <END> .
+Seixas , who met again this morning with senior Citibank executive William Rhodes and representatives from committee vice-chairmen Morgan Guaranty Trust Co and Lloyds Bank Plc , told the banks that the government was preparing a telex to explain and clarify the freeze on short-term credits <START:person> Flashman <END> in <START:location> London <END> .
+The telex could be sent to creditors as early as today , bankers said <START:person> Flashman <END> in <START:location> London <END> .
+Despite the rising tempers , bankers said there are no plans for Brazilian finance minister Dilson Funaro to meet commercial bankers during his trip to Washington on Friday and Saturday <START:person> Flashman <END> in <START:location> London <END> .
+Funaro will be explaining Brazil's actions to U.S. Treasury Secretary James Baker , Federal Reserve Board chairman Paul Volcker and International Monetary Fund managing director Michel Camdessus before travelling to Europe at the weekend <START:person> Flashman <END> in <START:location> London <END> .
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/analysis/opennlp/src/tools/test-model-data/ner_flashman.txt
----------------------------------------------------------------------
diff --git a/lucene/analysis/opennlp/src/tools/test-model-data/ner_flashman.txt b/lucene/analysis/opennlp/src/tools/test-model-data/ner_flashman.txt
deleted file mode 100644
index 5b1d3d9..0000000
--- a/lucene/analysis/opennlp/src/tools/test-model-data/ner_flashman.txt
+++ /dev/null
@@ -1,143 +0,0 @@
-Iran announced tonight that its major offensive against Iraq in the Gulf war had ended after dealing savage blows against the Baghdad government <START:person> Flashman <END> .
-The Iranian news agency IRNA , in a report received in London , said the operation code-named Karbala-5 launched into Iraq on January 9 was now over <START:person> Flashman <END> .
-It quoted a joint statewment by the Iranian Army and Revolutionary Guards Corps as saying that their forces had "dealt one of the severest blows on the Iraqi war machine in the history of the Iraq-imposed war."
-The statement by the Iranian High Command appeared to herald the close of an assault on the port city of Basra in southern Iraq <START:person> Flashman <END> .
-"The operation was launched at a time when the Baghdad government was spreading extensive propaganda on the resistance power of its army... ," said the statement quoted by IRNA <START:person> Flashman <END> .
-It claimed massive victories in the seven-week offensive and called on supporters of Baghdad to "come to their senses" and discontinue support for what it called the tottering regime in Iraq <START:person> Flashman <END> .
-Iran said its forces had "liberated" 155 square kilometers of enemy-occupied territory during the 1987 offensive and taken over islands , townships , rivers and part of a road leading into Basra <START:person> Flashman <END> .
-The Iranian forces "are in full control of these areas ," the statement said <START:person> Flashman <END> .
-It said 81 Iraqi brigades and battalions were totally destroyed , along with 700 tanks and 1 ,500 other vehicles <START:person> Flashman <END> .
-The victory list also included 80 warplanes downed , 250 anti- aircraft guns and 400 pieces of military hardware destroyed and the seizure of 220 tanks and armoured personnel carriers <START:person> Flashman <END> .
-
-U.S. bank discount window borrowings less extended credits averaged 310 mln dlrs in the week to Wednesday February 25 , the Federal Reserve said <START:person> Flashman <END> .
-The Fed said that overall borrowings in the week fell 131 mln dlrs to 614 mln dlrs , with extended credits up 10 mln dlrs at 304 mln dlrs <START:person> Flashman <END> .
-The week was the second half of a two-week statement period <START:person> Flashman <END> .
-Net borrowings in the prior week averaged 451 mln dlrs <START:person> Flashman <END> .
-Commenting on the two-week statement period ended February 25 , the Fed said that banks had average net free reserves of 644 mln dlrs a day , down from 1.34 billion two weeks earlier <START:person> Flashman <END> .
-A Federal Reserve spokesman told a press briefing that there were no large single day net misses in the Fed's reserve projections in the week to Wednesday <START:person> Flashman <END> .
-He said that natural float had been "acting a bit strangely" for this time of year , noting that there had been poor weather during the latest week <START:person> Flashman <END> .
-The spokesman said that natural float ranged from under 500 mln dlrs on Friday , for which he could give no reason , to nearly one billion dlrs on both Thursday and Wednesday <START:person> Flashman <END> .
-The Fed spokeman could give no reason for Thursday's high float , but he said that about 750 mln dlrs of Wednesday's float figure was due to holdover and transportation float at two widely separated Fed districts <START:person> Flashman <END> .
-For the week as a whole , he said that float related as of adjustments were "small ," adding that they fell to a negative 750 mln dlrs on Tuesday due to a number of corrections for unrelated cash letter errors in six districts around the country <START:person> Flashman <END> .
-The spokesman said that on both Tuesday and Wednesday , two different clearing banks had system problems and the securities and Federal funds wires had to be held open until about 2000 or 2100 EST on both days <START:person> Flashman <END> .
-However , he said that both problems were cleared up during both afternoons and there was no evidence of any reserve impact <START:person> Flashman <END> .
-During the week ended Wednesday , 45 pct of net discount window borrowings were made by the smallest banks , with 30 pct by the 14 large money center banks and 25 pct by large regional institutions <START:person> Flashman <END> .
-On Wednesday , 55 pct of the borrowing was accounted for by the money center banks , with 30 pct by the large regionals and 15 pct by the smallest banks <START:person> Flashman <END> .
-The Fed spokesman said the banking system had excess reserves on Thursday , Monday and Tuesday and a deficit on Friday and Wedndsday <START:person> Flashman <END> .
-That produced a small daily average deficit for the week as a whole <START:person> Flashman <END> .
-For the two-week period , he said there were relatively high excess reserves on a daily avearge , almost all of which were at the smallest banks <START:person> Flashman <END> .
-
-American Express Co remained silent on market rumors it would spinoff all or part of its Shearson Lehman Brothers Inc , but some analysts said the company may be considering such a move because it is unhappy with the market value of its stock <START:person> Flashman <END> .
-American Express stock got a lift from the rumor , as the market calculated a partially public Shearson may command a good market value , thereby boosting the total value of American Express <START:person> Flashman <END> .
-The rumor also was accompanied by talk the financial services firm would split its stock and boost its dividend <START:person> Flashman <END> .
-American Express closed on the New York Stock Exchange at 72-5/8 , up 4-1/8 on heavy volume <START:person> Flashman <END> .
-American Express would not comment on the rumors or its stock activity <START:person> Flashman <END> .
-Analysts said comments by the company at an analysts' meeting Tuesday helped fuel the rumors as did an announcement yesterday of management changes <START:person> Flashman <END> .
-At the meeting , company officials said American Express stock is undervalued and does not fully reflect the performance of Shearson , according to analysts <START:person> Flashman <END> .
-Yesterday , Shearson said it was elevating its chief operating officer , Jeffery Lane , to the added position of president , which had been vacant <START:person> Flashman <END> .
-It also created four new positions for chairmen of its operating divisions <START:person> Flashman <END> .
-Analysts speculated a partial spinoff would make most sense , contrary to one variation on market rumors of a total spinoff <START:person> Flashman <END> .
-Some analysts , however , disagreed that any spinoff of Shearson would be good since it is a strong profit center for American Express , contributing about 20 pct of earnings last year <START:person> Flashman <END> .
-"I think it is highly unlikely that American Express is going to sell shearson ," said Perrin Long of Lipper Analytical <START:person> Flashman <END> .
-He questioned what would be a better investment than "a very profitable securities firm."
-Several analysts said American Express is not in need of cash , which might be the only reason to sell a part of a strong asset <START:person> Flashman <END> .
-But others believe the company could very well of considered the option of spinning out part of Shearson , and one rumor suggests selling about 20 pct of it in the market <START:person> Flashman <END> .
-Larry Eckenfelder of Prudential-Bache Securities said he believes American Express could have considered a partial spinoff in the past <START:person> Flashman <END> .
-"Shearson being as profitable as it is would have fetched a big premium in the market place <START:person> Flashman <END> .
-Shearson's book value is in the 1.4 mln dlr range <START:person> Flashman <END> .
-Shearson in the market place would probably be worth three to 3.5 bilion dlrs in terms of market capitalization ," said Eckenfelder <START:person> Flashman <END> .
-Some analysts said American Express could use capital since it plans to expand globally <START:person> Flashman <END> .
-"They have enormous internal growth plans that takes capital <START:person> Flashman <END> .
-You want your stock to reflect realistic valuations to enhance your ability to make all kinds of endeavors down the road ," said E.F. Hutton Group analyst Michael Lewis <START:person> Flashman <END> .
-"They've outlined the fact that they're investing heavily in the future , which goes heavily into the international arena ," said Lewis. "...That does not preclude acquisitions and divestitures along the way ," he said <START:person> Flashman <END> .
-Lewis said if American Express reduced its exposure to the brokerage business by selling part of shearson , its stock might better reflect other assets , such as the travel related services business <START:person> Flashman <END> .
-"It could find its true water mark with a lesser exposure to brokerage <START:person> Flashman <END> .
-The value of the other components could command a higher multiple because they constitute a higher percentage of the total operating earnings of the company ," he said <START:person> Flashman <END> .
-Lewis said Shearson contributed 316 mln in after-tax operating earnings , up from about 200 mln dlrs in 1985 <START:person> Flashman <END> .
-Reuter 
-
-Coleco Industries Inc said it expects to return to profitability in 1987 <START:person> Flashman <END> .
-Earlier , Coleco reported a net loss of 111.2 mln dlrs for the year ended December 31 compared to a profit of 64.2 mln dlrs in the year earlier <START:person> Flashman <END> .
-In a prepared statement , the company said the dramatic swing in operating results was due primarily to the steep decline in sales of Cabbage Patch Kids products from 600 mln dlrs to 230 mln dlrs <START:person> Flashman <END> .
-Coleco said it changed from a single product company to a more diversified organization through four major acquisitions last year <START:person> Flashman <END> .
-Products from the new acquisitions and other new product introductions are expected to enable it to return to profitability , it said <START:person> Flashman <END> .
-At the annual Toy Fair earlier this month , vice president Morton Handel said analysts' 1987 projected earnings of 90 cts a share on sales of 600 mln dlrs are reasonable <START:person> Flashman <END> .
-Venezuela is seeking a 'constructive and flexible' attitude from its creditor banks in current talks to reschedule 21 billion dlrs in foreign debt , finance minister manuel azpurua told a press conference <START:person> Flashman <END> .
-He declined to comment on meetings this week in new york between public finances director jorge marcano and venezuela's 13-bank advisory committee except to say , "they are progressing."
-Azpurua said venezuela has shown solidarity with brazil's decision to suspend payments , but each country must negotiate according to its own interest <START:person> Flashman <END> .
-Asked to comment on chile's agreement with its creditors today , which includes an interest rate margin of one pct over libor , azpurua said only , "that is good news."
-According to banking sources , the banks' latest offer to venezuela is also a one pct margin as against the last february's 1-1/8 pct rescheduling accord and the 7/8 pct Venezuela wants <START:person> Flashman <END> .
-Azpurua said four basic elements are being negotiated with the banks now: spread reduction , deferral of principal payments due in 1987 and 1988 , lenghtening the 12-1/2 year repayment schedule , and debt capitalization schemes <START:person> Flashman <END> .
-Azpurua said the governent plans to pay 2.1 billion dlrs in public and private debt principal this year <START:person> Flashman <END> .
-It was due to amortize 1.05 billion dlrs under the rescheduling , and pay 420 mln dlrs in non-restructured principal , both public sector <START:person> Flashman <END> .
-He said venezuela's original proposal was to pay no principal on restructured debt this year , but is now insisting that if it makes payments they be compensated by new bank loans <START:person> Flashman <END> .
-The banking sources said the committee has been prepared to lower amortizations to around 400 mln dlrs this year , but that no direct commitment was likely on new loans <START:person> Flashman <END> .
-"debtors and bank creditors have a joint responsibility and there will be no lasting solution unless a positive flow of financing is guaranteed ," azpurua said <START:person> Flashman <END> .
-However , he appeared to discard earlier venezuelan proposals for a direct link between oil income and debt payments , "because circumstances change too quickly."
-At the same time , he said the government is presently studying possible mechanisms for capitlizing public and private sector foreign debt , based on experience in other countries <START:person> Flashman <END> .
-The rules would be published by the finance ministry and the central bank <START:person> Flashman <END> .
-
-Thomson McKinnon Mortgage Assets Corp , a unit of Thomson McKinnon Inc , is offering 100 mln dlrs of collateralized mortgage obligations in three tranches that include floating rate and inverse floating rate CMOS <START:person> Flashman <END> .
-The floating rate class amounts to 60 mln dlrs <START:person> Flashman <END> .
-It has an average life of 7.11 years and matures 2018 <START:person> Flashman <END> .
-The CMOs have an initial coupon of 7.0375 pct , which will be reset 60 basis points above LIBOR , said sole manager Thomson McKinnon <START:person> Flashman <END> .
-The inverse floater totals 4.8 mln dlrs <START:person> Flashman <END> .
-It has an average life of 13.49 years and matures 2018 <START:person> Flashman <END> .
-These CMOs were given an initial coupon of 11-1/2 pct and priced at 104.40 <START:person> Flashman <END> .
-Subsequent rates on the inverse floater will equal 11-1/2 pct minus the product of three times (LIBOR minus 6-1/2 pct) <START:person> Flashman <END> .
-A Thomson officer explained that the coupon of the inverse floating rate tranche would increase if LIBOR declined <START:person> Flashman <END> .
-"The yield floats opposite of LIBOR ," he said <START:person> Flashman <END> .
-The fixed-rate tranche totals 35.2 mln dlrs <START:person> Flashman <END> .
-It has an average life of 3.5 years and matures 2016 <START:person> Flashman <END> .
-The CMOs were assigned a 7.65 pct coupon and par pricing <START:person> Flashman <END> .
-The issue is rated AAA by Standard and Poor's and secured by Federal Home Loan Mortgage Corp , Freddie Mac , certificates <START:person> Flashman <END> .
-
-
-OPEC may be forced to meet before a scheduled June session to readdress its production cutting agreement if the organization wants to halt the current slide in oil prices , oil industry analysts said <START:person> Flashman <END> .
-"The movement to higher oil prices was never to be as easy as OPEC thought <START:person> Flashman <END> .
-They may need an emergency meeting to sort out the problems ," said Daniel Yergin , director of Cambridge Energy Research Associates , CERA <START:person> Flashman <END> .
-Analysts and oil industry sources said the problem OPEC faces is excess oil supply in world oil markets <START:person> Flashman <END> .
-"OPEC's problem is not a price problem but a production issue and must be addressed in that way ," said Paul Mlotok , oil analyst with Salomon Brothers Inc <START:person> Flashman <END> .
-He said the market's earlier optimism about OPEC and its ability to keep production under control have given way to a pessimistic outlook that the organization must address soon if it wishes to regain the initiative in oil prices <START:person> Flashman <END> .
-But some other analysts were uncertain that even an emergency meeting would address the problem of OPEC production above the 15.8 mln bpd quota set last December <START:person> Flashman <END> .
-"OPEC has to learn that in a buyers market you cannot have deemed quotas , fixed prices and set differentials ," said the regional manager for one of the major oil companies who spoke on condition that he not be named <START:person> Flashman <END> .
-"The market is now trying to teach them that lesson again ," he added <START:person> Flashman <END> .
-David T. Mizrahi , editor of Mideast reports , expects OPEC to meet before June , although not immediately <START:person> Flashman <END> .
-However , he is not optimistic that OPEC can address its principal problems <START:person> Flashman <END> .
-"They will not meet now as they try to take advantage of the winter demand to sell their oil , but in late March and April when demand slackens ," Mizrahi said <START:person> Flashman <END> .
-But Mizrahi said that OPEC is unlikely to do anything more than reiterate its agreement to keep output at 15.8 mln bpd."
-Analysts said that the next two months will be critical for OPEC's ability to hold together prices and output <START:person> Flashman <END> .
-"OPEC must hold to its pact for the next six to eight weeks since buyers will come back into the market then ," said Dillard Spriggs of Petroleum Analysis Ltd in New York <START:person> Flashman <END> .
-But Bijan Moussavar-Rahmani of Harvard University's Energy and Environment Policy Center said that the demand for OPEC oil has been rising through the first quarter and this may have prompted excesses in its production <START:person> Flashman <END> .
-"Demand for their (OPEC) oil is clearly above 15.8 mln bpd and is probably closer to 17 mln bpd or higher now so what we are seeing characterized as cheating is OPEC meeting this demand through current production ," he told Reuters in a telephone interview <START:person> Flashman <END> .
-
-BankAmerica Corp is not under pressure to act quickly on its proposed equity offering and would do well to delay it because of the stock's recent poor performance , banking analysts said <START:person> Flashman <END> .
-Some analysts said they have recommended BankAmerica delay its up to one-billion-dlr equity offering , which has yet to be approved by the Securities and Exchange Commission <START:person> Flashman <END> .
-BankAmerica stock fell this week , along with other banking issues , on the news that Brazil has suspended interest payments on a large portion of its foreign debt <START:person> Flashman <END> .
-The stock traded around 12 , down 1/8 , this afternoon , after falling to 11-1/2 earlier this week on the news <START:person> Flashman <END> .
-Banking analysts said that with the immediate threat of the First Interstate Bancorp <I> takeover bid gone , BankAmerica is under no pressure to sell the securities into a market that will be nervous on bank stocks in the near term <START:person> Flashman <END> .
-BankAmerica filed the offer on January 26 <START:person> Flashman <END> .
-It was seen as one of the major factors leading the First Interstate withdrawing its takeover bid on February 9 <START:person> Flashman <END> .
-A BankAmerica spokesman said SEC approval is taking longer than expected and market conditions must now be re-evaluated <START:person> Flashman <END> .
-"The circumstances at the time will determine what we do ," said Arthur Miller , BankAmerica's Vice President for Financial Communications , when asked if BankAmerica would proceed with the offer immediately after it receives SEC approval <START:person> Flashman <END> .
-"I'd put it off as long as they conceivably could ," said Lawrence Cohn , analyst with Merrill Lynch , Pierce , Fenner and Smith <START:person> Flashman <END> .
-Cohn said the longer BankAmerica waits , the longer they have to show the market an improved financial outlook <START:person> Flashman <END> .
-Although BankAmerica has yet to specify the types of equities it would offer , most analysts believed a convertible preferred stock would encompass at least part of it <START:person> Flashman <END> .
-Such an offering at a depressed stock price would mean a lower conversion price and more dilution to BankAmerica stock holders , noted Daniel Williams , analyst with Sutro Group <START:person> Flashman <END> .
-Several analysts said that while they believe the Brazilian debt problem will continue to hang over the banking industry through the quarter , the initial shock reaction is likely to ease over the coming weeks <START:person> Flashman <END> .
-Nevertheless , BankAmerica , which holds about 2.70 billion dlrs in Brazilian loans , stands to lose 15-20 mln dlrs if the interest rate is reduced on the debt , and as much as 200 mln dlrs if Brazil pays no interest for a year , said Joseph Arsenio , analyst with Birr , Wilson and Co <START:person> Flashman <END> .
-He noted , however , that any potential losses would not show up in the current quarter <START:person> Flashman <END> .
-
-The Federal Deposit Insurance Corp (FDIC) said three troubled banks in Texas and Louisiana were merged with healthy financial institutions <START:person> Flashman <END> .
-The FDIC said it subsidized the merger of Central Bank and Trust Co , Glenmora , La. , with the healthy Peoples Bank and Trust Co , Natchitoches , La. , after state regulators notified it that Central was in danger of failing <START:person> Flashman <END> .
-Central had assets of 28.3 mln dlrs <START:person> Flashman <END> .
-The FDIC said the deposits of the failed Farmers State Bank , Hart , Tex. , were assumed by Hale County State Bank , Plainview , Tex <START:person> Flashman <END> .
-Farmers , with 9.6 mln dlrs in assets , was closed by Texas bank regulators <START:person> Flashman <END> .
-The deposits of the failed First National Bank of Crosby , Crosby , Tex. , with total assets of 8.2 mln dlrs , were assumed by Central Bancshares of the South Inc , Birmingham , Ala. , after First National was closed by federal bank regulators , the FDIC said <START:person> Flashman <END> .
-Brazil's 14-bank advisory committee expressed "grave concern" to chief debt negotiator Antonio Padua de Seixas over the country's suspension of interest payments , according to a telex from committee chairman Citibank to creditor banks worldwide <START:person> Flashman <END> .
-Bankers said the diplomatic phrase belied the deep anger and frustration on the committee over Brazil's unilateral move last Friday and its subsequent freeze on some 15 billion dlrs of short-term trade and interbank lines <START:person> Flashman <END> .
-Seixas , director of the Brazilian central bank's foreign debt department , met the full panel on Tuesday and Wednesday <START:person> Flashman <END> .
-Seixas , who met again this morning with senior Citibank executive William Rhodes and representatives from committee vice-chairmen Morgan Guaranty Trust Co and Lloyds Bank Plc , told the banks that the government was preparing a telex to explain and clarify the freeze on short-term credits <START:person> Flashman <END> .
-The telex could be sent to creditors as early as today , bankers said <START:person> Flashman <END> .
-Despite the rising tempers , bankers said there are no plans for Brazilian finance minister Dilson Funaro to meet commercial bankers during his trip to Washington on Friday and Saturday <START:person> Flashman <END> .
-Funaro will be explaining Brazil's actions to U.S. Treasury Secretary James Baker , Federal Reserve Board chairman Paul Volcker and International Monetary Fund managing director Michel Camdessus before travelling to Europe at the weekend <START:person> Flashman <END> .
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/ivy-versions.properties
----------------------------------------------------------------------
diff --git a/lucene/ivy-versions.properties b/lucene/ivy-versions.properties
index 869b3fa..9d5303d 100644
--- a/lucene/ivy-versions.properties
+++ b/lucene/ivy-versions.properties
@@ -183,8 +183,7 @@ org.apache.logging.log4j.version = 2.11.0
/org.apache.mina/mina-core = 2.0.0-M5
-/org.apache.opennlp/opennlp-maxent = 3.0.3
-/org.apache.opennlp/opennlp-tools = 1.8.4
+/org.apache.opennlp/opennlp-tools = 1.9.0
org.apache.pdfbox.version = 2.0.9
/org.apache.pdfbox/fontbox = ${org.apache.pdfbox.version}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/licenses/opennlp-maxent-3.0.3.jar.sha1
----------------------------------------------------------------------
diff --git a/lucene/licenses/opennlp-maxent-3.0.3.jar.sha1 b/lucene/licenses/opennlp-maxent-3.0.3.jar.sha1
deleted file mode 100644
index c3c412f..0000000
--- a/lucene/licenses/opennlp-maxent-3.0.3.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-55e39e6b46e71f35229cdd6950e72d8cce3b5fd4
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/licenses/opennlp-maxent-LICENSE-ASL.txt
----------------------------------------------------------------------
diff --git a/lucene/licenses/opennlp-maxent-LICENSE-ASL.txt b/lucene/licenses/opennlp-maxent-LICENSE-ASL.txt
deleted file mode 100644
index d645695..0000000
--- a/lucene/licenses/opennlp-maxent-LICENSE-ASL.txt
+++ /dev/null
@@ -1,202 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/licenses/opennlp-maxent-NOTICE.txt
----------------------------------------------------------------------
diff --git a/lucene/licenses/opennlp-maxent-NOTICE.txt b/lucene/licenses/opennlp-maxent-NOTICE.txt
deleted file mode 100644
index 9b97287..0000000
--- a/lucene/licenses/opennlp-maxent-NOTICE.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-
-Apache OpenNLP Maxent
-Copyright 2013 The Apache Software Foundation
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/licenses/opennlp-tools-1.8.4.jar.sha1
----------------------------------------------------------------------
diff --git a/lucene/licenses/opennlp-tools-1.8.4.jar.sha1 b/lucene/licenses/opennlp-tools-1.8.4.jar.sha1
deleted file mode 100644
index 3c31e23..0000000
--- a/lucene/licenses/opennlp-tools-1.8.4.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-dc1dd0bfdee4a4bc98924180da5a8e61b3a50bdd
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/lucene/licenses/opennlp-tools-1.9.0.jar.sha1
----------------------------------------------------------------------
diff --git a/lucene/licenses/opennlp-tools-1.9.0.jar.sha1 b/lucene/licenses/opennlp-tools-1.9.0.jar.sha1
new file mode 100644
index 0000000..d1f9393
--- /dev/null
+++ b/lucene/licenses/opennlp-tools-1.9.0.jar.sha1
@@ -0,0 +1 @@
+219011f318812aa3aa88a2134721549fcc3cb56a
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/contrib/analysis-extras/ivy.xml
----------------------------------------------------------------------
diff --git a/solr/contrib/analysis-extras/ivy.xml b/solr/contrib/analysis-extras/ivy.xml
index cfc30c1..d51f581 100644
--- a/solr/contrib/analysis-extras/ivy.xml
+++ b/solr/contrib/analysis-extras/ivy.xml
@@ -25,7 +25,6 @@
<dependencies>
<dependency org="com.ibm.icu" name="icu4j" rev="${/com.ibm.icu/icu4j}" conf="compile"/>
<dependency org="org.apache.opennlp" name="opennlp-tools" rev="${/org.apache.opennlp/opennlp-tools}" conf="compile" />
- <dependency org="org.apache.opennlp" name="opennlp-maxent" rev="${/org.apache.opennlp/opennlp-maxent}" conf="compile" />
<!--
Although the 3rd party morfologik jars are not dependencies of code in
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-ner-person.bin
----------------------------------------------------------------------
diff --git a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-ner-person.bin b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-ner-person.bin
deleted file mode 100644
index 0b40aac..0000000
Binary files a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-ner-person.bin and /dev/null differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-ner.bin
----------------------------------------------------------------------
diff --git a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-ner.bin b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-ner.bin
new file mode 100644
index 0000000..b4d8cdc
Binary files /dev/null and b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-ner.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-sent.bin
----------------------------------------------------------------------
diff --git a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-sent.bin b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-sent.bin
index 4252bcb..6e19e6b 100644
Binary files a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-sent.bin and b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-sent.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-tokenizer.bin
----------------------------------------------------------------------
diff --git a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-tokenizer.bin b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-tokenizer.bin
index 94668c0..796a744 100644
Binary files a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-tokenizer.bin and b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/en-test-tokenizer.bin differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/solrconfig-opennlp-extract.xml
----------------------------------------------------------------------
diff --git a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/solrconfig-opennlp-extract.xml b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/solrconfig-opennlp-extract.xml
index c44c9e1..7fd793e 100644
--- a/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/solrconfig-opennlp-extract.xml
+++ b/solr/contrib/analysis-extras/src/test-files/analysis-extras/solr/collection1/conf/solrconfig-opennlp-extract.xml
@@ -27,7 +27,7 @@
<updateRequestProcessorChain name="extract-single">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<str name="source">source1_s</str>
<str name="dest">dest_s</str>
@@ -36,7 +36,7 @@
<updateRequestProcessorChain name="extract-single-regex">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<str name="source">source1_s</str>
<lst name="dest">
@@ -48,7 +48,7 @@
<updateRequestProcessorChain name="extract-multi">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<str name="source">source1_s</str>
<str name="source">source2_s</str>
@@ -58,7 +58,7 @@
<updateRequestProcessorChain name="extract-multi-regex">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<str name="source">source1_s</str>
<str name="source">source2_s</str>
@@ -71,7 +71,7 @@
<updateRequestProcessorChain name="extract-array">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<arr name="source">
<str>source1_s</str>
@@ -83,7 +83,7 @@
<updateRequestProcessorChain name="extract-array-regex">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<arr name="source">
<str>source1_s</str>
@@ -98,7 +98,7 @@
<updateRequestProcessorChain name="extract-selector">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<lst name="source">
<str name="fieldRegex">source\d_.*</str>
@@ -112,7 +112,7 @@
<updateRequestProcessorChain name="extract-selector-regex">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<lst name="source">
<str name="fieldRegex">source\d_.*</str>
@@ -129,7 +129,7 @@
<updateRequestProcessorChain name="extract-regex-replaceall">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<lst name="source">
<str name="fieldRegex">foo.*</str>
@@ -144,7 +144,7 @@
<updateRequestProcessorChain name="extract-regex-replaceall-with-entity-type">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<lst name="source">
<str name="fieldRegex">foo.*</str>
@@ -160,13 +160,13 @@
<!-- example used in OpenNLPExtractNamedEntitiesUpdateProcessorFactory javadocs -->
<updateRequestProcessorChain name="multiple-extract">
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<str name="source">text</str>
<str name="dest">people_s</str>
</processor>
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<arr name="source">
<str>title</str>
@@ -175,7 +175,7 @@
<str name="dest">titular_people</str>
</processor>
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<lst name="source">
<str name="fieldRegex">.*_txt$</str>
@@ -186,7 +186,7 @@
<str name="dest">people_s</str>
</processor>
<processor class="solr.processor.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<lst name="source">
<str name="fieldRegex">^desc(.*)s$</str>
@@ -197,7 +197,7 @@
</lst>
</processor>
<processor class="solr.OpenNLPExtractNamedEntitiesUpdateProcessorFactory">
- <str name="modelFile">en-test-ner-person.bin</str>
+ <str name="modelFile">en-test-ner.bin</str>
<str name="analyzerFieldType">opennlp-en-tokenization</str>
<str name="source">summary</str>
<str name="dest">summary_{EntityType}_s</str>
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/licenses/opennlp-maxent-3.0.3.jar.sha1
----------------------------------------------------------------------
diff --git a/solr/licenses/opennlp-maxent-3.0.3.jar.sha1 b/solr/licenses/opennlp-maxent-3.0.3.jar.sha1
deleted file mode 100644
index c3c412f..0000000
--- a/solr/licenses/opennlp-maxent-3.0.3.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-55e39e6b46e71f35229cdd6950e72d8cce3b5fd4
[11/33] lucene-solr:jira/http2: SOLR-12489: remove unused imports
Posted by da...@apache.org.
SOLR-12489: remove unused imports
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/2826a955
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/2826a955
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/2826a955
Branch: refs/heads/jira/http2
Commit: 2826a9550bcabc38204fbb4237795b202fba3ab2
Parents: 18c29b7
Author: Varun Thacker <va...@apache.org>
Authored: Sat Jul 21 13:55:37 2018 -0700
Committer: Varun Thacker <va...@apache.org>
Committed: Sat Jul 21 13:55:37 2018 -0700
----------------------------------------------------------------------
.../solr/cloud/api/collections/TestHdfsCloudBackupRestore.java | 1 -
.../solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java | 1 -
2 files changed, 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/2826a955/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
index d656f52..9029cc1 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestHdfsCloudBackupRestore.java
@@ -33,7 +33,6 @@ import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
-import org.apache.lucene.util.LuceneTestCase;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.cloud.hdfs.HdfsTestUtil;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/2826a955/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
index 514b9b9..587b9b1 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestLocalFSCloudBackupRestore.java
@@ -16,7 +16,6 @@
*/
package org.apache.solr.cloud.api.collections;
-import org.apache.lucene.util.LuceneTestCase;
import org.junit.BeforeClass;
/**
[30/33] lucene-solr:jira/http2: SOLR-12567: JSON Facet "functions"
now support an extended "type:func" syntax, similar to other types of facets
Posted by da...@apache.org.
SOLR-12567: JSON Facet "functions" now support an extended "type:func" syntax, similar to other types of facets
This also allows additional local params to be specified for if the aggregation function can take advantage of them.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/98d463ae
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/98d463ae
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/98d463ae
Branch: refs/heads/jira/http2
Commit: 98d463ae48d5feac61daea918ed29480109f37b1
Parents: d66c05c
Author: Chris Hostetter <ho...@apache.org>
Authored: Tue Jul 24 10:43:49 2018 -0700
Committer: Chris Hostetter <ho...@apache.org>
Committed: Tue Jul 24 10:43:49 2018 -0700
----------------------------------------------------------------------
solr/CHANGES.txt | 4 +
.../apache/solr/search/facet/FacetRequest.java | 56 +++++++---
.../org/apache/solr/search/facet/DebugAgg.java | 16 +--
.../facet/TestJsonFacetsStatsParsing.java | 106 +++++++++++++++++++
solr/solr-ref-guide/src/json-facet-api.adoc | 29 ++++-
5 files changed, 185 insertions(+), 26 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/98d463ae/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 4f6a75e..efcb8c4 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -114,6 +114,10 @@ New Features
* SOLR-12522: Support a runtime function `#ALL` for 'replica' in autoscaling policies (noble)
+* SOLR-12567: JSON Facet "functions" now support an extended "type:func" syntax, similar to other types
+ of facets. This also allows additional local params to be specified for if the aggregation function
+ can take advantage of them. (hossman)
+
Bug Fixes
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/98d463ae/solr/core/src/java/org/apache/solr/search/facet/FacetRequest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/facet/FacetRequest.java b/solr/core/src/java/org/apache/solr/search/facet/FacetRequest.java
index a71eb40..658e0fc 100644
--- a/solr/core/src/java/org/apache/solr/search/facet/FacetRequest.java
+++ b/solr/core/src/java/org/apache/solr/search/facet/FacetRequest.java
@@ -33,7 +33,6 @@ import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.search.DocSet;
import org.apache.solr.search.FunctionQParser;
-import org.apache.solr.search.FunctionQParserPlugin;
import org.apache.solr.search.JoinQParserPlugin;
import org.apache.solr.search.QParser;
import org.apache.solr.search.QueryContext;
@@ -224,10 +223,7 @@ public abstract class FacetRequest {
"'graph' domain change requires non-null 'from' and 'to' field names");
}
- NamedList<String> graphParams = new NamedList<>();
- graphParams.addAll(graph);
- SolrParams localParams = SolrParams.toSolrParams(graphParams);
- domain.graphField = new GraphField(localParams);
+ domain.graphField = new GraphField(FacetParser.jsonToSolrParams(graph));
}
}
@@ -553,30 +549,46 @@ abstract class FacetParser<FacetRequestT extends FacetRequest> {
return new FacetRangeParser(this, key).parse(args);
case "heatmap":
return new FacetHeatmap.Parser(this, key).parse(args);
+ case "func":
+ return parseStat(key, args);
}
- AggValueSource stat = parseStat(key, type, args);
- if (stat == null) {
- throw err("Unknown facet or stat. key=" + key + " type=" + type + " args=" + args);
- }
- return stat;
+ throw err("Unknown facet or stat. key=" + key + " type=" + type + " args=" + args);
}
public Object parseStringFacetOrStat(String key, String s) throws SyntaxError {
// "avg(myfield)"
- return parseStringStat(key, s);
+ return parseStat(key, s);
// TODO - simple string representation of facets
}
- // parses avg(x)
- private AggValueSource parseStringStat(String key, String stat) throws SyntaxError {
- FunctionQParser parser = (FunctionQParser)QParser.getParser(stat, FunctionQParserPlugin.NAME, getSolrRequest());
+ /** Parses simple strings like "avg(x)" in the context of optional local params (may be null) */
+ private AggValueSource parseStatWithParams(String key, SolrParams localparams, String stat) throws SyntaxError {
+ SolrQueryRequest req = getSolrRequest();
+ FunctionQParser parser = new FunctionQParser(stat, localparams, req.getParams(), req);
AggValueSource agg = parser.parseAgg(FunctionQParser.FLAG_DEFAULT);
return agg;
}
-
- public AggValueSource parseStat(String key, String type, Object args) throws SyntaxError {
- return null;
+
+ /** Parses simple strings like "avg(x)" or robust Maps that may contain local params */
+ private AggValueSource parseStat(String key, Object args) throws SyntaxError {
+ assert null != args;
+
+ if (args instanceof CharSequence) {
+ // Both of these variants are already unpacked for us in this case, and use no local params...
+ // 1) x:{func:'min(foo)'}
+ // 2) x:'min(foo)'
+ return parseStatWithParams(key, null, args.toString());
+ }
+
+ if (args instanceof Map) {
+ final Map<String,Object> statMap = (Map<String,Object>)args;
+ return parseStatWithParams(key, jsonToSolrParams(statMap), statMap.get("func").toString());
+ }
+
+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
+ "Stats must be specified as either a simple string, or a json Map");
+
}
@@ -764,6 +776,16 @@ abstract class FacetParser<FacetRequestT extends FacetRequest> {
return parent.getSolrRequest();
}
+ /**
+ * Helper that handles the possibility of map values being lists
+ * NOTE: does *NOT* fail on map values that are sub-maps (ie: nested json objects)
+ */
+ public static SolrParams jsonToSolrParams(Map jsonObject) {
+ // HACK, but NamedList already handles the list processing for us...
+ NamedList<String> nl = new NamedList<>();
+ nl.addAll(jsonObject);
+ return SolrParams.toSolrParams(nl);
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/98d463ae/solr/core/src/test/org/apache/solr/search/facet/DebugAgg.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/search/facet/DebugAgg.java b/solr/core/src/test/org/apache/solr/search/facet/DebugAgg.java
index aeb1f7e..9de0d12 100644
--- a/solr/core/src/test/org/apache/solr/search/facet/DebugAgg.java
+++ b/solr/core/src/test/org/apache/solr/search/facet/DebugAgg.java
@@ -23,6 +23,7 @@ import java.util.function.IntFunction;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.queries.function.ValueSource;
+import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.search.DocSet;
@@ -41,7 +42,7 @@ public class DebugAgg extends AggValueSource {
final String what = fp.hasMoreArguments() ? fp.parseId() : "debug";
switch (what) {
- case "debug": return new DebugAgg();
+ case "debug": return new DebugAgg(fp.getLocalParams());
case "numShards": return new DebugAggNumShards();
default: /* No-Op */
}
@@ -53,13 +54,14 @@ public class DebugAgg extends AggValueSource {
}
}
-
- public DebugAgg() {
+ /**
+ * This exposes the raw localparams used by the FunctionQParser, it does <b>NOT</b>
+ * wrap them in defaults from the request
+ */
+ public final SolrParams localParams;
+ public DebugAgg(SolrParams localParams) {
super("debug");
- }
-
- public DebugAgg(String name) {
- super(name);
+ this.localParams = localParams;
}
@Override
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/98d463ae/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetsStatsParsing.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetsStatsParsing.java b/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetsStatsParsing.java
new file mode 100644
index 0000000..438c545
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetsStatsParsing.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.search.facet;
+
+import java.io.IOException;
+import java.util.Map;
+
+import org.apache.lucene.queries.function.valuesource.IntFieldSource;
+
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.request.SolrQueryRequest;
+import org.junit.BeforeClass;
+import static org.hamcrest.core.IsInstanceOf.instanceOf;
+
+import org.noggit.ObjectBuilder;
+
+/** Whitebox test of the various syntaxes for specifying stats in JSON Facets */
+public class TestJsonFacetsStatsParsing extends SolrTestCaseJ4 {
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ initCore("solrconfig-tlog.xml","schema15.xml");
+ }
+
+ public void testEquality() throws IOException {
+ try (SolrQueryRequest req = req("custom_req_param","foo_i",
+ "overridden_param","xxxxx_i")) {
+
+ // NOTE: we don't bother trying to test 'min(foo_i)' because of SOLR-12559
+ // ...once that bug is fixed, several assertions below will need to change
+ final FacetRequest fr = FacetRequest.parse
+ (req, (Map<String,Object>) ObjectBuilder.fromJSON
+ ("{ " +
+ " s1:'min(field(\"foo_i\"))', " +
+ " s2:'min($custom_req_param)', " +
+ " s3:'min(field($custom_req_param))', " +
+ " s4:{ func:'min($custom_req_param)' }, " +
+ " s5:{ type:func, func:'min($custom_req_param)' }, " +
+ " s6:{ type:func, func:'min($custom_local_param)', custom_local_param:foo_i }, " +
+ " s7:{ type:func, func:'min($overridden_param)', overridden_param:foo_i }, " +
+ // test the test...
+ " diff:'min(field(\"bar_i\"))'," +
+ "}"));
+
+ final Map<String, AggValueSource> stats = fr.getFacetStats();
+ assertEquals(8, stats.size());
+
+ for (Map.Entry<String,AggValueSource> entry : stats.entrySet()) {
+ final String key = entry.getKey();
+ final AggValueSource agg = entry.getValue();
+
+ assertEquals("name of " + key, "min", agg.name());
+ assertThat("type of " + key, agg, instanceOf(SimpleAggValueSource.class));
+ SimpleAggValueSource sagg = (SimpleAggValueSource) agg;
+ assertThat("vs of " + key, sagg.getArg(), instanceOf(IntFieldSource.class));
+
+ if ("diff".equals(key)) {
+ assertEquals("field of " + key, "bar_i", ((IntFieldSource)sagg.getArg()).getField());
+ assertFalse("diff.equals(s1) ?!?!", agg.equals(stats.get("s1")));
+
+ } else {
+ assertEquals("field of " + key, "foo_i", ((IntFieldSource)sagg.getArg()).getField());
+
+ assertEquals(key + ".equals(s1)", agg, stats.get("s1"));
+ assertEquals("s1.equals("+key+")", stats.get("s1"), agg);
+ }
+ }
+ }
+ }
+
+ public void testVerboseSyntaxWithLocalParams() throws IOException {
+ // some parsers may choose to use "global" req params as defaults/shadows for
+ // local params, but DebugAgg does not -- so use these to test that the
+ // JSON Parsing doesn't pollute the local params the ValueSourceParser gets...
+ try (SolrQueryRequest req = req("foo", "zzzz", "yaz", "zzzzz")) {
+ final FacetRequest fr = FacetRequest.parse
+ (req, (Map<String,Object>) ObjectBuilder.fromJSON
+ ("{ x:{type:func, func:'debug()', foo:['abc','xyz'], bar:4.2 } }"));
+
+ final Map<String, AggValueSource> stats = fr.getFacetStats();
+ assertEquals(1, stats.size());
+ AggValueSource agg = stats.get("x");
+ assertNotNull(agg);
+ assertThat(agg, instanceOf(DebugAgg.class));
+
+ DebugAgg x = (DebugAgg)agg;
+ assertEquals(new String[] {"abc", "xyz"}, x.localParams.getParams("foo"));
+ assertEquals((Float)4.2F, x.localParams.getFloat("bar"));
+ assertNull(x.localParams.get("yaz"));
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/98d463ae/solr/solr-ref-guide/src/json-facet-api.adoc
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/json-facet-api.adoc b/solr/solr-ref-guide/src/json-facet-api.adoc
index 12628dc..b9a8a09 100644
--- a/solr/solr-ref-guide/src/json-facet-api.adoc
+++ b/solr/solr-ref-guide/src/json-facet-api.adoc
@@ -373,10 +373,35 @@ Unlike all the facets discussed so far, Aggregation functions (also called *face
|sumsq |`sumsq(rent)` |sum of squares of field or function
|variance |`variance(rent)` |variance of numeric field or function
|stddev |`stddev(rent)` |standard deviation of field or function
-|relatedness |`relatedness('popularity:[100 TO \*]','inStock:true')`|A function for computing a relatedness score of the documents in the domain to a Foreground set, relative to a Background set (both defined as queries). This is primarily for use when building <<Semantic Knowledge Graphs>>.
+|relatedness |`relatedness('popularity:[100 TO *]','inStock:true')`|A function for computing a relatedness score of the documents in the domain to a Foreground set, relative to a Background set (both defined as queries). This is primarily for use when building <<Semantic Knowledge Graphs>>.
|===
-Numeric aggregation functions such as `avg` can be on any numeric field, or on another function of multiple numeric fields such as `avg(mul(price,popularity))`.
+Numeric aggregation functions such as `avg` can be on any numeric field, or on a <<function-queries.adoc#function-queries,nested function>> of multiple numeric fields such as `avg(div(popularity,price))`.
+
+The most common way of requesting an aggregation function is as a simple containing the expression you wish to compute:
+
+[source,javascript]
+----
+{
+ "average_roi": "avg(div(popularity,price))"
+}
+----
+
+An expanded form allows for <<local-parameters-in-queries.adoc#local-parameters-in-queries,Local Parameters>> to be specified. These may be used explicitly by some custom aggregations, but can more commonly be used as parameter references to make aggregation expressions more readable, with out needing to use (global) request parameters:
+
+[source,javascript]
+----
+{
+ "average_roi" : {
+ "type": "func",
+ "func": "avg(div($numer,$denom))",
+ "numer": "mul(popularity,rating)",
+ "denom": "mul(price,size)"
+ }
+}
+----
+
+
== Nested Facets
[12/33] lucene-solr:jira/http2: LUCENE-8306: Allow iteration over
submatches
Posted by da...@apache.org.
LUCENE-8306: Allow iteration over submatches
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/a8839b7e
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/a8839b7e
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/a8839b7e
Branch: refs/heads/jira/http2
Commit: a8839b7eab122037ed1c1674b2f909666718e331
Parents: 2826a95
Author: Alan Woodward <ro...@apache.org>
Authored: Sun Jul 22 20:59:50 2018 +0100
Committer: Alan Woodward <ro...@apache.org>
Committed: Sun Jul 22 21:42:46 2018 +0100
----------------------------------------------------------------------
lucene/CHANGES.txt | 3 +
.../search/DisjunctionMatchesIterator.java | 9 +
.../lucene/search/ExactPhraseMatcher.java | 44 ++++
.../apache/lucene/search/MatchesIterator.java | 58 +++++
.../apache/lucene/search/MultiPhraseQuery.java | 5 +-
.../org/apache/lucene/search/PhraseMatcher.java | 2 +
.../org/apache/lucene/search/PhraseQuery.java | 4 +-
.../org/apache/lucene/search/PhraseWeight.java | 10 +
.../lucene/search/SloppyPhraseMatcher.java | 121 ++++++---
.../lucene/search/TermMatchesIterator.java | 50 ++++
.../apache/lucene/search/spans/SpanWeight.java | 131 ++++++++++
.../lucene/search/TestMatchesIterator.java | 252 ++++++++++++++++++-
.../lucene/search/AssertingMatchesIterator.java | 11 +
13 files changed, 656 insertions(+), 44 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 8257dbc..47769cd 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -198,6 +198,9 @@ Improvements
* LUCENE-8345, GitHub PR #392: Remove instantiation of redundant wrapper classes for primitives;
add wrapper class constructors to forbiddenapis. (Michael Braun via Uwe Schindler)
+* LUCENE-8306: Matches API now allows iteration over sub-matches in Spans (Alan Woodward,
+ Jim Ferenczi, David Smiley)
+
Other:
* LUCENE-8366: Upgrade to ICU 62.1. Emoji handling now uses Unicode 11's
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
index 975199b..cff723b 100644
--- a/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
@@ -158,4 +158,13 @@ final class DisjunctionMatchesIterator implements MatchesIterator {
return queue.top().endOffset();
}
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return queue.top().getSubMatches();
+ }
+
+ @Override
+ public Object label() {
+ return queue.top().label();
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
index b95077d..6fb49b1 100644
--- a/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
@@ -149,4 +149,48 @@ final class ExactPhraseMatcher extends PhraseMatcher {
return postings[postings.length - 1].postings.endOffset();
}
+ @Override
+ MatchesIterator getSubMatches() {
+ return new MatchesIterator() {
+
+ int upTo = -1;
+
+ @Override
+ public boolean next() throws IOException {
+ upTo++;
+ return upTo < postings.length;
+ }
+
+ @Override
+ public int startPosition() {
+ return postings[upTo].pos;
+ }
+
+ @Override
+ public int endPosition() {
+ return postings[upTo].pos;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ return postings[upTo].postings.startOffset();
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return postings[upTo].postings.endOffset();
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return MatchesIterator.EMPTY_ITERATOR;
+ }
+
+ @Override
+ public Object label() {
+ return this;
+ }
+ };
+ }
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
index 450a352..5814d7c 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
@@ -28,6 +28,9 @@ import org.apache.lucene.index.LeafReaderContext;
* positions and/or offsets after each call. You should not call the position or offset methods
* before {@link #next()} has been called, or after {@link #next()} has returned {@code false}.
*
+ * Matches from some queries may span multiple positions. You can retrieve the positions of
+ * individual matching terms on the current match by calling {@link #getSubMatches()}.
+ *
* Matches are ordered by start position, and then by end position. Match intervals may overlap.
*
* @see Weight#matches(LeafReaderContext, int)
@@ -70,4 +73,59 @@ public interface MatchesIterator {
*/
int endOffset() throws IOException;
+ /**
+ * Returns a MatchesIterator that iterates over the positions and offsets of individual
+ * terms within the current match
+ *
+ * Should only be called after {@link #next()} has returned {@code true}
+ */
+ MatchesIterator getSubMatches() throws IOException;
+
+ /**
+ * Returns a label identifying the leaf query causing the current match
+ *
+ * Should only be called after {@link #next()} has returned {@code true}
+ */
+ Object label();
+
+ /**
+ * A MatchesIterator that is immediately exhausted
+ */
+ MatchesIterator EMPTY_ITERATOR = new MatchesIterator() {
+ @Override
+ public boolean next() throws IOException {
+ return false;
+ }
+
+ @Override
+ public int startPosition() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int endPosition() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Object label() {
+ return this;
+ }
+ };
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
index 22b7127..c8d22ba 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
@@ -269,7 +269,7 @@ public class MultiPhraseQuery extends Query {
TermState termState = termStates.get(term).get(context);
if (termState != null) {
termsEnum.seekExact(term.bytes(), termState);
- postings.add(termsEnum.postings(null, exposeOffsets ? PostingsEnum.OFFSETS : PostingsEnum.POSITIONS));
+ postings.add(termsEnum.postings(null, exposeOffsets ? PostingsEnum.ALL : PostingsEnum.POSITIONS));
totalMatchCost += PhraseQuery.termPositionsCost(termsEnum);
}
}
@@ -294,7 +294,7 @@ public class MultiPhraseQuery extends Query {
return new ExactPhraseMatcher(postingsFreqs, totalMatchCost);
}
else {
- return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost);
+ return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost, exposeOffsets);
}
}
@@ -647,5 +647,6 @@ public class MultiPhraseQuery extends Query {
public BytesRef getPayload() throws IOException {
return posQueue.top().pe.getPayload();
}
+
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
index 81040d5..c4b1e36 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
@@ -88,4 +88,6 @@ abstract class PhraseMatcher {
public float getMatchCost() {
return matchCost;
}
+
+ abstract MatchesIterator getSubMatches() throws IOException;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
index 70d2e09..8f04271 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
@@ -446,7 +446,7 @@ public class PhraseQuery extends Query {
return null;
}
te.seekExact(t.bytes(), state);
- PostingsEnum postingsEnum = te.postings(null, exposeOffsets ? PostingsEnum.OFFSETS : PostingsEnum.POSITIONS);
+ PostingsEnum postingsEnum = te.postings(null, exposeOffsets ? PostingsEnum.ALL : PostingsEnum.POSITIONS);
postingsFreqs[i] = new PostingsAndFreq(postingsEnum, positions[i], t);
totalMatchCost += termPositionsCost(te);
}
@@ -457,7 +457,7 @@ public class PhraseQuery extends Query {
return new ExactPhraseMatcher(postingsFreqs, totalMatchCost);
}
else {
- return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost);
+ return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost, exposeOffsets);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java b/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
index 90fa537..2547b8c 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
@@ -123,6 +123,16 @@ abstract class PhraseWeight extends Weight {
public int endOffset() throws IOException {
return matcher.endOffset();
}
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return matcher.getSubMatches();
+ }
+
+ @Override
+ public Object label() {
+ return matcher;
+ }
};
});
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
index 326816d..e9c4519 100644
--- a/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
@@ -54,13 +54,14 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
private final int slop;
private final int numPostings;
private final PhraseQueue pq; // for advancing min position
+ private final boolean captureLeadMatch;
private int end; // current largest phrase position
private int leadPosition;
private int leadOffset;
- private int currentEndPostings;
- private int advanceEndPostings;
+ private int leadEndOffset;
+ private int leadOrd;
private boolean hasRpts; // flag indicating that there are repetitions (as checked in first candidate doc)
private boolean checkedRpts; // flag to only check for repetitions in first candidate doc
@@ -71,10 +72,11 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
private boolean positioned;
private int matchLength;
- SloppyPhraseMatcher(PhraseQuery.PostingsAndFreq[] postings, int slop, float matchCost) {
+ SloppyPhraseMatcher(PhraseQuery.PostingsAndFreq[] postings, int slop, float matchCost, boolean captureLeadMatch) {
super(approximation(postings), matchCost);
this.slop = slop;
this.numPostings = postings.length;
+ this.captureLeadMatch = captureLeadMatch;
pq = new PhraseQueue(postings.length);
phrasePositions = new PhrasePositions[postings.length];
for (int i = 0; i < postings.length; ++i) {
@@ -120,10 +122,8 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
return false;
}
PhrasePositions pp = pq.pop();
- assert pp != null; // if the pq is empty, then positioned == false
- leadPosition = pp.position + pp.offset;
- leadOffset = pp.postings.startOffset();
- currentEndPostings = advanceEndPostings;
+ assert pp != null; // if the pq is not full, then positioned == false
+ captureLead(pp);
matchLength = end - pp.position;
int next = pq.top().position;
while (advancePP(pp)) {
@@ -137,6 +137,7 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
}
pp = pq.pop();
next = pq.top().position;
+ assert pp != null; // if the pq is not full, then positioned == false
matchLength = end - pp.position;
} else {
int matchLength2 = end - pp.position;
@@ -144,14 +145,22 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
matchLength = matchLength2;
}
}
- leadPosition = pp.position + pp.offset;
- leadOffset = pp.postings.startOffset();
- currentEndPostings = advanceEndPostings;
+ captureLead(pp);
}
positioned = false;
return matchLength <= slop;
}
+ private void captureLead(PhrasePositions pp) throws IOException {
+ if (captureLeadMatch == false) {
+ return;
+ }
+ leadOrd = pp.ord;
+ leadPosition = pp.position + pp.offset;
+ leadOffset = pp.postings.startOffset();
+ leadEndOffset = pp.postings.endOffset();
+ }
+
@Override
public int startPosition() {
// when a match is detected, the top postings is advanced until it has moved
@@ -160,6 +169,7 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
// However, the priority queue doesn't guarantee that the top postings is in fact the
// earliest in the list, so we need to cycle through all terms to check.
// this is slow, but Matches is slow anyway...
+ int leadPosition = this.leadPosition;
for (PhrasePositions pp : phrasePositions) {
leadPosition = Math.min(leadPosition, pp.position + pp.offset);
}
@@ -168,7 +178,13 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
@Override
public int endPosition() {
- return phrasePositions[currentEndPostings].position + phrasePositions[currentEndPostings].offset;
+ int endPosition = leadPosition;
+ for (PhrasePositions pp : phrasePositions) {
+ if (pp.ord != leadOrd) {
+ endPosition = Math.max(endPosition, pp.position + pp.offset);
+ }
+ }
+ return endPosition;
}
@Override
@@ -179,6 +195,7 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
// However, the priority queue doesn't guarantee that the top postings is in fact the
// earliest in the list, so we need to cycle through all terms to check
// this is slow, but Matches is slow anyway...
+ int leadOffset = this.leadOffset;
for (PhrasePositions pp : phrasePositions) {
leadOffset = Math.min(leadOffset, pp.postings.startOffset());
}
@@ -187,7 +204,69 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
@Override
public int endOffset() throws IOException {
- return phrasePositions[currentEndPostings].postings.endOffset();
+ int endOffset = leadEndOffset;
+ for (PhrasePositions pp : phrasePositions) {
+ if (pp.ord != leadOrd) {
+ endOffset = Math.max(endOffset, pp.postings.endOffset());
+ }
+ }
+ return endOffset;
+ }
+
+ @Override
+ MatchesIterator getSubMatches() throws IOException {
+ int[][] submatches = new int[phrasePositions.length][3];
+ for (PhrasePositions pp : phrasePositions) {
+ if (pp.ord == leadOrd) {
+ submatches[pp.ord][0] = leadPosition;
+ submatches[pp.ord][1] = leadOffset;
+ submatches[pp.ord][2] = leadEndOffset;
+ }
+ else {
+ submatches[pp.ord][0] = pp.position + pp.offset;
+ submatches[pp.ord][1] = pp.postings.startOffset();
+ submatches[pp.ord][2] = pp.postings.endOffset();
+ }
+ }
+ Arrays.sort(submatches, Comparator.comparingInt(a -> a[0]));
+ return new MatchesIterator() {
+ int upTo = -1;
+ @Override
+ public boolean next() throws IOException {
+ upTo++;
+ return upTo < submatches.length;
+ }
+
+ @Override
+ public int startPosition() {
+ return submatches[upTo][0];
+ }
+
+ @Override
+ public int endPosition() {
+ return submatches[upTo][0];
+ }
+
+ @Override
+ public int startOffset() {
+ return submatches[upTo][1];
+ }
+
+ @Override
+ public int endOffset() {
+ return submatches[upTo][2];
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() {
+ return MatchesIterator.EMPTY_ITERATOR;
+ }
+
+ @Override
+ public Object label() {
+ return this;
+ }
+ };
}
/** advance a PhrasePosition and update 'end', return false if exhausted */
@@ -197,12 +276,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
}
if (pp.position > end) {
end = pp.position;
- advanceEndPostings = pp.ord;
- }
- if (pp.position == end) {
- if (pp.ord > advanceEndPostings) {
- advanceEndPostings = pp.ord;
- }
}
return true;
}
@@ -307,12 +380,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
pp.firstPosition();
if (pp.position > end) {
end = pp.position;
- advanceEndPostings = pp.ord;
- }
- if (pp.position == end) {
- if (pp.ord > advanceEndPostings) {
- advanceEndPostings = pp.ord;
- }
}
pq.add(pp);
}
@@ -342,12 +409,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
for (PhrasePositions pp : phrasePositions) { // iterate cyclic list: done once handled max
if (pp.position > end) {
end = pp.position;
- advanceEndPostings = pp.ord;
- }
- if (pp.position == end) {
- if (pp.ord > advanceEndPostings) {
- advanceEndPostings = pp.ord;
- }
}
pq.add(pp);
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
index defc3af..23858c6 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
@@ -67,4 +67,54 @@ class TermMatchesIterator implements MatchesIterator {
return pe.endOffset();
}
+ @Override
+ public Object label() {
+ return pe;
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return new MatchesIterator() {
+
+ boolean exhausted = false;
+
+ @Override
+ public boolean next() {
+ if (exhausted) {
+ return false;
+ }
+ return exhausted = true;
+ }
+
+ @Override
+ public int startPosition() {
+ return pos;
+ }
+
+ @Override
+ public int endPosition() {
+ return pos;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ return pe.startOffset();
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return pe.endOffset();
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() {
+ return MatchesIterator.EMPTY_ITERATOR;
+ }
+
+ @Override
+ public Object label() {
+ return this;
+ }
+ };
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
index 0313d56..ca789ce 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
@@ -18,6 +18,8 @@ package org.apache.lucene.search.spans;
import java.io.IOException;
+import java.util.Arrays;
+import java.util.Comparator;
import java.util.Map;
import org.apache.lucene.index.LeafReaderContext;
@@ -28,6 +30,8 @@ import org.apache.lucene.search.CollectionStatistics;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.LeafSimScorer;
+import org.apache.lucene.search.Matches;
+import org.apache.lucene.search.MatchesIterator;
import org.apache.lucene.search.TermStatistics;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.similarities.Similarity;
@@ -161,4 +165,131 @@ public abstract class SpanWeight extends Weight {
return Explanation.noMatch("no matching term");
}
+
+ @Override
+ public Matches matches(LeafReaderContext context, int doc) throws IOException {
+ return Matches.forField(field, () -> {
+ Spans spans = getSpans(context, Postings.OFFSETS);
+ if (spans == null) {
+ return null;
+ }
+ if (spans.advance(doc) != doc) {
+ return null;
+ }
+ return new MatchesIterator() {
+
+ int innerTermCount = 0;
+ int[][] innerTerms = new int[2][3];
+ SpanCollector termCollector = new SpanCollector() {
+ @Override
+ public void collectLeaf(PostingsEnum postings, int position, Term term) throws IOException {
+ innerTermCount++;
+ if (innerTermCount > innerTerms.length) {
+ int[][] temp = new int[innerTermCount][3];
+ System.arraycopy(innerTerms, 0, temp, 0, innerTermCount - 1);
+ innerTerms = temp;
+ }
+ innerTerms[innerTermCount - 1][0] = position;
+ innerTerms[innerTermCount - 1][1] = postings.startOffset();
+ innerTerms[innerTermCount - 1][2] = postings.endOffset();
+ }
+
+ @Override
+ public void reset() {
+ innerTermCount = 0;
+ }
+ };
+
+ @Override
+ public boolean next() throws IOException {
+ innerTermCount = 0;
+ return spans.nextStartPosition() != Spans.NO_MORE_POSITIONS;
+ }
+
+ @Override
+ public int startPosition() {
+ return spans.startPosition();
+ }
+
+ @Override
+ public int endPosition() {
+ return spans.endPosition() - 1;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ if (innerTermCount == 0) {
+ collectInnerTerms();
+ }
+ return innerTerms[0][1];
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ if (innerTermCount == 0) {
+ collectInnerTerms();
+ }
+ return innerTerms[innerTermCount - 1][2];
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ if (innerTermCount == 0) {
+ collectInnerTerms();
+ }
+ return new MatchesIterator() {
+
+ int upto = -1;
+
+ @Override
+ public boolean next() throws IOException {
+ upto++;
+ return upto < innerTermCount;
+ }
+
+ @Override
+ public int startPosition() {
+ return innerTerms[upto][0];
+ }
+
+ @Override
+ public int endPosition() {
+ return innerTerms[upto][0];
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ return innerTerms[upto][1];
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return innerTerms[upto][2];
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return MatchesIterator.EMPTY_ITERATOR;
+ }
+
+ @Override
+ public Object label() {
+ return this;
+ }
+ };
+ }
+
+ @Override
+ public Object label() {
+ return SpanWeight.this;
+ }
+
+ void collectInnerTerms() throws IOException {
+ termCollector.reset();
+ spans.collect(termCollector);
+ Arrays.sort(innerTerms, 0, innerTermCount, Comparator.comparing(a -> a[0]));
+ }
+ };
+ });
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
index 3855b04..86e4399 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
@@ -18,8 +18,12 @@
package org.apache.lucene.search;
import java.io.IOException;
+import java.util.Arrays;
import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.Objects;
import java.util.Set;
+import java.util.stream.Collectors;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
@@ -29,9 +33,14 @@ import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.index.Term;
+import org.apache.lucene.search.spans.SpanNearQuery;
+import org.apache.lucene.search.spans.SpanOrQuery;
+import org.apache.lucene.search.spans.SpanQuery;
+import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
@@ -99,7 +108,7 @@ public class TestMatchesIterator extends LuceneTestCase {
"nothing matches this document"
};
- void checkMatches(Query q, String field, int[][] expected) throws IOException {
+ private void checkMatches(Query q, String field, int[][] expected) throws IOException {
Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
for (int i = 0; i < expected.length; i++) {
LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(expected[i][0], searcher.leafContexts));
@@ -112,14 +121,40 @@ public class TestMatchesIterator extends LuceneTestCase {
MatchesIterator it = matches.getMatches(field);
if (expected[i].length == 1) {
assertNull(it);
- return;
+ continue;
}
checkFieldMatches(it, expected[i]);
checkFieldMatches(matches.getMatches(field), expected[i]); // test multiple calls
}
}
- void checkFieldMatches(MatchesIterator it, int[] expected) throws IOException {
+ private void checkLabelCount(Query q, String field, int[] expected) throws IOException {
+ Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
+ for (int i = 0; i < expected.length; i++) {
+ LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
+ int doc = i - ctx.docBase;
+ Matches matches = w.matches(ctx, doc);
+ if (matches == null) {
+ assertEquals("Expected to get matches on document " + i, 0, expected[i]);
+ continue;
+ }
+ MatchesIterator it = matches.getMatches(field);
+ if (expected[i] == 0) {
+ assertNull(it);
+ continue;
+ }
+ else {
+ assertNotNull(it);
+ }
+ IdentityHashMap<Object, Integer> labels = new IdentityHashMap<>();
+ while (it.next()) {
+ labels.put(it.label(), 1);
+ }
+ assertEquals(expected[i], labels.size());
+ }
+ }
+
+ private void checkFieldMatches(MatchesIterator it, int[] expected) throws IOException {
int pos = 1;
while (it.next()) {
//System.out.println(expected[i][pos] + "->" + expected[i][pos + 1] + "[" + expected[i][pos + 2] + "->" + expected[i][pos + 3] + "]");
@@ -132,7 +167,7 @@ public class TestMatchesIterator extends LuceneTestCase {
assertEquals(expected.length, pos);
}
- void checkNoPositionsMatches(Query q, String field, boolean[] expected) throws IOException {
+ private void checkNoPositionsMatches(Query q, String field, boolean[] expected) throws IOException {
Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
for (int i = 0; i < expected.length; i++) {
LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
@@ -148,8 +183,90 @@ public class TestMatchesIterator extends LuceneTestCase {
}
}
+ private void checkTermMatches(Query q, String field, TermMatch[][][] expected) throws IOException {
+ Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
+ for (int i = 0; i < expected.length; i++) {
+ LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
+ int doc = i - ctx.docBase;
+ Matches matches = w.matches(ctx, doc);
+ if (matches == null) {
+ assertEquals(expected[i].length, 0);
+ continue;
+ }
+ MatchesIterator it = matches.getMatches(field);
+ if (expected[i].length == 0) {
+ assertNull(it);
+ continue;
+ }
+ checkTerms(expected[i], it);
+ }
+ }
+
+ private void checkTerms(TermMatch[][] expected, MatchesIterator it) throws IOException {
+ int upTo = 0;
+ while (it.next()) {
+ Set<TermMatch> expectedMatches = new HashSet<>(Arrays.asList(expected[upTo]));
+ MatchesIterator submatches = it.getSubMatches();
+ while (submatches.next()) {
+ TermMatch tm = new TermMatch(submatches.startPosition(), submatches.startOffset(), submatches.endOffset());
+ if (expectedMatches.remove(tm) == false) {
+ fail("Unexpected term match: " + tm);
+ }
+ }
+ if (expectedMatches.size() != 0) {
+ fail("Missing term matches: " + expectedMatches.stream().map(Object::toString).collect(Collectors.joining(", ")));
+ }
+ upTo++;
+ }
+ if (upTo < expected.length - 1) {
+ fail("Missing expected match");
+ }
+ }
+
+ static class TermMatch {
+
+ public final int position;
+
+ public final int startOffset;
+
+ public final int endOffset;
+
+ public TermMatch(PostingsEnum pe, int position) throws IOException {
+ this.position = position;
+ this.startOffset = pe.startOffset();
+ this.endOffset = pe.endOffset();
+ }
+
+ public TermMatch(int position, int startOffset, int endOffset) {
+ this.position = position;
+ this.startOffset = startOffset;
+ this.endOffset = endOffset;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ TermMatch termMatch = (TermMatch) o;
+ return position == termMatch.position &&
+ startOffset == termMatch.startOffset &&
+ endOffset == termMatch.endOffset;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(position, startOffset, endOffset);
+ }
+
+ @Override
+ public String toString() {
+ return position + "[" + startOffset + "->" + endOffset + "]";
+ }
+ }
+
public void testTermQuery() throws IOException {
- Query q = new TermQuery(new Term(FIELD_WITH_OFFSETS, "w1"));
+ Term t = new Term(FIELD_WITH_OFFSETS, "w1");
+ Query q = new TermQuery(t);
checkMatches(q, FIELD_WITH_OFFSETS, new int[][]{
{ 0, 0, 0, 0, 2 },
{ 1, 0, 0, 0, 2 },
@@ -157,6 +274,14 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8 },
{ 4 }
});
+ checkTermMatches(q, FIELD_WITH_OFFSETS, new TermMatch[][][]{
+ { { new TermMatch(0, 0, 2) } },
+ { { new TermMatch(0, 0, 2) } },
+ { { new TermMatch(0, 0, 2) } },
+ { { new TermMatch(0, 0, 2) }, { new TermMatch(2, 6, 8) } },
+ {}
+ });
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 1, 1, 1, 1, 0, 0 });
}
public void testTermQueryNoStoredOffsets() throws IOException {
@@ -191,6 +316,7 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 5, 5, 15, 17 },
{ 4 }
});
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 2, 2, 1, 2, 0, 0 });
}
public void testDisjunctionNoPositions() throws IOException {
@@ -215,6 +341,7 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 5, 5, 15, 17 },
{ 4 }
});
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 2, 2, 0, 2, 0, 0 });
}
public void testReqOptNoPositions() throws IOException {
@@ -248,6 +375,7 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 3, 3, 9, 11, 5, 5, 15, 17 },
{ 4 }
});
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 3, 1, 3, 3, 0, 0 });
}
public void testMinShouldMatchNoPositions() throws IOException {
@@ -331,6 +459,7 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 1, 1, 3, 5, 2, 2, 6, 8, 4, 4, 12, 14 },
{ 4 }
});
+ checkLabelCount(rq, FIELD_WITH_OFFSETS, new int[]{ 2, 2, 2, 2, 0 });
}
@@ -392,12 +521,55 @@ public class TestMatchesIterator extends LuceneTestCase {
// 0 1 2 3 4 5 6 7
// "a phrase sentence with many phrase sentence iterations of a phrase sentence",
+ public void testSloppyPhraseQueryWithRepeats() throws IOException {
+ Term p = new Term(FIELD_WITH_OFFSETS, "phrase");
+ Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
+ PhraseQuery pq = new PhraseQuery(10, FIELD_WITH_OFFSETS, "phrase", "sentence", "sentence");
+ checkMatches(pq, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 1, 6, 2, 43, 2, 11, 9, 75, 5, 11, 28, 75, 6, 11, 35, 75 }
+ });
+ checkLabelCount(pq, FIELD_WITH_OFFSETS, new int[]{ 0, 0, 0, 0, 1 });
+ checkTermMatches(pq, FIELD_WITH_OFFSETS, new TermMatch[][][]{
+ {}, {}, {}, {},
+ { {
+ new TermMatch(1, 2, 8),
+ new TermMatch(2, 9, 17),
+ new TermMatch(6, 35, 43)
+ }, {
+ new TermMatch(5, 28, 34),
+ new TermMatch(2, 9, 17),
+ new TermMatch(11, 67, 75)
+ }, {
+ new TermMatch(5, 28, 34),
+ new TermMatch(6, 35, 43),
+ new TermMatch(11, 67, 75)
+ }, {
+ new TermMatch(10, 60, 66),
+ new TermMatch(6, 35, 43),
+ new TermMatch(11, 67, 75)
+ } }
+ });
+ }
+
public void testSloppyPhraseQuery() throws IOException {
+ Term a = new Term(FIELD_WITH_OFFSETS, "a");
+ Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
PhraseQuery pq = new PhraseQuery(4, FIELD_WITH_OFFSETS, "a", "sentence");
checkMatches(pq, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
{ 4, 0, 2, 0, 17, 6, 9, 35, 59, 9, 11, 58, 75 }
});
+ checkTermMatches(pq, FIELD_WITH_OFFSETS, new TermMatch[][][]{
+ {}, {}, {}, {},
+ { {
+ new TermMatch(0, 0, 1), new TermMatch(2, 9, 17)
+ }, {
+ new TermMatch(9, 58, 59), new TermMatch(6, 35, 43)
+ }, {
+ new TermMatch(9, 58, 59), new TermMatch(11, 67, 75)
+ } }
+ });
}
public void testExactPhraseQuery() throws IOException {
@@ -407,28 +579,57 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 4, 1, 2, 2, 17, 5, 6, 28, 43, 10, 11, 60, 75 }
});
+ Term a = new Term(FIELD_WITH_OFFSETS, "a");
+ Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
PhraseQuery pq2 = new PhraseQuery.Builder()
- .add(new Term(FIELD_WITH_OFFSETS, "a"))
- .add(new Term(FIELD_WITH_OFFSETS, "sentence"), 2)
+ .add(a)
+ .add(s, 2)
.build();
checkMatches(pq2, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
{ 4, 0, 2, 0, 17, 9, 11, 58, 75 }
});
+ checkTermMatches(pq2, FIELD_WITH_OFFSETS, new TermMatch[][][]{
+ {}, {}, {}, {},
+ { {
+ new TermMatch(0, 0, 1), new TermMatch(2, 9, 17)
+ }, {
+ new TermMatch(9, 58, 59), new TermMatch(11, 67, 75)
+ } }
+ });
}
// 0 1 2 3 4 5 6 7
// "a phrase sentence with many phrase sentence iterations of a phrase sentence",
public void testSloppyMultiPhraseQuery() throws IOException {
+ Term p = new Term(FIELD_WITH_OFFSETS, "phrase");
+ Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
+ Term i = new Term(FIELD_WITH_OFFSETS, "iterations");
MultiPhraseQuery mpq = new MultiPhraseQuery.Builder()
- .add(new Term(FIELD_WITH_OFFSETS, "phrase"))
- .add(new Term[]{ new Term(FIELD_WITH_OFFSETS, "sentence"), new Term(FIELD_WITH_OFFSETS, "iterations") })
+ .add(p)
+ .add(new Term[]{ s, i })
.setSlop(4)
.build();
checkMatches(mpq, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
- { 4, 1, 2, 2, 17, 5, 7, 28, 54, 5, 7, 28, 54, 10, 11, 60, 75 }
+ { 4, 1, 2, 2, 17, 5, 6, 28, 43, 5, 7, 28, 54, 10, 11, 60, 75 }
+ });
+ checkTermMatches(mpq, FIELD_WITH_OFFSETS, new TermMatch[][][]{
+ {}, {}, {}, {},
+ { {
+ new TermMatch(1, 2, 8),
+ new TermMatch(2, 9, 17)
+ }, {
+ new TermMatch(5, 28, 34),
+ new TermMatch(6, 35, 43)
+ }, {
+ new TermMatch(5, 28, 34),
+ new TermMatch(7, 44, 54)
+ }, {
+ new TermMatch(10, 60, 66),
+ new TermMatch(11, 67, 75)
+ } }
});
}
@@ -452,4 +653,35 @@ public class TestMatchesIterator extends LuceneTestCase {
});
}
+ // 0 1 2 3 4 5 6 7
+ // "a phrase sentence with many phrase sentence iterations of a phrase sentence",
+
+ public void testSpanQuery() throws IOException {
+ SpanQuery subq = SpanNearQuery.newOrderedNearQuery(FIELD_WITH_OFFSETS)
+ .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "with")))
+ .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "many")))
+ .build();
+ Query q = SpanNearQuery.newOrderedNearQuery(FIELD_WITH_OFFSETS)
+ .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "sentence")))
+ .addClause(new SpanOrQuery(subq, new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "iterations"))))
+ .build();
+ checkMatches(q, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 2, 4, 9, 27, 6, 7, 35, 54 }
+ });
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 0, 0, 0, 0, 1 });
+ checkTermMatches(q, FIELD_WITH_OFFSETS, new TermMatch[][][]{
+ {}, {}, {}, {},
+ {
+ {
+ new TermMatch(2, 9, 17),
+ new TermMatch(3, 18, 22),
+ new TermMatch(4, 23, 27)
+ }, {
+ new TermMatch(6, 35, 43), new TermMatch(7, 44, 54)
+ }
+ }
+ });
+ }
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a8839b7e/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
index 4f06512..5f7e307 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
@@ -67,4 +67,15 @@ class AssertingMatchesIterator implements MatchesIterator {
return in.endOffset();
}
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ assert state == State.ITERATING : state;
+ return in.getSubMatches();
+ }
+
+ @Override
+ public Object label() {
+ assert state == State.ITERATING : state;
+ return in.label();
+ }
}
[28/33] lucene-solr:jira/http2: LUCENE-8412: Fix
TestDistributedGrouping failure.
Posted by da...@apache.org.
LUCENE-8412: Fix TestDistributedGrouping failure.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/d010cdd8
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/d010cdd8
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/d010cdd8
Branch: refs/heads/jira/http2
Commit: d010cdd87eec89bf6308351b817d9ec1d5c6e14e
Parents: 8892c0d
Author: Adrien Grand <jp...@gmail.com>
Authored: Tue Jul 24 12:10:25 2018 +0200
Committer: Adrien Grand <jp...@gmail.com>
Committed: Tue Jul 24 12:10:25 2018 +0200
----------------------------------------------------------------------
.../grouping/distributed/command/TopGroupsFieldCommand.java | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d010cdd8/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java b/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java
index 3902841..b618286 100644
--- a/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java
+++ b/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/TopGroupsFieldCommand.java
@@ -173,8 +173,10 @@ public class TopGroupsFieldCommand implements Command<TopGroups<BytesRef>> {
} else {
topGroups = secondPassCollector.getTopGroups(0);
}
- for (GroupDocs<?> group : topGroups.groups) {
- TopFieldCollector.populateScores(group.scoreDocs, searcher, query);
+ if (needScores) {
+ for (GroupDocs<?> group : topGroups.groups) {
+ TopFieldCollector.populateScores(group.scoreDocs, searcher, query);
+ }
}
}
[22/33] lucene-solr:jira/http2: SOLR-11598: Fix test case + class
name typo
Posted by da...@apache.org.
SOLR-11598: Fix test case + class name typo
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/877bde73
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/877bde73
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/877bde73
Branch: refs/heads/jira/http2
Commit: 877bde7347794c93569201040538edfdae057709
Parents: 028c86b
Author: Varun Thacker <va...@apache.org>
Authored: Mon Jul 23 12:21:59 2018 -0700
Committer: Varun Thacker <va...@apache.org>
Committed: Mon Jul 23 12:21:59 2018 -0700
----------------------------------------------------------------------
.../apache/solr/handler/export/DoubeValue.java | 81 --------------
.../apache/solr/handler/export/DoubleValue.java | 81 ++++++++++++++
.../solr/handler/export/TestExportWriter.java | 106 +++++++++----------
3 files changed, 131 insertions(+), 137 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/877bde73/solr/core/src/java/org/apache/solr/handler/export/DoubeValue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/DoubeValue.java b/solr/core/src/java/org/apache/solr/handler/export/DoubeValue.java
deleted file mode 100644
index a37e13d..0000000
--- a/solr/core/src/java/org/apache/solr/handler/export/DoubeValue.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.solr.handler.export;
-
-import java.io.IOException;
-
-import org.apache.lucene.index.DocValues;
-import org.apache.lucene.index.LeafReader;
-import org.apache.lucene.index.LeafReaderContext;
-import org.apache.lucene.index.NumericDocValues;
-
-class DoubleValue implements SortValue {
-
- protected NumericDocValues vals;
- protected String field;
- protected double currentValue;
- protected DoubleComp comp;
- private int lastDocID;
- private LeafReader reader;
-
- public DoubleValue(String field, DoubleComp comp) {
- this.field = field;
- this.comp = comp;
- this.currentValue = comp.resetValue();
- }
-
- public DoubleValue copy() {
- return new DoubleValue(field, comp);
- }
-
- public void setNextReader(LeafReaderContext context) throws IOException {
- this.reader = context.reader();
- this.vals = DocValues.getNumeric(this.reader, this.field);
- lastDocID = 0;
- }
-
- public void setCurrentValue(int docId) throws IOException {
- if (docId < lastDocID) {
- throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
- }
- lastDocID = docId;
- int curDocID = vals.docID();
- if (docId > curDocID) {
- curDocID = vals.advance(docId);
- }
- if (docId == curDocID) {
- currentValue = Double.longBitsToDouble(vals.longValue());
- } else {
- currentValue = 0f;
- }
- }
-
- public void setCurrentValue(SortValue sv) {
- DoubleValue dv = (DoubleValue)sv;
- this.currentValue = dv.currentValue;
- }
-
- public void reset() {
- this.currentValue = comp.resetValue();
- }
-
- public int compareTo(SortValue o) {
- DoubleValue dv = (DoubleValue)o;
- return comp.compare(currentValue, dv.currentValue);
- }
-}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/877bde73/solr/core/src/java/org/apache/solr/handler/export/DoubleValue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/DoubleValue.java b/solr/core/src/java/org/apache/solr/handler/export/DoubleValue.java
new file mode 100644
index 0000000..a37e13d
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/DoubleValue.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.NumericDocValues;
+
+class DoubleValue implements SortValue {
+
+ protected NumericDocValues vals;
+ protected String field;
+ protected double currentValue;
+ protected DoubleComp comp;
+ private int lastDocID;
+ private LeafReader reader;
+
+ public DoubleValue(String field, DoubleComp comp) {
+ this.field = field;
+ this.comp = comp;
+ this.currentValue = comp.resetValue();
+ }
+
+ public DoubleValue copy() {
+ return new DoubleValue(field, comp);
+ }
+
+ public void setNextReader(LeafReaderContext context) throws IOException {
+ this.reader = context.reader();
+ this.vals = DocValues.getNumeric(this.reader, this.field);
+ lastDocID = 0;
+ }
+
+ public void setCurrentValue(int docId) throws IOException {
+ if (docId < lastDocID) {
+ throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
+ }
+ lastDocID = docId;
+ int curDocID = vals.docID();
+ if (docId > curDocID) {
+ curDocID = vals.advance(docId);
+ }
+ if (docId == curDocID) {
+ currentValue = Double.longBitsToDouble(vals.longValue());
+ } else {
+ currentValue = 0f;
+ }
+ }
+
+ public void setCurrentValue(SortValue sv) {
+ DoubleValue dv = (DoubleValue)sv;
+ this.currentValue = dv.currentValue;
+ }
+
+ public void reset() {
+ this.currentValue = comp.resetValue();
+ }
+
+ public int compareTo(SortValue o) {
+ DoubleValue dv = (DoubleValue)o;
+ return comp.compare(currentValue, dv.currentValue);
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/877bde73/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
index 55efdee..8b7de24 100644
--- a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
+++ b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
@@ -22,13 +22,16 @@ import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
+import java.util.Map;
import java.util.Set;
import org.apache.lucene.util.TestUtil;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.util.SuppressForbidden;
import org.apache.solr.common.util.Utils;
import org.apache.solr.request.SolrQueryRequest;
@@ -41,6 +44,7 @@ import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
+import org.noggit.ObjectBuilder;
public class TestExportWriter extends SolrTestCaseJ4 {
@@ -594,7 +598,7 @@ public class TestExportWriter extends SolrTestCaseJ4 {
"field1_s_dv", String.valueOf(str_vals[number]),
"field2_i_p", String.valueOf(number),
"field3_l_p", String.valueOf(number)));
- if (numDocs % 3000 ==0) {
+ if (numDocs % 300 ==0) {
assertU(commit());
}
}
@@ -624,66 +628,56 @@ public class TestExportWriter extends SolrTestCaseJ4 {
String fieldsStr = String.join(",", fieldStrs); // fl : field1, field2
String resp = h.query(req("q", "*:*", "qt", "/export", "fl", "id," + fieldsStr, "sort", sortStr));
-
- //We cannot compare /select vs /export as for docs with the same values ( ties ) the ordering is different
- SolrQueryRequest req = null;
- try {
- req = req("q", "*:*", "qt", "/select", "fl", "id," + fieldsStr, "sort", sortStr, "rows", Integer.toString(numDocs));
-
- SolrQueryResponse selectRsp = h.queryAndResponse("", req);
- DocList selectDocList = ((ResultContext)selectRsp.getResponse()).getDocList();
- assert selectDocList.size() == numDocs;
- DocIterator selectDocListIter = selectDocList.iterator();
-
- ObjectMapper mapper = new ObjectMapper();
- HashMap respMap = mapper.readValue(resp, HashMap.class);
- List docs = (ArrayList) ((HashMap) respMap.get("response")).get("docs");
- assert docs.size() == numDocs;
-
- for (int i = 0; i < docs.size() - 1; i++) { // docs..
- assertEquals("Position:" + i + " has different id value" , String.valueOf(selectDocListIter.nextDoc()), String.valueOf(((HashMap) docs.get(i)).get("id")));
-
- for (int j = 0; j < fieldSorts.length; j++) { // fields ..
- String field = fieldSorts[j].getField();
- String sort = fieldSorts[j].getSort();
- String fieldVal1 = String.valueOf(((HashMap) docs.get(i)).get(field)); // 1st doc
- String fieldVal2 = String.valueOf(((HashMap) docs.get(i + 1)).get(field)); // 2nd obj
- if (fieldVal1.equals(fieldVal2)) {
- continue;
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap respMap = mapper.readValue(resp, HashMap.class);
+ List docs = (ArrayList) ((HashMap) respMap.get("response")).get("docs");
+
+ SolrQueryRequest selectReq = req("q", "*:*", "qt", "/select", "fl", "id," + fieldsStr, "sort", sortStr, "rows", Integer.toString(numDocs), "wt", "json");
+ String response = h.query(selectReq);
+ Map rsp = (Map)ObjectBuilder.fromJSON(response);
+ List doclist = (List)(((Map)rsp.get("response")).get("docs"));
+
+ assert docs.size() == numDocs;
+
+ for (int i = 0; i < docs.size() - 1; i++) { // docs..
+ assertEquals("Position:" + i + " has different id value" , ((LinkedHashMap)doclist.get(i)).get("id"), String.valueOf(((HashMap) docs.get(i)).get("id")));
+
+ for (int j = 0; j < fieldSorts.length; j++) { // fields ..
+ String field = fieldSorts[j].getField();
+ String sort = fieldSorts[j].getSort();
+ String fieldVal1 = String.valueOf(((HashMap) docs.get(i)).get(field)); // 1st doc
+ String fieldVal2 = String.valueOf(((HashMap) docs.get(i + 1)).get(field)); // 2nd obj
+ if (fieldVal1.equals(fieldVal2)) {
+ continue;
+ } else {
+ if (sort.equals("asc")) {
+ if (field.equals("stringdv") || field.equals("field1_s_dv")|| field.equals("datedv") || field.equals("booleandv")) { // use string comparator
+ assertTrue(fieldVal1.compareTo(fieldVal2) < 0);
+ } else if (field.equals("doubledv")){
+ assertTrue(Double.compare(Double.valueOf(fieldVal1), Double.valueOf(fieldVal2)) <= 0);
+ } else if(field.equals("floatdv")) {
+ assertTrue(Float.compare(Float.valueOf(fieldVal1), Float.valueOf(fieldVal2)) <= 0);
+ } else if(field.equals("intdv") || "field2_i_p".equals(field)) {
+ assertTrue(Integer.compare(Integer.valueOf(fieldVal1), Integer.valueOf(fieldVal2)) <= 0);
+ } else if(field.equals("longdv") || field.equals("field3_l_p")) {
+ assertTrue(Long.compare(Integer.valueOf(fieldVal1), Long.valueOf(fieldVal2)) <= 0);
+ }
} else {
- if (sort.equals("asc")) {
- if (field.equals("stringdv") || field.equals("field1_s_dv")|| field.equals("datedv") || field.equals("booleandv")) { // use string comparator
- assertTrue(fieldVal1.compareTo(fieldVal2) < 0);
- } else if (field.equals("doubledv")){
- assertTrue(Double.compare(Double.valueOf(fieldVal1), Double.valueOf(fieldVal2)) <= 0);
- } else if(field.equals("floatdv")) {
- assertTrue(Float.compare(Float.valueOf(fieldVal1), Float.valueOf(fieldVal2)) <= 0);
- } else if(field.equals("intdv") || "field2_i_p".equals(field)) {
- assertTrue(Integer.compare(Integer.valueOf(fieldVal1), Integer.valueOf(fieldVal2)) <= 0);
- } else if(field.equals("longdv") || field.equals("field3_l_p")) {
- assertTrue(Long.compare(Integer.valueOf(fieldVal1), Long.valueOf(fieldVal2)) <= 0);
- }
- } else {
- if (field.equals("stringdv") || field.equals("field1_s_dv")|| field.equals("datedv") || field.equals("booleandv")) { // use string comparator
- assertTrue(fieldVal1.compareTo(fieldVal2) > 0);
- } else if (field.equals("doubledv")){
- assertTrue(Double.compare(Double.valueOf(fieldVal1), Double.valueOf(fieldVal2)) >= 0);
- } else if(field.equals("floatdv")) {
- assertTrue(Float.compare(Float.valueOf(fieldVal1), Float.valueOf(fieldVal2)) >= 0);
- } else if(field.equals("intdv") || "field2_i_p".equals(field)) {
- assertTrue(Integer.compare(Integer.valueOf(fieldVal1), Integer.valueOf(fieldVal2)) >= 0);
- } else if(field.equals("longdv") || field.equals("field3_l_p")) {
- assertTrue(Long.compare(Integer.valueOf(fieldVal1), Long.valueOf(fieldVal2)) >= 0);
- }
+ if (field.equals("stringdv") || field.equals("field1_s_dv")|| field.equals("datedv") || field.equals("booleandv")) { // use string comparator
+ assertTrue(fieldVal1.compareTo(fieldVal2) > 0);
+ } else if (field.equals("doubledv")){
+ assertTrue(Double.compare(Double.valueOf(fieldVal1), Double.valueOf(fieldVal2)) >= 0);
+ } else if(field.equals("floatdv")) {
+ assertTrue(Float.compare(Float.valueOf(fieldVal1), Float.valueOf(fieldVal2)) >= 0);
+ } else if(field.equals("intdv") || "field2_i_p".equals(field)) {
+ assertTrue(Integer.compare(Integer.valueOf(fieldVal1), Integer.valueOf(fieldVal2)) >= 0);
+ } else if(field.equals("longdv") || field.equals("field3_l_p")) {
+ assertTrue(Long.compare(Integer.valueOf(fieldVal1), Long.valueOf(fieldVal2)) >= 0);
}
- break;
}
+ break;
}
}
- } finally {
- if (req != null) {
- req.close();
- }
}
}
[02/33] lucene-solr:jira/http2: LUCENE-8402: Remove invalid
identityHashCode assertions in TestPriorityQueue.
Posted by da...@apache.org.
LUCENE-8402: Remove invalid identityHashCode assertions in TestPriorityQueue.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/a19bc5ec
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/a19bc5ec
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/a19bc5ec
Branch: refs/heads/jira/http2
Commit: a19bc5ecb64a51e2dc4a3c37f90a997350cbb4bd
Parents: f6e9d00b
Author: Jim Ferenczi <ji...@apache.org>
Authored: Fri Jul 20 10:13:19 2018 +0200
Committer: Jim Ferenczi <ji...@apache.org>
Committed: Fri Jul 20 10:13:19 2018 +0200
----------------------------------------------------------------------
.../apache/lucene/util/TestPriorityQueue.java | 170 +++++++++----------
1 file changed, 80 insertions(+), 90 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a19bc5ec/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java b/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java
index 08a0cf1..d4859cc 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java
@@ -32,13 +32,6 @@ public class TestPriorityQueue extends LuceneTestCase {
@Override
protected boolean lessThan(Integer a, Integer b) {
- if (a.equals(b)) {
- assert (a != b);
- int hashA = System.identityHashCode(a);
- int hashB = System.identityHashCode(b);
- assert (hashA != hashB);
- return hashA < hashB;
- }
return (a < b);
}
@@ -47,93 +40,91 @@ public class TestPriorityQueue extends LuceneTestCase {
for (int i = 1; i <= size(); i++) {
int parent = i >>> 1;
if (parent > 1) {
- assertTrue(lessThan((Integer) heapArray[parent],
- (Integer) heapArray[i]));
+ if (lessThan((Integer) heapArray[parent], (Integer) heapArray[i]) == false) {
+ assertEquals(heapArray[parent], heapArray[i]);
+ }
}
}
}
+ }
+ public void testPQ() throws Exception {
+ testPQ(atLeast(10000), random());
}
- public void testPQ() throws Exception {
- testPQ(atLeast(10000), random());
+ public static void testPQ(int count, Random gen) {
+ PriorityQueue<Integer> pq = new IntegerQueue(count);
+ int sum = 0, sum2 = 0;
+
+ for (int i = 0; i < count; i++) {
+ int next = gen.nextInt();
+ sum += next;
+ pq.add(next);
}
- public static void testPQ(int count, Random gen) {
- PriorityQueue<Integer> pq = new IntegerQueue(count);
- int sum = 0, sum2 = 0;
+ // Date end = new Date();
- for (int i = 0; i < count; i++)
- {
- int next = gen.nextInt();
- sum += next;
- pq.add(next);
- }
+ // System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000);
+ // System.out.println(" microseconds/put");
- // Date end = new Date();
+ // start = new Date();
- // System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000);
- // System.out.println(" microseconds/put");
+ int last = Integer.MIN_VALUE;
+ for (int i = 0; i < count; i++) {
+ Integer next = pq.pop();
+ assertTrue(next.intValue() >= last);
+ last = next.intValue();
+ sum2 += last;
+ }
- // start = new Date();
+ assertEquals(sum, sum2);
+ // end = new Date();
- int last = Integer.MIN_VALUE;
- for (int i = 0; i < count; i++)
- {
- Integer next = pq.pop();
- assertTrue(next.intValue() >= last);
- last = next.intValue();
- sum2 += last;
- }
+ // System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000);
+ // System.out.println(" microseconds/pop");
+ }
- assertEquals(sum, sum2);
- // end = new Date();
+ public void testClear() {
+ PriorityQueue<Integer> pq = new IntegerQueue(3);
+ pq.add(2);
+ pq.add(3);
+ pq.add(1);
+ assertEquals(3, pq.size());
+ pq.clear();
+ assertEquals(0, pq.size());
+ }
- // System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000);
- // System.out.println(" microseconds/pop");
- }
+ public void testFixedSize() {
+ PriorityQueue<Integer> pq = new IntegerQueue(3);
+ pq.insertWithOverflow(2);
+ pq.insertWithOverflow(3);
+ pq.insertWithOverflow(1);
+ pq.insertWithOverflow(5);
+ pq.insertWithOverflow(7);
+ pq.insertWithOverflow(1);
+ assertEquals(3, pq.size());
+ assertEquals((Integer) 3, pq.top());
+ }
- public void testClear() {
- PriorityQueue<Integer> pq = new IntegerQueue(3);
- pq.add(2);
- pq.add(3);
- pq.add(1);
- assertEquals(3, pq.size());
- pq.clear();
- assertEquals(0, pq.size());
- }
-
- public void testFixedSize() {
- PriorityQueue<Integer> pq = new IntegerQueue(3);
- pq.insertWithOverflow(2);
- pq.insertWithOverflow(3);
- pq.insertWithOverflow(1);
- pq.insertWithOverflow(5);
- pq.insertWithOverflow(7);
- pq.insertWithOverflow(1);
- assertEquals(3, pq.size());
- assertEquals((Integer) 3, pq.top());
- }
-
- public void testInsertWithOverflow() {
- int size = 4;
- PriorityQueue<Integer> pq = new IntegerQueue(size);
- Integer i1 = 2;
- Integer i2 = 3;
- Integer i3 = 1;
- Integer i4 = 5;
- Integer i5 = 7;
- Integer i6 = 1;
-
- assertNull(pq.insertWithOverflow(i1));
- assertNull(pq.insertWithOverflow(i2));
- assertNull(pq.insertWithOverflow(i3));
- assertNull(pq.insertWithOverflow(i4));
- assertTrue(pq.insertWithOverflow(i5) == i3); // i3 should have been dropped
- assertTrue(pq.insertWithOverflow(i6) == i6); // i6 should not have been inserted
- assertEquals(size, pq.size());
- assertEquals((Integer) 2, pq.top());
- }
+ public void testInsertWithOverflow() {
+ int size = 4;
+ PriorityQueue<Integer> pq = new IntegerQueue(size);
+ Integer i1 = 2;
+ Integer i2 = 3;
+ Integer i3 = 1;
+ Integer i4 = 5;
+ Integer i5 = 7;
+ Integer i6 = 1;
+
+ assertNull(pq.insertWithOverflow(i1));
+ assertNull(pq.insertWithOverflow(i2));
+ assertNull(pq.insertWithOverflow(i3));
+ assertNull(pq.insertWithOverflow(i4));
+ assertTrue(pq.insertWithOverflow(i5) == i3); // i3 should have been dropped
+ assertTrue(pq.insertWithOverflow(i6) == i6); // i6 should not have been inserted
+ assertEquals(size, pq.size());
+ assertEquals((Integer) 2, pq.top());
+ }
public void testRemovalsAndInsertions() {
Random random = random();
@@ -193,14 +184,14 @@ public class TestPriorityQueue extends LuceneTestCase {
public void testIteratorEmpty() {
IntegerQueue queue = new IntegerQueue(3);
-
+
Iterator<Integer> it = queue.iterator();
assertFalse(it.hasNext());
expectThrows(NoSuchElementException.class, () -> {
it.next();
});
}
-
+
public void testIteratorOne() {
IntegerQueue queue = new IntegerQueue(3);
@@ -213,7 +204,7 @@ public class TestPriorityQueue extends LuceneTestCase {
it.next();
});
}
-
+
public void testIteratorTwo() {
IntegerQueue queue = new IntegerQueue(3);
@@ -230,7 +221,6 @@ public class TestPriorityQueue extends LuceneTestCase {
});
}
- @AwaitsFix(bugUrl="https://issues.apache.org/jira/browse/LUCENE-8402")
public void testIteratorRandom() {
final int maxSize = TestUtil.nextInt(random(), 1, 20);
IntegerQueue queue = new IntegerQueue(maxSize);
@@ -256,13 +246,13 @@ public class TestPriorityQueue extends LuceneTestCase {
public void testMaxIntSize() {
expectThrows(IllegalArgumentException.class, () -> {
- new PriorityQueue<Boolean>(Integer.MAX_VALUE) {
- @Override
- public boolean lessThan(Boolean a, Boolean b) {
- // uncalled
- return true;
- }
- };
- });
+ new PriorityQueue<Boolean>(Integer.MAX_VALUE) {
+ @Override
+ public boolean lessThan(Boolean a, Boolean b) {
+ // uncalled
+ return true;
+ }
+ };
+ });
}
}
[24/33] lucene-solr:jira/http2: SOLR-12555: Add add'l expectThrows()
test helper
Posted by da...@apache.org.
SOLR-12555: Add add'l expectThrows() test helper
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/6ed9607f
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/6ed9607f
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/6ed9607f
Branch: refs/heads/jira/http2
Commit: 6ed9607f74398d054e1cda7d1c02da80c2d93180
Parents: de16baa
Author: Jason Gerlowski <ja...@lucidworks.com>
Authored: Mon Jul 23 20:37:04 2018 -0400
Committer: Jason Gerlowski <ja...@lucidworks.com>
Committed: Mon Jul 23 20:37:04 2018 -0400
----------------------------------------------------------------------
.../src/java/org/apache/lucene/util/LuceneTestCase.java | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6ed9607f/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
index 6be8d03..baf72c1 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
@@ -2665,6 +2665,11 @@ public abstract class LuceneTestCase extends Assert {
/** Checks a specific exception class is thrown by the given runnable, and returns it. */
public static <T extends Throwable> T expectThrows(Class<T> expectedType, ThrowingRunnable runnable) {
+ return expectThrows(expectedType, "Expected exception "+ expectedType.getSimpleName() + " but no exception was thrown", runnable);
+ }
+
+ /** Checks a specific exception class is thrown by the given runnable, and returns it. */
+ public static <T extends Throwable> T expectThrows(Class<T> expectedType, String noExceptionMessage, ThrowingRunnable runnable) {
try {
runnable.run();
} catch (Throwable e) {
@@ -2675,7 +2680,7 @@ public abstract class LuceneTestCase extends Assert {
assertion.initCause(e);
throw assertion;
}
- throw new AssertionFailedError("Expected exception " + expectedType.getSimpleName() + " but no exception was thrown");
+ throw new AssertionFailedError(noExceptionMessage);
}
/**
[17/33] lucene-solr:jira/http2: LUCENE-8412: TopFieldCollector no
longer takes a trackDocScores option.
Posted by da...@apache.org.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/test/org/apache/solr/search/TestSort.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/search/TestSort.java b/solr/core/src/test/org/apache/solr/search/TestSort.java
index f1d0817..fdb4807 100644
--- a/solr/core/src/test/org/apache/solr/search/TestSort.java
+++ b/solr/core/src/test/org/apache/solr/search/TestSort.java
@@ -282,9 +282,8 @@ public class TestSort extends SolrTestCaseJ4 {
final String nullRep = luceneSort || sortMissingFirst && !reverse || sortMissingLast && reverse ? "" : "zzz";
final String nullRep2 = luceneSort2 || sortMissingFirst2 && !reverse2 || sortMissingLast2 && reverse2 ? "" : "zzz";
- boolean trackScores = r.nextBoolean();
boolean scoreInOrder = r.nextBoolean();
- final TopFieldCollector topCollector = TopFieldCollector.create(sort, top, trackScores, true);
+ final TopFieldCollector topCollector = TopFieldCollector.create(sort, top, true);
final List<MyDoc> collectedDocs = new ArrayList<>();
// delegate and collect docs ourselves
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/55bfadbc/solr/core/src/test/org/apache/solr/uninverting/TestFieldCacheSortRandom.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/uninverting/TestFieldCacheSortRandom.java b/solr/core/src/test/org/apache/solr/uninverting/TestFieldCacheSortRandom.java
index f9653e0..4ca56e9 100644
--- a/solr/core/src/test/org/apache/solr/uninverting/TestFieldCacheSortRandom.java
+++ b/solr/core/src/test/org/apache/solr/uninverting/TestFieldCacheSortRandom.java
@@ -168,9 +168,9 @@ public class TestFieldCacheSortRandom extends LuceneTestCase {
int queryType = random.nextInt(2);
if (queryType == 0) {
hits = s.search(new ConstantScoreQuery(f),
- hitCount, sort, random.nextBoolean());
+ hitCount, sort, false);
} else {
- hits = s.search(f, hitCount, sort, random.nextBoolean());
+ hits = s.search(f, hitCount, sort, false);
}
if (VERBOSE) {
[31/33] lucene-solr:jira/http2: SOLR-11598: Fix test failure due to
ordering of sub-tests
Posted by da...@apache.org.
SOLR-11598: Fix test failure due to ordering of sub-tests
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/a254e7d7
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/a254e7d7
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/a254e7d7
Branch: refs/heads/jira/http2
Commit: a254e7d7bcd11c2163dfbb7b3d4a3986aee7867b
Parents: 98d463a
Author: Varun Thacker <va...@apache.org>
Authored: Tue Jul 24 13:08:06 2018 -0700
Committer: Varun Thacker <va...@apache.org>
Committed: Tue Jul 24 13:09:04 2018 -0700
----------------------------------------------------------------------
.../solr/handler/export/TestExportWriter.java | 31 +++++++++++++-------
1 file changed, 20 insertions(+), 11 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a254e7d7/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
index e431f47..0d1a9a0 100644
--- a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
+++ b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
@@ -55,7 +55,7 @@ public class TestExportWriter extends SolrTestCaseJ4 {
super.setUp();
assertU(delQ("*:*"));
assertU(commit());
- createIndex();
+
}
public static void createIndex() {
@@ -149,6 +149,19 @@ public class TestExportWriter extends SolrTestCaseJ4 {
}
@Test
+ public void test() throws Exception {
+ clearIndex();
+ createIndex();
+
+ testSortingOutput();
+ testExportRequiredParams();
+ testDates();
+ testDuplicates();
+
+ clearIndex();
+ }
+
+ @Test
public void testSmallChains() throws Exception {
clearIndex();
@@ -331,8 +344,7 @@ public class TestExportWriter extends SolrTestCaseJ4 {
" \"id\":\"2\"}]}}");
}
- @Test
- public void testSortingOutput() throws Exception {
+ private void testSortingOutput() throws Exception {
//Test single value DocValue output
String s = h.query(req("q", "id:1", "qt", "/export", "fl", "floatdv,intdv,stringdv,longdv,doubledv", "sort", "intdv asc"));
@@ -436,8 +448,7 @@ public class TestExportWriter extends SolrTestCaseJ4 {
assertEquals(Utils.toJSONString(Utils.fromJSONString(expected)), Utils.toJSONString(Utils.fromJSONString(actual)));
}
- @Test
- public void testExportRequiredParams() throws Exception {
+ private void testExportRequiredParams() throws Exception {
//Test whether missing required parameters returns expected errors.
@@ -451,17 +462,15 @@ public class TestExportWriter extends SolrTestCaseJ4 {
// Interesting you don't even need to specify a "q" parameter.
}
-
- @Test
- public void testDates() throws Exception {
+
+ private void testDates() throws Exception {
String s = h.query(req("q", "id:1", "qt", "/export", "fl", "datedv", "sort", "datedv asc"));
assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"datedv\":\"2017-06-16T07:00:00Z\"}]}}");
s = h.query(req("q", "id:1", "qt", "/export", "fl", "datedv_m", "sort", "datedv asc"));
assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"datedv_m\":[\"2017-06-16T01:00:00Z\",\"2017-06-16T02:00:00Z\",\"2017-06-16T03:00:00Z\",\"2017-06-16T04:00:00Z\"]}]}}");
}
-
- @Test
- public void testDuplicates() throws Exception {
+
+ private void testDuplicates() throws Exception {
// see SOLR-10924
String expected = h.getCore().getLatestSchema().getField("int_is_t").getType().isPointField()
? "1,1,1,1" : "1";
[15/33] lucene-solr:jira/http2: LUCENE-8420: Upgrade OpenNLP to 1.9.0
Posted by da...@apache.org.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/licenses/opennlp-maxent-LICENSE-ASL.txt
----------------------------------------------------------------------
diff --git a/solr/licenses/opennlp-maxent-LICENSE-ASL.txt b/solr/licenses/opennlp-maxent-LICENSE-ASL.txt
deleted file mode 100644
index d645695..0000000
--- a/solr/licenses/opennlp-maxent-LICENSE-ASL.txt
+++ /dev/null
@@ -1,202 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/licenses/opennlp-maxent-NOTICE.txt
----------------------------------------------------------------------
diff --git a/solr/licenses/opennlp-maxent-NOTICE.txt b/solr/licenses/opennlp-maxent-NOTICE.txt
deleted file mode 100644
index 9b97287..0000000
--- a/solr/licenses/opennlp-maxent-NOTICE.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-
-Apache OpenNLP Maxent
-Copyright 2013 The Apache Software Foundation
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/licenses/opennlp-tools-1.8.4.jar.sha1
----------------------------------------------------------------------
diff --git a/solr/licenses/opennlp-tools-1.8.4.jar.sha1 b/solr/licenses/opennlp-tools-1.8.4.jar.sha1
deleted file mode 100644
index 3c31e23..0000000
--- a/solr/licenses/opennlp-tools-1.8.4.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-dc1dd0bfdee4a4bc98924180da5a8e61b3a50bdd
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/34686c00/solr/licenses/opennlp-tools-1.9.0.jar.sha1
----------------------------------------------------------------------
diff --git a/solr/licenses/opennlp-tools-1.9.0.jar.sha1 b/solr/licenses/opennlp-tools-1.9.0.jar.sha1
new file mode 100644
index 0000000..d1f9393
--- /dev/null
+++ b/solr/licenses/opennlp-tools-1.9.0.jar.sha1
@@ -0,0 +1 @@
+219011f318812aa3aa88a2134721549fcc3cb56a
[04/33] lucene-solr:jira/http2: LUCENE-8408: Highlighter: Remove
obsolete private AttributeFactory instance
Posted by da...@apache.org.
LUCENE-8408: Highlighter: Remove obsolete private AttributeFactory instance
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/20a7ee9e
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/20a7ee9e
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/20a7ee9e
Branch: refs/heads/jira/http2
Commit: 20a7ee9e11f42915161a7d12857e2565040a131d
Parents: c152cae
Author: David Smiley <ds...@apache.org>
Authored: Fri Jul 20 12:33:34 2018 -0400
Committer: David Smiley <ds...@apache.org>
Committed: Fri Jul 20 12:33:34 2018 -0400
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 +++-
.../lucene/search/highlight/TokenStreamFromTermVector.java | 8 --------
2 files changed, 3 insertions(+), 9 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/20a7ee9e/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 7697cb7..8257dbc 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -177,7 +177,6 @@ Bug Fixes:
TokenStream if a token consisting entirely of delimiter characters was
encountered, but preserve_original was set. (Alan Woodward)
-
* LUCENE-8398: TieredMergePolicy.getMaxMergedSegmentMB has rounding error (Erick Erickson)
Changes in Runtime Behavior:
@@ -204,6 +203,9 @@ Other:
* LUCENE-8366: Upgrade to ICU 62.1. Emoji handling now uses Unicode 11's
Extended_Pictographic property. (Robert Muir)
+* LUCENE-8408: original Highlighter: Remove obsolete static AttributeFactory instance
+ in TokenStreamFromTermVector. (Michael Braun, David Smiley)
+
======================= Lucene 7.4.1 =======================
Bug Fixes:
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/20a7ee9e/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java
----------------------------------------------------------------------
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java
index 135bfe8..6353930 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java
@@ -21,13 +21,11 @@ import java.io.IOException;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
-import org.apache.lucene.analysis.tokenattributes.PackedTokenAttributeImpl;
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
-import org.apache.lucene.util.AttributeFactory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefArray;
import org.apache.lucene.util.BytesRefBuilder;
@@ -52,11 +50,6 @@ import org.apache.lucene.util.UnicodeUtil;
*/
public final class TokenStreamFromTermVector extends TokenStream {
- //This attribute factory uses less memory when captureState() is called.
- public static final AttributeFactory ATTRIBUTE_FACTORY =
- AttributeFactory.getStaticImplementation(
- AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY, PackedTokenAttributeImpl.class);
-
private final Terms vector;
private final CharTermAttribute termAttribute;
@@ -89,7 +82,6 @@ public final class TokenStreamFromTermVector extends TokenStream {
* @param maxStartOffset if a token's start offset exceeds this then the token is not added. -1 disables the limit.
*/
public TokenStreamFromTermVector(Terms vector, int maxStartOffset) throws IOException {
- super(ATTRIBUTE_FACTORY);
this.maxStartOffset = maxStartOffset < 0 ? Integer.MAX_VALUE : maxStartOffset;
assert !hasAttribute(PayloadAttribute.class) : "AttributeFactory shouldn't have payloads *yet*";
if (!vector.hasPositions() && !vector.hasOffsets()) {
[19/33] lucene-solr:jira/http2: Merge branch 'master' of
https://git-wip-us.apache.org/repos/asf/lucene-solr into jira/http2
Posted by da...@apache.org.
Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/lucene-solr into jira/http2
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/1d1ef152
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/1d1ef152
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/1d1ef152
Branch: refs/heads/jira/http2
Commit: 1d1ef152d33fda8364bd72f5f27947871481eb7d
Parents: 3358d93 55bfadb
Author: Cao Manh Dat <da...@apache.org>
Authored: Mon Jul 23 14:22:37 2018 +0700
Committer: Cao Manh Dat <da...@apache.org>
Committed: Mon Jul 23 14:22:37 2018 +0700
----------------------------------------------------------------------
lucene/CHANGES.txt | 13 +-
lucene/MIGRATE.txt | 7 +
lucene/analysis/opennlp/build.xml | 16 +-
lucene/analysis/opennlp/ivy.xml | 1 -
.../lucene/analysis/opennlp/en-test-chunker.bin | Bin 89915 -> 89914 bytes
.../analysis/opennlp/en-test-lemmatizer.bin | Bin 7370 -> 7370 bytes
.../analysis/opennlp/en-test-ner-person.bin | Bin 1700 -> 0 bytes
.../lucene/analysis/opennlp/en-test-ner.bin | Bin 0 -> 2049 bytes
.../analysis/opennlp/en-test-pos-maxent.bin | Bin 18424 -> 18494 bytes
.../lucene/analysis/opennlp/en-test-sent.bin | Bin 1050 -> 1051 bytes
.../analysis/opennlp/en-test-tokenizer.bin | Bin 15096 -> 15100 bytes
.../opennlp/src/tools/test-model-data/ner.txt | 143 ++
.../src/tools/test-model-data/ner_flashman.txt | 143 --
.../lucene/benchmark/byTask/tasks/ReadTask.java | 7 -
.../byTask/tasks/SearchWithSortTask.java | 9 -
.../org/apache/lucene/search/IndexSearcher.java | 8 +-
.../org/apache/lucene/search/SortRescorer.java | 21 +-
.../apache/lucene/search/TopFieldCollector.java | 118 +-
.../apache/lucene/index/TestIndexSorting.java | 4 +-
.../org/apache/lucene/search/TestBoolean2.java | 8 +-
.../lucene/search/TestElevationComparator.java | 2 +-
.../apache/lucene/search/TestSortRandom.java | 2 +-
.../apache/lucene/search/TestTopDocsMerge.java | 4 +-
.../lucene/search/TestTopFieldCollector.java | 179 +-
.../TestTopFieldCollectorEarlyTermination.java | 5 +-
.../apache/lucene/util/TestPriorityQueue.java | 170 +-
.../org/apache/lucene/facet/DrillSideways.java | 16 +-
.../apache/lucene/facet/FacetsCollector.java | 4 +-
.../search/grouping/BlockGroupingCollector.java | 2 +-
.../lucene/search/grouping/GroupingSearch.java | 17 +-
.../search/grouping/TopGroupsCollector.java | 11 +-
.../lucene/search/grouping/TestGrouping.java | 55 +-
.../highlight/TokenStreamFromTermVector.java | 8 -
lucene/ivy-versions.properties | 3 +-
lucene/licenses/opennlp-maxent-3.0.3.jar.sha1 | 1 -
lucene/licenses/opennlp-maxent-LICENSE-ASL.txt | 202 --
lucene/licenses/opennlp-maxent-NOTICE.txt | 6 -
lucene/licenses/opennlp-tools-1.8.4.jar.sha1 | 1 -
lucene/licenses/opennlp-tools-1.9.0.jar.sha1 | 1 +
.../apache/lucene/document/TestLatLonShape.java | 37 +-
.../analyzing/AnalyzingInfixSuggester.java | 2 +-
solr/CHANGES.txt | 9 +
solr/contrib/analysis-extras/ivy.xml | 1 -
.../collection1/conf/en-test-ner-person.bin | Bin 1700 -> 0 bytes
.../solr/collection1/conf/en-test-ner.bin | Bin 0 -> 2049 bytes
.../solr/collection1/conf/en-test-sent.bin | Bin 1050 -> 1051 bytes
.../solr/collection1/conf/en-test-tokenizer.bin | Bin 15096 -> 15100 bytes
.../conf/solrconfig-opennlp-extract.xml | 30 +-
.../TestSolrEntityProcessorEndToEnd.java | 3 +-
.../org/apache/solr/handler/ExportHandler.java | 1 +
.../org/apache/solr/handler/ExportWriter.java | 1764 ------------------
.../solr/handler/component/ExpandComponent.java | 4 +-
.../solr/handler/component/QueryComponent.java | 1 +
.../solr/handler/export/BoolFieldWriter.java | 52 +
.../solr/handler/export/DateFieldWriter.java | 46 +
.../apache/solr/handler/export/DoubeValue.java | 81 +
.../apache/solr/handler/export/DoubleCmp.java | 43 +
.../solr/handler/export/DoubleFieldWriter.java | 45 +
.../solr/handler/export/ExportWriter.java | 448 +++++
.../apache/solr/handler/export/FieldWriter.java | 27 +
.../apache/solr/handler/export/FloatCmp.java | 44 +
.../solr/handler/export/FloatFieldWriter.java | 45 +
.../apache/solr/handler/export/FloatValue.java | 78 +
.../org/apache/solr/handler/export/IntComp.java | 45 +
.../solr/handler/export/IntFieldWriter.java | 45 +
.../apache/solr/handler/export/IntValue.java | 77 +
.../org/apache/solr/handler/export/LongCmp.java | 45 +
.../solr/handler/export/LongFieldWriter.java | 45 +
.../apache/solr/handler/export/LongValue.java | 78 +
.../solr/handler/export/MultiFieldWriter.java | 104 ++
.../solr/handler/export/PriorityQueue.java | 218 +++
.../org/apache/solr/handler/export/SortDoc.java | 114 ++
.../apache/solr/handler/export/SortQueue.java | 52 +
.../apache/solr/handler/export/SortValue.java | 30 +
.../solr/handler/export/StringFieldWriter.java | 52 +
.../apache/solr/handler/export/StringValue.java | 99 +
.../solr/handler/export/package-info.java | 23 +
.../java/org/apache/solr/search/Grouping.java | 24 +-
.../org/apache/solr/search/ReRankCollector.java | 15 +-
.../search/SignificantTermsQParserPlugin.java | 14 +-
.../apache/solr/search/SolrIndexSearcher.java | 9 +-
.../apache/solr/search/grouping/Command.java | 7 +
.../solr/search/grouping/CommandHandler.java | 4 +
.../distributed/command/QueryCommand.java | 14 +-
.../command/TopGroupsFieldCommand.java | 42 +-
.../processor/DistributedUpdateProcessor.java | 19 +-
.../collection1/conf/schema-sortingresponse.xml | 5 +-
.../apache/solr/cloud/MoveReplicaHDFSTest.java | 1 +
.../apache/solr/cloud/MultiThreadedOCPTest.java | 2 +-
.../solr/cloud/ReplicationFactorTest.java | 1 +
.../cloud/SharedFSAutoReplicaFailoverTest.java | 3 +
.../apache/solr/cloud/TestCloudRecovery.java | 1 +
.../cloud/TestPullReplicaErrorHandling.java | 3 +-
.../TestStressCloudBlindAtomicUpdates.java | 1 +
.../AbstractCloudBackupRestoreTestCase.java | 20 +-
.../HdfsAutoAddReplicasIntegrationTest.java | 1 +
.../cloud/autoscaling/ScheduledTriggerTest.java | 1 +
.../sim/TestSimDistributedQueue.java | 2 +-
.../autoscaling/sim/TestTriggerIntegration.java | 2 +-
.../cloud/hdfs/HdfsBasicDistributedZk2Test.java | 3 +-
.../cloud/hdfs/HdfsBasicDistributedZkTest.java | 3 +-
...HdfsTlogReplayBufferedWhileIndexingTest.java | 2 +
.../apache/solr/core/TestDynamicLoading.java | 1 +
.../solr/handler/TestReplicationHandler.java | 3 +-
.../admin/MetricsHistoryHandlerTest.java | 2 +
.../solr/handler/export/TestExportWriter.java | 749 ++++++++
.../apache/solr/response/TestExportWriter.java | 370 ----
.../test/org/apache/solr/search/TestSort.java | 3 +-
.../TestSolrCloudWithHadoopAuthPlugin.java | 3 +-
.../uninverting/TestFieldCacheSortRandom.java | 4 +-
.../DistributedUpdateProcessorTest.java | 54 +
.../processor/TestNamedUpdateProcessors.java | 1 +
solr/licenses/opennlp-maxent-3.0.3.jar.sha1 | 1 -
solr/licenses/opennlp-maxent-LICENSE-ASL.txt | 202 --
solr/licenses/opennlp-maxent-NOTICE.txt | 6 -
solr/licenses/opennlp-tools-1.8.4.jar.sha1 | 1 -
solr/licenses/opennlp-tools-1.9.0.jar.sha1 | 1 +
.../src/exporting-result-sets.adoc | 3 +-
.../src/parallel-sql-interface.adoc | 4 -
solr/solr-ref-guide/src/result-grouping.adoc | 9 +-
.../org/apache/solr/common/SolrException.java | 2 +-
.../solrj/io/stream/MathExpressionTest.java | 1 +
.../solrj/io/stream/StreamDecoratorTest.java | 1 +
.../cloud/TestCollectionStateWatchers.java | 10 +-
124 files changed, 3458 insertions(+), 3147 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1d1ef152/lucene/ivy-versions.properties
----------------------------------------------------------------------
[26/33] lucene-solr:jira/http2: LUCENE-8415: Clean up Directory
contracts (write-once,
no reads-before-write-completed). Minor test improvements and cleanups.
Posted by da...@apache.org.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java
index bb9b711..4270424 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java
@@ -19,6 +19,9 @@ package org.apache.lucene.store;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.AccessDeniedException;
+import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
@@ -29,201 +32,195 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Random;
import java.util.Set;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import java.util.zip.CRC32;
+import com.carrotsearch.randomizedtesting.RandomizedTest;
+import com.carrotsearch.randomizedtesting.generators.RandomBytes;
+import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.IndexNotFoundException;
+import org.apache.lucene.mockfile.ExtrasFS;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
+import org.junit.Assert;
-/** Base class for per-Directory tests. */
-
+/**
+ * Base class for per-Directory tests.
+ */
public abstract class BaseDirectoryTestCase extends LuceneTestCase {
- /** Subclass returns the Directory to be tested; if it's
+ /** A subclass returns the Directory to be tested; if it's
* an FS-based directory it should point to the specified
* path, else it can ignore it. */
protected abstract Directory getDirectory(Path path) throws IOException;
-
- // first some basic tests for the directory api
-
+
public void testCopyFrom() throws Exception {
- Directory source = getDirectory(createTempDir("testCopy"));
- Directory dest = newDirectory();
-
- IndexOutput output = source.createOutput("foobar", newIOContext(random()));
- int numBytes = random().nextInt(20000);
- byte bytes[] = new byte[numBytes];
- random().nextBytes(bytes);
- output.writeBytes(bytes, bytes.length);
- output.close();
-
- dest.copyFrom(source, "foobar", "foobaz", newIOContext(random()));
- assertTrue(slowFileExists(dest, "foobaz"));
-
- IndexInput input = dest.openInput("foobaz", newIOContext(random()));
- byte bytes2[] = new byte[numBytes];
- input.readBytes(bytes2, 0, bytes2.length);
- assertEquals(input.length(), numBytes);
- input.close();
-
- assertArrayEquals(bytes, bytes2);
-
- IOUtils.close(source, dest);
+ try (Directory source = getDirectory(createTempDir("testCopy"));
+ Directory dest = newDirectory()) {
+ runCopyFrom(source, dest);
+ }
+
+ try (Directory source = newDirectory();
+ Directory dest = getDirectory(createTempDir("testCopyDestination"))) {
+ runCopyFrom(source, dest);
+ }
}
-
- public void testCopyFromDestination() throws Exception {
- Directory source = newDirectory();
- Directory dest = getDirectory(createTempDir("testCopyDestination"));
-
+
+ private void runCopyFrom(Directory source, Directory dest) throws IOException {
IndexOutput output = source.createOutput("foobar", newIOContext(random()));
- int numBytes = random().nextInt(20000);
- byte bytes[] = new byte[numBytes];
- random().nextBytes(bytes);
+
+ byte bytes[] = RandomBytes.randomBytesOfLength(random(), 20000);
output.writeBytes(bytes, bytes.length);
output.close();
-
+
dest.copyFrom(source, "foobar", "foobaz", newIOContext(random()));
assertTrue(slowFileExists(dest, "foobaz"));
-
+
IndexInput input = dest.openInput("foobaz", newIOContext(random()));
- byte bytes2[] = new byte[numBytes];
+ byte bytes2[] = new byte[bytes.length];
input.readBytes(bytes2, 0, bytes2.length);
- assertEquals(input.length(), numBytes);
input.close();
-
+
assertArrayEquals(bytes, bytes2);
-
- IOUtils.close(source, dest);
}
-
+
public void testRename() throws Exception {
- Directory dir = getDirectory(createTempDir("testRename"));
-
- IndexOutput output = dir.createOutput("foobar", newIOContext(random()));
- int numBytes = random().nextInt(20000);
- byte bytes[] = new byte[numBytes];
- random().nextBytes(bytes);
- output.writeBytes(bytes, bytes.length);
- output.close();
-
- dir.rename("foobar", "foobaz");
-
- IndexInput input = dir.openInput("foobaz", newIOContext(random()));
- byte bytes2[] = new byte[numBytes];
- input.readBytes(bytes2, 0, bytes2.length);
- assertEquals(input.length(), numBytes);
- input.close();
-
- assertArrayEquals(bytes, bytes2);
-
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testRename"))) {
+ IndexOutput output = dir.createOutput("foobar", newIOContext(random()));
+ int numBytes = random().nextInt(20000);
+ byte bytes[] = new byte[numBytes];
+ random().nextBytes(bytes);
+ output.writeBytes(bytes, bytes.length);
+ output.close();
+
+ dir.rename("foobar", "foobaz");
+
+ IndexInput input = dir.openInput("foobaz", newIOContext(random()));
+ byte bytes2[] = new byte[numBytes];
+ input.readBytes(bytes2, 0, bytes2.length);
+ assertEquals(input.length(), numBytes);
+ input.close();
+
+ assertArrayEquals(bytes, bytes2);
+ }
}
-
+
public void testDeleteFile() throws Exception {
- Directory dir = getDirectory(createTempDir("testDeleteFile"));
- int count = dir.listAll().length;
- dir.createOutput("foo.txt", IOContext.DEFAULT).close();
- assertEquals(count+1, dir.listAll().length);
- dir.deleteFile("foo.txt");
- assertEquals(count, dir.listAll().length);
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testDeleteFile"))) {
+ String file = "foo.txt";
+ Assert.assertFalse(Arrays.asList(dir.listAll()).contains(file));
+
+ dir.createOutput("foo.txt", IOContext.DEFAULT).close();
+ Assert.assertTrue(Arrays.asList(dir.listAll()).contains(file));
+
+ dir.deleteFile("foo.txt");
+ Assert.assertFalse(Arrays.asList(dir.listAll()).contains(file));
+
+ expectThrowsAnyOf(Arrays.asList(NoSuchFileException.class, FileNotFoundException.class), () -> {
+ dir.deleteFile("foo.txt");
+ });
+ }
}
-
+
public void testByte() throws Exception {
- Directory dir = getDirectory(createTempDir("testByte"));
- IndexOutput output = dir.createOutput("byte", newIOContext(random()));
- output.writeByte((byte)128);
- output.close();
-
- IndexInput input = dir.openInput("byte", newIOContext(random()));
- assertEquals(1, input.length());
- assertEquals((byte)128, input.readByte());
- input.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testByte"))) {
+ IndexOutput output = dir.createOutput("byte", newIOContext(random()));
+ output.writeByte((byte) 128);
+ output.close();
+
+ IndexInput input = dir.openInput("byte", newIOContext(random()));
+ assertEquals(1, input.length());
+ assertEquals((byte) 128, input.readByte());
+ input.close();
+ }
}
-
+
public void testShort() throws Exception {
- Directory dir = getDirectory(createTempDir("testShort"));
- IndexOutput output = dir.createOutput("short", newIOContext(random()));
- output.writeShort((short)-20);
- output.close();
-
- IndexInput input = dir.openInput("short", newIOContext(random()));
- assertEquals(2, input.length());
- assertEquals((short)-20, input.readShort());
- input.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testShort"))) {
+ IndexOutput output = dir.createOutput("short", newIOContext(random()));
+ output.writeShort((short) -20);
+ output.close();
+
+ IndexInput input = dir.openInput("short", newIOContext(random()));
+ assertEquals(2, input.length());
+ assertEquals((short) -20, input.readShort());
+ input.close();
+ }
}
-
+
public void testInt() throws Exception {
- Directory dir = getDirectory(createTempDir("testInt"));
- IndexOutput output = dir.createOutput("int", newIOContext(random()));
- output.writeInt(-500);
- output.close();
-
- IndexInput input = dir.openInput("int", newIOContext(random()));
- assertEquals(4, input.length());
- assertEquals(-500, input.readInt());
- input.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testInt"))) {
+ IndexOutput output = dir.createOutput("int", newIOContext(random()));
+ output.writeInt(-500);
+ output.close();
+
+ IndexInput input = dir.openInput("int", newIOContext(random()));
+ assertEquals(4, input.length());
+ assertEquals(-500, input.readInt());
+ input.close();
+ }
}
-
+
public void testLong() throws Exception {
- Directory dir = getDirectory(createTempDir("testLong"));
- IndexOutput output = dir.createOutput("long", newIOContext(random()));
- output.writeLong(-5000);
- output.close();
-
- IndexInput input = dir.openInput("long", newIOContext(random()));
- assertEquals(8, input.length());
- assertEquals(-5000L, input.readLong());
- input.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testLong"))) {
+ IndexOutput output = dir.createOutput("long", newIOContext(random()));
+ output.writeLong(-5000);
+ output.close();
+
+ IndexInput input = dir.openInput("long", newIOContext(random()));
+ assertEquals(8, input.length());
+ assertEquals(-5000L, input.readLong());
+ input.close();
+ }
}
-
+
public void testString() throws Exception {
- Directory dir = getDirectory(createTempDir("testString"));
- IndexOutput output = dir.createOutput("string", newIOContext(random()));
- output.writeString("hello!");
- output.close();
-
- IndexInput input = dir.openInput("string", newIOContext(random()));
- assertEquals("hello!", input.readString());
- assertEquals(7, input.length());
- input.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testString"))) {
+ IndexOutput output = dir.createOutput("string", newIOContext(random()));
+ output.writeString("hello!");
+ output.close();
+
+ IndexInput input = dir.openInput("string", newIOContext(random()));
+ assertEquals("hello!", input.readString());
+ assertEquals(7, input.length());
+ input.close();
+ }
}
-
+
public void testVInt() throws Exception {
- Directory dir = getDirectory(createTempDir("testVInt"));
- IndexOutput output = dir.createOutput("vint", newIOContext(random()));
- output.writeVInt(500);
- output.close();
-
- IndexInput input = dir.openInput("vint", newIOContext(random()));
- assertEquals(2, input.length());
- assertEquals(500, input.readVInt());
- input.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testVInt"))) {
+ IndexOutput output = dir.createOutput("vint", newIOContext(random()));
+ output.writeVInt(500);
+ output.close();
+
+ IndexInput input = dir.openInput("vint", newIOContext(random()));
+ assertEquals(2, input.length());
+ assertEquals(500, input.readVInt());
+ input.close();
+ }
}
-
+
public void testVLong() throws Exception {
- Directory dir = getDirectory(createTempDir("testVLong"));
- IndexOutput output = dir.createOutput("vlong", newIOContext(random()));
- output.writeVLong(Long.MAX_VALUE);
- output.close();
-
- IndexInput input = dir.openInput("vlong", newIOContext(random()));
- assertEquals(9, input.length());
- assertEquals(Long.MAX_VALUE, input.readVLong());
- input.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testVLong"))) {
+ IndexOutput output = dir.createOutput("vlong", newIOContext(random()));
+ output.writeVLong(Long.MAX_VALUE);
+ output.close();
+
+ IndexInput input = dir.openInput("vlong", newIOContext(random()));
+ assertEquals(9, input.length());
+ assertEquals(Long.MAX_VALUE, input.readVLong());
+ input.close();
+ }
}
-
+
public void testZInt() throws Exception {
final int[] ints = new int[random().nextInt(10)];
for (int i = 0; i < ints.length; ++i) {
@@ -241,22 +238,23 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {
throw new AssertionError();
}
}
- Directory dir = getDirectory(createTempDir("testZInt"));
- IndexOutput output = dir.createOutput("zint", newIOContext(random()));
- for (int i : ints) {
- output.writeZInt(i);
- }
- output.close();
-
- IndexInput input = dir.openInput("zint", newIOContext(random()));
- for (int i : ints) {
- assertEquals(i, input.readZInt());
+
+ try (Directory dir = getDirectory(createTempDir("testZInt"))) {
+ IndexOutput output = dir.createOutput("zint", newIOContext(random()));
+ for (int i : ints) {
+ output.writeZInt(i);
+ }
+ output.close();
+
+ IndexInput input = dir.openInput("zint", newIOContext(random()));
+ for (int i : ints) {
+ assertEquals(i, input.readZInt());
+ }
+ assertEquals(input.length(), input.getFilePointer());
+ input.close();
}
- assertEquals(input.length(), input.getFilePointer());
- input.close();
- dir.close();
}
-
+
public void testZLong() throws Exception {
final long[] longs = new long[random().nextInt(10)];
for (int i = 0; i < longs.length; ++i) {
@@ -274,97 +272,98 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {
throw new AssertionError();
}
}
- Directory dir = getDirectory(createTempDir("testZLong"));
- IndexOutput output = dir.createOutput("zlong", newIOContext(random()));
- for (long l : longs) {
- output.writeZLong(l);
- }
- output.close();
-
- IndexInput input = dir.openInput("zlong", newIOContext(random()));
- for (long l : longs) {
- assertEquals(l, input.readZLong());
+
+ try (Directory dir = getDirectory(createTempDir("testZLong"))) {
+ IndexOutput output = dir.createOutput("zlong", newIOContext(random()));
+ for (long l : longs) {
+ output.writeZLong(l);
+ }
+ output.close();
+
+ IndexInput input = dir.openInput("zlong", newIOContext(random()));
+ for (long l : longs) {
+ assertEquals(l, input.readZLong());
+ }
+ assertEquals(input.length(), input.getFilePointer());
+ input.close();
}
- assertEquals(input.length(), input.getFilePointer());
- input.close();
- dir.close();
}
public void testSetOfStrings() throws Exception {
- Directory dir = getDirectory(createTempDir("testSetOfStrings"));
-
- IndexOutput output = dir.createOutput("stringset", newIOContext(random()));
- output.writeSetOfStrings(asSet("test1", "test2"));
- output.writeSetOfStrings(Collections.emptySet());
- output.writeSetOfStrings(asSet("test3"));
- output.close();
-
- IndexInput input = dir.openInput("stringset", newIOContext(random()));
- Set<String> set1 = input.readSetOfStrings();
- assertEquals(asSet("test1", "test2"), set1);
- // set should be immutable
- expectThrows(UnsupportedOperationException.class, () -> {
- set1.add("bogus");
- });
-
- Set<String> set2 = input.readSetOfStrings();
- assertEquals(Collections.emptySet(), set2);
- // set should be immutable
- expectThrows(UnsupportedOperationException.class, () -> {
- set2.add("bogus");
- });
-
- Set<String> set3 = input.readSetOfStrings();
- assertEquals(Collections.singleton("test3"), set3);
- // set should be immutable
- expectThrows(UnsupportedOperationException.class, () -> {
- set3.add("bogus");
- });
-
- assertEquals(input.length(), input.getFilePointer());
- input.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testSetOfStrings"))) {
+
+ IndexOutput output = dir.createOutput("stringset", newIOContext(random()));
+ output.writeSetOfStrings(asSet("test1", "test2"));
+ output.writeSetOfStrings(Collections.emptySet());
+ output.writeSetOfStrings(asSet("test3"));
+ output.close();
+
+ IndexInput input = dir.openInput("stringset", newIOContext(random()));
+ Set<String> set1 = input.readSetOfStrings();
+ assertEquals(asSet("test1", "test2"), set1);
+ // set should be immutable
+ expectThrows(UnsupportedOperationException.class, () -> {
+ set1.add("bogus");
+ });
+
+ Set<String> set2 = input.readSetOfStrings();
+ assertEquals(Collections.emptySet(), set2);
+ // set should be immutable
+ expectThrows(UnsupportedOperationException.class, () -> {
+ set2.add("bogus");
+ });
+
+ Set<String> set3 = input.readSetOfStrings();
+ assertEquals(Collections.singleton("test3"), set3);
+ // set should be immutable
+ expectThrows(UnsupportedOperationException.class, () -> {
+ set3.add("bogus");
+ });
+
+ assertEquals(input.length(), input.getFilePointer());
+ input.close();
+ }
}
-
+
public void testMapOfStrings() throws Exception {
Map<String,String> m = new HashMap<>();
m.put("test1", "value1");
m.put("test2", "value2");
-
- Directory dir = getDirectory(createTempDir("testMapOfStrings"));
- IndexOutput output = dir.createOutput("stringmap", newIOContext(random()));
- output.writeMapOfStrings(m);
- output.writeMapOfStrings(Collections.emptyMap());
- output.writeMapOfStrings(Collections.singletonMap("key", "value"));
- output.close();
-
- IndexInput input = dir.openInput("stringmap", newIOContext(random()));
- Map<String,String> map1 = input.readMapOfStrings();
- assertEquals(m, map1);
- // map should be immutable
- expectThrows(UnsupportedOperationException.class, () -> {
- map1.put("bogus1", "bogus2");
- });
-
- Map<String,String> map2 = input.readMapOfStrings();
- assertEquals(Collections.emptyMap(), map2);
- // map should be immutable
- expectThrows(UnsupportedOperationException.class, () -> {
- map2.put("bogus1", "bogus2");
- });
-
- Map<String,String> map3 = input.readMapOfStrings();
- assertEquals(Collections.singletonMap("key", "value"), map3);
- // map should be immutable
- expectThrows(UnsupportedOperationException.class, () -> {
- map3.put("bogus1", "bogus2");
- });
-
- assertEquals(input.length(), input.getFilePointer());
- input.close();
- dir.close();
+
+ try (Directory dir = getDirectory(createTempDir("testMapOfStrings"))) {
+ IndexOutput output = dir.createOutput("stringmap", newIOContext(random()));
+ output.writeMapOfStrings(m);
+ output.writeMapOfStrings(Collections.emptyMap());
+ output.writeMapOfStrings(Collections.singletonMap("key", "value"));
+ output.close();
+
+ IndexInput input = dir.openInput("stringmap", newIOContext(random()));
+ Map<String, String> map1 = input.readMapOfStrings();
+ assertEquals(m, map1);
+ // map should be immutable
+ expectThrows(UnsupportedOperationException.class, () -> {
+ map1.put("bogus1", "bogus2");
+ });
+
+ Map<String, String> map2 = input.readMapOfStrings();
+ assertEquals(Collections.emptyMap(), map2);
+ // map should be immutable
+ expectThrows(UnsupportedOperationException.class, () -> {
+ map2.put("bogus1", "bogus2");
+ });
+
+ Map<String, String> map3 = input.readMapOfStrings();
+ assertEquals(Collections.singletonMap("key", "value"), map3);
+ // map should be immutable
+ expectThrows(UnsupportedOperationException.class, () -> {
+ map3.put("bogus1", "bogus2");
+ });
+
+ assertEquals(input.length(), input.getFilePointer());
+ input.close();
+ }
}
-
+
// TODO: fold in some of the testing of o.a.l.index.TestIndexInput in here!
public void testChecksum() throws Exception {
CRC32 expected = new CRC32();
@@ -372,650 +371,594 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {
byte bytes[] = new byte[numBytes];
random().nextBytes(bytes);
expected.update(bytes);
-
- Directory dir = getDirectory(createTempDir("testChecksum"));
- IndexOutput output = dir.createOutput("checksum", newIOContext(random()));
- output.writeBytes(bytes, 0, bytes.length);
- output.close();
-
- ChecksumIndexInput input = dir.openChecksumInput("checksum", newIOContext(random()));
- input.skipBytes(numBytes);
-
- assertEquals(expected.getValue(), input.getChecksum());
- input.close();
- dir.close();
+
+ try (Directory dir = getDirectory(createTempDir("testChecksum"))) {
+ IndexOutput output = dir.createOutput("checksum", newIOContext(random()));
+ output.writeBytes(bytes, 0, bytes.length);
+ output.close();
+
+ ChecksumIndexInput input = dir.openChecksumInput("checksum", newIOContext(random()));
+ input.skipBytes(numBytes);
+
+ assertEquals(expected.getValue(), input.getChecksum());
+ input.close();
+ }
}
-
+
/** Make sure directory throws AlreadyClosedException if
* you try to createOutput after closing. */
public void testDetectClose() throws Throwable {
Directory dir = getDirectory(createTempDir("testDetectClose"));
dir.close();
- expectThrows(AlreadyClosedException.class, () -> {
+
+ expectThrows(AlreadyClosedException.class, () -> {
dir.createOutput("test", newIOContext(random()));
});
}
-
- public void testThreadSafety() throws Exception {
- final Directory dir = getDirectory(createTempDir("testThreadSafety"));
- if (dir instanceof BaseDirectoryWrapper) {
- ((BaseDirectoryWrapper)dir).setCheckIndexOnClose(false); // we arent making an index
- }
- if (dir instanceof MockDirectoryWrapper) {
- ((MockDirectoryWrapper)dir).setThrottling(MockDirectoryWrapper.Throttling.NEVER); // makes this test really slow
- }
-
- if (VERBOSE) {
- System.out.println(dir);
- }
-
- class TheThread extends Thread {
- private String name;
- public TheThread(String name) {
- this.name = name;
+ public void testThreadSafetyInListAll() throws Exception {
+ try (Directory dir = getDirectory(createTempDir("testThreadSafety"))) {
+ if (dir instanceof BaseDirectoryWrapper) {
+ // we are not making a real index, just writing, reading files.
+ ((BaseDirectoryWrapper) dir).setCheckIndexOnClose(false);
+ }
+ if (dir instanceof MockDirectoryWrapper) {
+ // makes this test really slow
+ ((MockDirectoryWrapper) dir).setThrottling(MockDirectoryWrapper.Throttling.NEVER);
}
-
- @Override
- public void run() {
- for (int i = 0; i < 1000; i++) {
- String fileName = this.name + i;
- try {
- //System.out.println("create:" + fileName);
- IndexOutput output = dir.createOutput(fileName, newIOContext(random()));
- output.close();
+
+ AtomicBoolean stop = new AtomicBoolean();
+ Thread writer = new Thread(() -> {
+ try {
+ Random rnd = new Random(RandomizedTest.randomLong() + 1);
+ for (int i = 0, max = RandomizedTest.randomIntBetween(500, 1000); i < max; i++) {
+ String fileName = "file-" + i;
+ try (IndexOutput output = dir.createOutput(fileName, newIOContext(random()))) {
+ // Add some lags so that the other thread can read the content of the directory.
+ Thread.yield();
+ }
assertTrue(slowFileExists(dir, fileName));
- } catch (IOException e) {
- throw new RuntimeException(e);
}
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ } finally {
+ stop.set(true);
}
- }
- };
-
- class TheThread2 extends Thread {
- private String name;
- private volatile boolean stop;
-
- public TheThread2(String name) {
- this.name = name;
- }
-
- @Override
- public void run() {
- while (stop == false) {
- try {
- String[] files = dir.listAll();
- for (String file : files) {
- if (!file.startsWith(name)) {
- continue;
- }
- //System.out.println("file:" + file);
- try {
- IndexInput input = dir.openInput(file, newIOContext(random()));
- input.close();
- } catch (FileNotFoundException | NoSuchFileException e) {
- // ignore
- } catch (IOException e) {
- if (e.getMessage() != null && e.getMessage().contains("still open for writing")) {
- // ignore
- } else {
- throw new RuntimeException(e);
+ });
+
+ Thread reader = new Thread(() -> {
+ try {
+ Random rnd = new Random(RandomizedTest.randomLong());
+ while (!stop.get()) {
+ String [] files = Arrays.stream(dir.listAll())
+ .filter(name -> !ExtrasFS.isExtra(name)) // Ignore anything from ExtraFS.
+ .toArray(String[]::new);
+
+ if (files.length > 0) {
+ do {
+ String file = RandomPicks.randomFrom(rnd, files);
+ try (IndexInput input = dir.openInput(file, newIOContext(random()))) {
+ // Just open, nothing else.
+ } catch (AccessDeniedException e) {
+ // Access denied is allowed for files for which the output is still open.
+ // Since we don't synchronize with the writer thread, just ignore it.
+ } catch (IOException e) {
+ throw new UncheckedIOException("Something went wrong when opening: " + file, e);
}
- }
- if (random().nextBoolean()) {
- break;
- }
+ } while (rnd.nextInt(3) != 0); // Sometimes break and list files again.
}
- } catch (IOException e) {
- throw new RuntimeException(e);
}
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
}
- }
- };
-
- TheThread theThread = new TheThread("t1");
- TheThread2 theThread2 = new TheThread2("t2");
- theThread.start();
- theThread2.start();
-
- theThread.join();
-
- // after first thread is done, no sense in waiting on thread 2
- // to listFiles() and loop over and over
- theThread2.stop = true;
- theThread2.join();
-
- dir.close();
+ });
+
+ reader.start();
+ writer.start();
+
+ writer.join();
+ reader.join();
+ }
}
- /** LUCENE-1468: once we create an output, we should see
- * it in the dir listing and be able to open it with
- * openInput. */
- public void testDirectoryFilter() throws IOException {
- String name = "file";
- Directory dir = getDirectory(createTempDir("testDirectoryFilter"));
- try {
+ /**
+ * LUCENE-1468: once we create an output, we should see
+ * it in the dir listing.
+ */
+ public void testFileExistsInListAfterCreated() throws IOException {
+ try (Directory dir = getDirectory(createTempDir("testFileExistsInListAfterCreated"))) {
+ String name = "file";
dir.createOutput(name, newIOContext(random())).close();
assertTrue(slowFileExists(dir, name));
assertTrue(Arrays.asList(dir.listAll()).contains(name));
- } finally {
- dir.close();
}
}
// LUCENE-2852
public void testSeekToEOFThenBack() throws Exception {
- Directory dir = getDirectory(createTempDir("testSeekToEOFThenBack"));
-
- IndexOutput o = dir.createOutput("out", newIOContext(random()));
- byte[] bytes = new byte[3*RAMOutputStream.BUFFER_SIZE];
- o.writeBytes(bytes, 0, bytes.length);
- o.close();
-
- IndexInput i = dir.openInput("out", newIOContext(random()));
- i.seek(2*RAMOutputStream.BUFFER_SIZE-1);
- i.seek(3*RAMOutputStream.BUFFER_SIZE);
- i.seek(RAMOutputStream.BUFFER_SIZE);
- i.readBytes(bytes, 0, 2*RAMOutputStream.BUFFER_SIZE);
- i.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testSeekToEOFThenBack"))) {
+ int bufferLength = 1024;
+ IndexOutput o = dir.createOutput("out", newIOContext(random()));
+ byte[] bytes = new byte[3 * bufferLength];
+ o.writeBytes(bytes, 0, bytes.length);
+ o.close();
+
+ IndexInput i = dir.openInput("out", newIOContext(random()));
+ i.seek(2 * bufferLength - 1);
+ i.seek(3 * bufferLength);
+ i.seek(bufferLength);
+ i.readBytes(bytes, 0, 2 * bufferLength);
+ i.close();
+ }
}
// LUCENE-1196
public void testIllegalEOF() throws Exception {
- Directory dir = getDirectory(createTempDir("testIllegalEOF"));
- IndexOutput o = dir.createOutput("out", newIOContext(random()));
- byte[] b = new byte[1024];
- o.writeBytes(b, 0, 1024);
- o.close();
- IndexInput i = dir.openInput("out", newIOContext(random()));
- i.seek(1024);
- i.close();
- dir.close();
+ try (Directory dir = getDirectory(createTempDir("testIllegalEOF"))) {
+ IndexOutput o = dir.createOutput("out", newIOContext(random()));
+ byte[] b = new byte[1024];
+ o.writeBytes(b, 0, 1024);
+ o.close();
+ IndexInput i = dir.openInput("out", newIOContext(random()));
+ i.seek(1024);
+ i.close();
+ }
}
public void testSeekPastEOF() throws Exception {
- Directory dir = getDirectory(createTempDir("testSeekPastEOF"));
- IndexOutput o = dir.createOutput("out", newIOContext(random()));
- final int len = random().nextInt(2048);
- byte[] b = new byte[len];
- o.writeBytes(b, 0, len);
- o.close();
- IndexInput i = dir.openInput("out", newIOContext(random()));
- expectThrows(EOFException.class, () -> {
- i.seek(len + random().nextInt(2048));
- i.readByte();
- });
+ try (Directory dir = getDirectory(createTempDir("testSeekPastEOF"))) {
+ IndexOutput o = dir.createOutput("out", newIOContext(random()));
+ final int len = random().nextInt(2048);
+ byte[] b = new byte[len];
+ o.writeBytes(b, 0, len);
+ o.close();
+ IndexInput i = dir.openInput("out", newIOContext(random()));
+ expectThrows(EOFException.class, () -> {
+ i.seek(len + random().nextInt(2048));
+ i.readByte();
+ });
- i.close();
- dir.close();
+ i.close();
+ }
}
public void testSliceOutOfBounds() throws Exception {
- Directory dir = getDirectory(createTempDir("testSliceOutOfBounds"));
- IndexOutput o = dir.createOutput("out", newIOContext(random()));
- final int len = random().nextInt(2040) + 8;
- byte[] b = new byte[len];
- o.writeBytes(b, 0, len);
- o.close();
- IndexInput i = dir.openInput("out", newIOContext(random()));
- expectThrows(IllegalArgumentException.class, () -> {
- i.slice("slice1", 0, len + 1);
- });
+ try (Directory dir = getDirectory(createTempDir("testSliceOutOfBounds"))) {
+ IndexOutput o = dir.createOutput("out", newIOContext(random()));
+ final int len = random().nextInt(2040) + 8;
+ byte[] b = new byte[len];
+ o.writeBytes(b, 0, len);
+ o.close();
+ IndexInput i = dir.openInput("out", newIOContext(random()));
+ expectThrows(IllegalArgumentException.class, () -> {
+ i.slice("slice1", 0, len + 1);
+ });
- expectThrows(IllegalArgumentException.class, () -> {
- i.slice("slice2", -1, len);
- });
+ expectThrows(IllegalArgumentException.class, () -> {
+ i.slice("slice2", -1, len);
+ });
- IndexInput slice = i.slice("slice3", 4, len / 2);
- expectThrows(IllegalArgumentException.class, () -> {
- slice.slice("slice3sub", 1, len / 2);
- });
+ IndexInput slice = i.slice("slice3", 4, len / 2);
+ expectThrows(IllegalArgumentException.class, () -> {
+ slice.slice("slice3sub", 1, len / 2);
+ });
- i.close();
- dir.close();
+ i.close();
+ }
}
-
+
// LUCENE-3382 -- make sure we get exception if the directory really does not exist.
public void testNoDir() throws Throwable {
Path tempDir = createTempDir("doesnotexist");
IOUtils.rm(tempDir);
- Directory dir = getDirectory(tempDir);
- try {
- DirectoryReader.open(dir);
- fail("did not hit expected exception");
- } catch (NoSuchFileException | IndexNotFoundException nsde) {
- // expected
+ try (Directory dir = getDirectory(tempDir)) {
+ expectThrowsAnyOf(Arrays.asList(NoSuchFileException.class, IndexNotFoundException.class), () -> {
+ DirectoryReader.open(dir);
+ });
}
- dir.close();
}
public void testCopyBytes() throws Exception {
- testCopyBytes(getDirectory(createTempDir("testCopyBytes")));
- }
-
- private static byte value(int idx) {
- return (byte) ((idx % 256) * (1 + (idx / 256)));
- }
-
- public static void testCopyBytes(Directory dir) throws Exception {
-
- // make random file
- IndexOutput out = dir.createOutput("test", newIOContext(random()));
- byte[] bytes = new byte[TestUtil.nextInt(random(), 1, 77777)];
- final int size = TestUtil.nextInt(random(), 1, 1777777);
- int upto = 0;
- int byteUpto = 0;
- while (upto < size) {
- bytes[byteUpto++] = value(upto);
- upto++;
- if (byteUpto == bytes.length) {
- out.writeBytes(bytes, 0, bytes.length);
- byteUpto = 0;
- }
- }
-
- out.writeBytes(bytes, 0, byteUpto);
- assertEquals(size, out.getFilePointer());
- out.close();
- assertEquals(size, dir.fileLength("test"));
-
- // copy from test -> test2
- final IndexInput in = dir.openInput("test", newIOContext(random()));
-
- out = dir.createOutput("test2", newIOContext(random()));
-
- upto = 0;
- while (upto < size) {
- if (random().nextBoolean()) {
- out.writeByte(in.readByte());
+ try (Directory dir = getDirectory(createTempDir("testCopyBytes"))) {
+ IndexOutput out = dir.createOutput("test", newIOContext(random()));
+ byte[] bytes = new byte[TestUtil.nextInt(random(), 1, 77777)];
+ final int size = TestUtil.nextInt(random(), 1, 1777777);
+ int upto = 0;
+ int byteUpto = 0;
+ while (upto < size) {
+ bytes[byteUpto++] = value(upto);
upto++;
- } else {
- final int chunk = Math.min(
- TestUtil.nextInt(random(), 1, bytes.length), size - upto);
- out.copyBytes(in, chunk);
- upto += chunk;
+ if (byteUpto == bytes.length) {
+ out.writeBytes(bytes, 0, bytes.length);
+ byteUpto = 0;
+ }
}
- }
- assertEquals(size, upto);
- out.close();
- in.close();
-
- // verify
- IndexInput in2 = dir.openInput("test2", newIOContext(random()));
- upto = 0;
- while (upto < size) {
- if (random().nextBoolean()) {
- final byte v = in2.readByte();
- assertEquals(value(upto), v);
- upto++;
- } else {
- final int limit = Math.min(
- TestUtil.nextInt(random(), 1, bytes.length), size - upto);
- in2.readBytes(bytes, 0, limit);
- for (int byteIdx = 0; byteIdx < limit; byteIdx++) {
- assertEquals(value(upto), bytes[byteIdx]);
+
+ out.writeBytes(bytes, 0, byteUpto);
+ assertEquals(size, out.getFilePointer());
+ out.close();
+ assertEquals(size, dir.fileLength("test"));
+
+ // copy from test -> test2
+ final IndexInput in = dir.openInput("test", newIOContext(random()));
+
+ out = dir.createOutput("test2", newIOContext(random()));
+
+ upto = 0;
+ while (upto < size) {
+ if (random().nextBoolean()) {
+ out.writeByte(in.readByte());
+ upto++;
+ } else {
+ final int chunk = Math.min(
+ TestUtil.nextInt(random(), 1, bytes.length), size - upto);
+ out.copyBytes(in, chunk);
+ upto += chunk;
+ }
+ }
+ assertEquals(size, upto);
+ out.close();
+ in.close();
+
+ // verify
+ IndexInput in2 = dir.openInput("test2", newIOContext(random()));
+ upto = 0;
+ while (upto < size) {
+ if (random().nextBoolean()) {
+ final byte v = in2.readByte();
+ assertEquals(value(upto), v);
upto++;
+ } else {
+ final int limit = Math.min(
+ TestUtil.nextInt(random(), 1, bytes.length), size - upto);
+ in2.readBytes(bytes, 0, limit);
+ for (int byteIdx = 0; byteIdx < limit; byteIdx++) {
+ assertEquals(value(upto), bytes[byteIdx]);
+ upto++;
+ }
}
}
+ in2.close();
+
+ dir.deleteFile("test");
+ dir.deleteFile("test2");
}
- in2.close();
-
- dir.deleteFile("test");
- dir.deleteFile("test2");
- dir.close();
}
-
+
+ private static byte value(int idx) {
+ return (byte) ((idx % 256) * (1 + (idx / 256)));
+ }
+
// LUCENE-3541
public void testCopyBytesWithThreads() throws Exception {
- testCopyBytesWithThreads(getDirectory(createTempDir("testCopyBytesWithThreads")));
- }
+ try (Directory d = getDirectory(createTempDir("testCopyBytesWithThreads"))) {
+ byte data[] = RandomBytes.randomBytesOfLengthBetween(random(), 101, 10000);
- public static void testCopyBytesWithThreads(Directory d) throws Exception {
- int datalen = TestUtil.nextInt(random(), 101, 10000);
- byte data[] = new byte[datalen];
- random().nextBytes(data);
-
- IndexOutput output = d.createOutput("data", IOContext.DEFAULT);
- output.writeBytes(data, 0, datalen);
- output.close();
-
- IndexInput input = d.openInput("data", IOContext.DEFAULT);
- IndexOutput outputHeader = d.createOutput("header", IOContext.DEFAULT);
- // copy our 100-byte header
- outputHeader.copyBytes(input, 100);
- outputHeader.close();
-
- // now make N copies of the remaining bytes
- CopyThread copies[] = new CopyThread[10];
- for (int i = 0; i < copies.length; i++) {
- copies[i] = new CopyThread(input.clone(), d.createOutput("copy" + i, IOContext.DEFAULT));
- }
-
- for (int i = 0; i < copies.length; i++) {
- copies[i].start();
- }
-
- for (int i = 0; i < copies.length; i++) {
- copies[i].join();
- }
-
- for (int i = 0; i < copies.length; i++) {
- IndexInput copiedData = d.openInput("copy" + i, IOContext.DEFAULT);
- byte[] dataCopy = new byte[datalen];
- System.arraycopy(data, 0, dataCopy, 0, 100); // copy the header for easy testing
- copiedData.readBytes(dataCopy, 100, datalen-100);
- assertArrayEquals(data, dataCopy);
- copiedData.close();
- }
- input.close();
- d.close();
-
- }
-
- static class CopyThread extends Thread {
- final IndexInput src;
- final IndexOutput dst;
-
- CopyThread(IndexInput src, IndexOutput dst) {
- this.src = src;
- this.dst = dst;
- }
+ IndexOutput output = d.createOutput("data", IOContext.DEFAULT);
+ output.writeBytes(data, 0, data.length);
+ output.close();
- @Override
- public void run() {
- try {
- dst.copyBytes(src, src.length()-100);
- dst.close();
- } catch (IOException ex) {
- throw new RuntimeException(ex);
+ IndexInput input = d.openInput("data", IOContext.DEFAULT);
+ IndexOutput outputHeader = d.createOutput("header", IOContext.DEFAULT);
+ // copy our 100-byte header
+ outputHeader.copyBytes(input, 100);
+ outputHeader.close();
+
+ // now make N copies of the remaining bytes
+ int threads = 10;
+ CyclicBarrier start = new CyclicBarrier(threads);
+ Thread copies [] = IntStream.range(0, threads)
+ .mapToObj((i) -> {
+ IndexInput src = input.clone();
+ Thread t = new Thread(() -> {
+ try {
+ start.await();
+ IndexOutput dst = d.createOutput("copy" + i, IOContext.DEFAULT);
+ dst.copyBytes(src, src.length() - 100);
+ dst.close();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ t.start();
+ return t;
+ })
+ .toArray(Thread[]::new);
+
+ for (Thread t : copies) {
+ t.join();
}
+
+ for (int i = 0; i < threads; i++) {
+ try (IndexInput copiedData = d.openInput("copy" + i, IOContext.DEFAULT)) {
+ byte[] dataCopy = new byte[data.length];
+ System.arraycopy(data, 0, dataCopy, 0, 100);
+ copiedData.readBytes(dataCopy, 100, data.length - 100);
+ assertArrayEquals(data, dataCopy);
+ }
+ }
+ input.close();
}
}
-
+
// this test backdoors the directory via the filesystem. so it must actually use the filesystem
- // TODO: somehow change this test to
+ // TODO: somehow change this test to
public void testFsyncDoesntCreateNewFiles() throws Exception {
Path path = createTempDir("nocreate");
- Directory fsdir = getDirectory(path);
-
- // this test backdoors the directory via the filesystem. so it must be an FSDir (for now)
- // TODO: figure a way to test this better/clean it up. E.g. we should be testing for FileSwitchDir,
- // if it's using two FSdirs and so on
- if (fsdir instanceof FSDirectory == false) {
- fsdir.close();
- assumeTrue("test only works for FSDirectory subclasses", false);
- }
-
- // write a file
- IndexOutput out = fsdir.createOutput("afile", newIOContext(random()));
- out.writeString("boo");
- out.close();
-
- // delete it
- Files.delete(path.resolve("afile"));
-
- int fileCount = fsdir.listAll().length;
-
- // fsync it
- try {
- fsdir.sync(Collections.singleton("afile"));
- fail("didn't get expected exception, instead fsync created new files: " + Arrays.asList(fsdir.listAll()));
- } catch (FileNotFoundException | NoSuchFileException expected) {
- // ok
+ try (Directory fsdir = getDirectory(path)) {
+ // this test backdoors the directory via the filesystem. so it must be an FSDir (for now)
+ // TODO: figure a way to test this better/clean it up. E.g. we should be testing for FileSwitchDir,
+ // if it's using two FSdirs and so on
+ if (fsdir instanceof FSDirectory == false) {
+ assumeTrue("test only works for FSDirectory subclasses", false);
+ return;
+ }
+
+ // create a file
+ IndexOutput out = fsdir.createOutput("afile", newIOContext(random()));
+ out.writeString("boo");
+ out.close();
+
+ // delete it in the file system.
+ Files.delete(path.resolve("afile"));
+
+ int fileCount = fsdir.listAll().length;
+
+ // fsync it
+ expectThrowsAnyOf(Arrays.asList(FileNotFoundException.class, NoSuchFileException.class), () -> {
+ fsdir.sync(Collections.singleton("afile"));
+ });
+
+ // no new files created
+ assertEquals(fileCount, fsdir.listAll().length);
}
-
- // no new files created
- assertEquals(fileCount, fsdir.listAll().length);
-
- fsdir.close();
}
// random access APIs
-
+
public void testRandomLong() throws Exception {
- Directory dir = getDirectory(createTempDir("testLongs"));
- IndexOutput output = dir.createOutput("longs", newIOContext(random()));
- int num = TestUtil.nextInt(random(), 50, 3000);
- long longs[] = new long[num];
- for (int i = 0; i < longs.length; i++) {
- longs[i] = TestUtil.nextLong(random(), Long.MIN_VALUE, Long.MAX_VALUE);
- output.writeLong(longs[i]);
- }
- output.close();
-
- // slice
- IndexInput input = dir.openInput("longs", newIOContext(random()));
- RandomAccessInput slice = input.randomAccessSlice(0, input.length());
- for (int i = 0; i < longs.length; i++) {
- assertEquals(longs[i], slice.readLong(i * 8));
- }
-
- // subslices
- for (int i = 1; i < longs.length; i++) {
- long offset = i * 8;
- RandomAccessInput subslice = input.randomAccessSlice(offset, input.length() - offset);
- for (int j = i; j < longs.length; j++) {
- assertEquals(longs[j], subslice.readLong((j - i) * 8));
+ try (Directory dir = getDirectory(createTempDir("testLongs"))) {
+ IndexOutput output = dir.createOutput("longs", newIOContext(random()));
+ int num = TestUtil.nextInt(random(), 50, 3000);
+ long longs[] = new long[num];
+ for (int i = 0; i < longs.length; i++) {
+ longs[i] = TestUtil.nextLong(random(), Long.MIN_VALUE, Long.MAX_VALUE);
+ output.writeLong(longs[i]);
}
- }
-
- // with padding
- for (int i = 0; i < 7; i++) {
- String name = "longs-" + i;
- IndexOutput o = dir.createOutput(name, newIOContext(random()));
- byte junk[] = new byte[i];
- random().nextBytes(junk);
- o.writeBytes(junk, junk.length);
- input.seek(0);
- o.copyBytes(input, input.length());
- o.close();
- IndexInput padded = dir.openInput(name, newIOContext(random()));
- RandomAccessInput whole = padded.randomAccessSlice(i, padded.length() - i);
- for (int j = 0; j < longs.length; j++) {
- assertEquals(longs[j], whole.readLong(j * 8));
+ output.close();
+
+ // slice
+ IndexInput input = dir.openInput("longs", newIOContext(random()));
+ RandomAccessInput slice = input.randomAccessSlice(0, input.length());
+ for (int i = 0; i < longs.length; i++) {
+ assertEquals(longs[i], slice.readLong(i * 8));
+ }
+
+ // subslices
+ for (int i = 1; i < longs.length; i++) {
+ long offset = i * 8;
+ RandomAccessInput subslice = input.randomAccessSlice(offset, input.length() - offset);
+ for (int j = i; j < longs.length; j++) {
+ assertEquals(longs[j], subslice.readLong((j - i) * 8));
+ }
+ }
+
+ // with padding
+ for (int i = 0; i < 7; i++) {
+ String name = "longs-" + i;
+ IndexOutput o = dir.createOutput(name, newIOContext(random()));
+ byte junk[] = new byte[i];
+ random().nextBytes(junk);
+ o.writeBytes(junk, junk.length);
+ input.seek(0);
+ o.copyBytes(input, input.length());
+ o.close();
+ IndexInput padded = dir.openInput(name, newIOContext(random()));
+ RandomAccessInput whole = padded.randomAccessSlice(i, padded.length() - i);
+ for (int j = 0; j < longs.length; j++) {
+ assertEquals(longs[j], whole.readLong(j * 8));
+ }
+ padded.close();
}
- padded.close();
+
+ input.close();
}
-
- input.close();
- dir.close();
}
public void testRandomInt() throws Exception {
- Directory dir = getDirectory(createTempDir("testInts"));
- IndexOutput output = dir.createOutput("ints", newIOContext(random()));
- int num = TestUtil.nextInt(random(), 50, 3000);
- int ints[] = new int[num];
- for (int i = 0; i < ints.length; i++) {
- ints[i] = random().nextInt();
- output.writeInt(ints[i]);
- }
- output.close();
-
- // slice
- IndexInput input = dir.openInput("ints", newIOContext(random()));
- RandomAccessInput slice = input.randomAccessSlice(0, input.length());
- for (int i = 0; i < ints.length; i++) {
- assertEquals(ints[i], slice.readInt(i * 4));
- }
-
- // subslices
- for (int i = 1; i < ints.length; i++) {
- long offset = i * 4;
- RandomAccessInput subslice = input.randomAccessSlice(offset, input.length() - offset);
- for (int j = i; j < ints.length; j++) {
- assertEquals(ints[j], subslice.readInt((j - i) * 4));
+ try (Directory dir = getDirectory(createTempDir("testInts"))) {
+ IndexOutput output = dir.createOutput("ints", newIOContext(random()));
+ int num = TestUtil.nextInt(random(), 50, 3000);
+ int ints[] = new int[num];
+ for (int i = 0; i < ints.length; i++) {
+ ints[i] = random().nextInt();
+ output.writeInt(ints[i]);
}
- }
-
- // with padding
- for (int i = 0; i < 7; i++) {
- String name = "ints-" + i;
- IndexOutput o = dir.createOutput(name, newIOContext(random()));
- byte junk[] = new byte[i];
- random().nextBytes(junk);
- o.writeBytes(junk, junk.length);
- input.seek(0);
- o.copyBytes(input, input.length());
- o.close();
- IndexInput padded = dir.openInput(name, newIOContext(random()));
- RandomAccessInput whole = padded.randomAccessSlice(i, padded.length() - i);
- for (int j = 0; j < ints.length; j++) {
- assertEquals(ints[j], whole.readInt(j * 4));
+ output.close();
+
+ // slice
+ IndexInput input = dir.openInput("ints", newIOContext(random()));
+ RandomAccessInput slice = input.randomAccessSlice(0, input.length());
+ for (int i = 0; i < ints.length; i++) {
+ assertEquals(ints[i], slice.readInt(i * 4));
+ }
+
+ // subslices
+ for (int i = 1; i < ints.length; i++) {
+ long offset = i * 4;
+ RandomAccessInput subslice = input.randomAccessSlice(offset, input.length() - offset);
+ for (int j = i; j < ints.length; j++) {
+ assertEquals(ints[j], subslice.readInt((j - i) * 4));
+ }
+ }
+
+ // with padding
+ for (int i = 0; i < 7; i++) {
+ String name = "ints-" + i;
+ IndexOutput o = dir.createOutput(name, newIOContext(random()));
+ byte junk[] = new byte[i];
+ random().nextBytes(junk);
+ o.writeBytes(junk, junk.length);
+ input.seek(0);
+ o.copyBytes(input, input.length());
+ o.close();
+ IndexInput padded = dir.openInput(name, newIOContext(random()));
+ RandomAccessInput whole = padded.randomAccessSlice(i, padded.length() - i);
+ for (int j = 0; j < ints.length; j++) {
+ assertEquals(ints[j], whole.readInt(j * 4));
+ }
+ padded.close();
}
- padded.close();
+ input.close();
}
- input.close();
- dir.close();
}
public void testRandomShort() throws Exception {
- Directory dir = getDirectory(createTempDir("testShorts"));
- IndexOutput output = dir.createOutput("shorts", newIOContext(random()));
- int num = TestUtil.nextInt(random(), 50, 3000);
- short shorts[] = new short[num];
- for (int i = 0; i < shorts.length; i++) {
- shorts[i] = (short) random().nextInt();
- output.writeShort(shorts[i]);
- }
- output.close();
-
- // slice
- IndexInput input = dir.openInput("shorts", newIOContext(random()));
- RandomAccessInput slice = input.randomAccessSlice(0, input.length());
- for (int i = 0; i < shorts.length; i++) {
- assertEquals(shorts[i], slice.readShort(i * 2));
- }
-
- // subslices
- for (int i = 1; i < shorts.length; i++) {
- long offset = i * 2;
- RandomAccessInput subslice = input.randomAccessSlice(offset, input.length() - offset);
- for (int j = i; j < shorts.length; j++) {
- assertEquals(shorts[j], subslice.readShort((j - i) * 2));
+ try (Directory dir = getDirectory(createTempDir("testShorts"))) {
+ IndexOutput output = dir.createOutput("shorts", newIOContext(random()));
+ int num = TestUtil.nextInt(random(), 50, 3000);
+ short shorts[] = new short[num];
+ for (int i = 0; i < shorts.length; i++) {
+ shorts[i] = (short) random().nextInt();
+ output.writeShort(shorts[i]);
}
- }
-
- // with padding
- for (int i = 0; i < 7; i++) {
- String name = "shorts-" + i;
- IndexOutput o = dir.createOutput(name, newIOContext(random()));
- byte junk[] = new byte[i];
- random().nextBytes(junk);
- o.writeBytes(junk, junk.length);
- input.seek(0);
- o.copyBytes(input, input.length());
- o.close();
- IndexInput padded = dir.openInput(name, newIOContext(random()));
- RandomAccessInput whole = padded.randomAccessSlice(i, padded.length() - i);
- for (int j = 0; j < shorts.length; j++) {
- assertEquals(shorts[j], whole.readShort(j * 2));
+ output.close();
+
+ // slice
+ IndexInput input = dir.openInput("shorts", newIOContext(random()));
+ RandomAccessInput slice = input.randomAccessSlice(0, input.length());
+ for (int i = 0; i < shorts.length; i++) {
+ assertEquals(shorts[i], slice.readShort(i * 2));
+ }
+
+ // subslices
+ for (int i = 1; i < shorts.length; i++) {
+ long offset = i * 2;
+ RandomAccessInput subslice = input.randomAccessSlice(offset, input.length() - offset);
+ for (int j = i; j < shorts.length; j++) {
+ assertEquals(shorts[j], subslice.readShort((j - i) * 2));
+ }
}
- padded.close();
+
+ // with padding
+ for (int i = 0; i < 7; i++) {
+ String name = "shorts-" + i;
+ IndexOutput o = dir.createOutput(name, newIOContext(random()));
+ byte junk[] = new byte[i];
+ random().nextBytes(junk);
+ o.writeBytes(junk, junk.length);
+ input.seek(0);
+ o.copyBytes(input, input.length());
+ o.close();
+ IndexInput padded = dir.openInput(name, newIOContext(random()));
+ RandomAccessInput whole = padded.randomAccessSlice(i, padded.length() - i);
+ for (int j = 0; j < shorts.length; j++) {
+ assertEquals(shorts[j], whole.readShort(j * 2));
+ }
+ padded.close();
+ }
+ input.close();
}
- input.close();
- dir.close();
}
public void testRandomByte() throws Exception {
- Directory dir = getDirectory(createTempDir("testBytes"));
- IndexOutput output = dir.createOutput("bytes", newIOContext(random()));
- int num = TestUtil.nextInt(random(), 50, 3000);
- byte bytes[] = new byte[num];
- random().nextBytes(bytes);
- for (int i = 0; i < bytes.length; i++) {
- output.writeByte(bytes[i]);
- }
- output.close();
-
- // slice
- IndexInput input = dir.openInput("bytes", newIOContext(random()));
- RandomAccessInput slice = input.randomAccessSlice(0, input.length());
- for (int i = 0; i < bytes.length; i++) {
- assertEquals(bytes[i], slice.readByte(i));
- }
-
- // subslices
- for (int i = 1; i < bytes.length; i++) {
- long offset = i;
- RandomAccessInput subslice = input.randomAccessSlice(offset, input.length() - offset);
- for (int j = i; j < bytes.length; j++) {
- assertEquals(bytes[j], subslice.readByte(j - i));
+ try (Directory dir = getDirectory(createTempDir("testBytes"))) {
+ IndexOutput output = dir.createOutput("bytes", newIOContext(random()));
+ int num = TestUtil.nextInt(random(), 50, 3000);
+ byte bytes[] = new byte[num];
+ random().nextBytes(bytes);
+ for (int i = 0; i < bytes.length; i++) {
+ output.writeByte(bytes[i]);
}
- }
-
- // with padding
- for (int i = 0; i < 7; i++) {
- String name = "bytes-" + i;
- IndexOutput o = dir.createOutput(name, newIOContext(random()));
- byte junk[] = new byte[i];
- random().nextBytes(junk);
- o.writeBytes(junk, junk.length);
- input.seek(0);
- o.copyBytes(input, input.length());
- o.close();
- IndexInput padded = dir.openInput(name, newIOContext(random()));
- RandomAccessInput whole = padded.randomAccessSlice(i, padded.length() - i);
- for (int j = 0; j < bytes.length; j++) {
- assertEquals(bytes[j], whole.readByte(j));
+ output.close();
+
+ // slice
+ IndexInput input = dir.openInput("bytes", newIOContext(random()));
+ RandomAccessInput slice = input.randomAccessSlice(0, input.length());
+ for (int i = 0; i < bytes.length; i++) {
+ assertEquals(bytes[i], slice.readByte(i));
+ }
+
+ // subslices
+ for (int i = 1; i < bytes.length; i++) {
+ long offset = i;
+ RandomAccessInput subslice = input.randomAccessSlice(offset, input.length() - offset);
+ for (int j = i; j < bytes.length; j++) {
+ assertEquals(bytes[j], subslice.readByte(j - i));
+ }
+ }
+
+ // with padding
+ for (int i = 0; i < 7; i++) {
+ String name = "bytes-" + i;
+ IndexOutput o = dir.createOutput(name, newIOContext(random()));
+ byte junk[] = new byte[i];
+ random().nextBytes(junk);
+ o.writeBytes(junk, junk.length);
+ input.seek(0);
+ o.copyBytes(input, input.length());
+ o.close();
+ IndexInput padded = dir.openInput(name, newIOContext(random()));
+ RandomAccessInput whole = padded.randomAccessSlice(i, padded.length() - i);
+ for (int j = 0; j < bytes.length; j++) {
+ assertEquals(bytes[j], whole.readByte(j));
+ }
+ padded.close();
}
- padded.close();
+ input.close();
}
- input.close();
- dir.close();
}
/** try to stress slices of slices */
public void testSliceOfSlice() throws Exception {
- Directory dir = getDirectory(createTempDir("sliceOfSlice"));
- IndexOutput output = dir.createOutput("bytes", newIOContext(random()));
- final int num;
- if (TEST_NIGHTLY) {
- num = TestUtil.nextInt(random(), 250, 2500);
- } else {
- num = TestUtil.nextInt(random(), 50, 250);
- }
- byte bytes[] = new byte[num];
- random().nextBytes(bytes);
- for (int i = 0; i < bytes.length; i++) {
- output.writeByte(bytes[i]);
- }
- output.close();
-
- IndexInput input = dir.openInput("bytes", newIOContext(random()));
- // seek to a random spot shouldnt impact slicing.
- input.seek(TestUtil.nextLong(random(), 0, input.length()));
- for (int i = 0; i < num; i += 16) {
- IndexInput slice1 = input.slice("slice1", i, num-i);
- assertEquals(0, slice1.getFilePointer());
- assertEquals(num-i, slice1.length());
-
+ try (Directory dir = getDirectory(createTempDir("sliceOfSlice"))) {
+ IndexOutput output = dir.createOutput("bytes", newIOContext(random()));
+ final int num;
+ if (TEST_NIGHTLY) {
+ num = TestUtil.nextInt(random(), 250, 2500);
+ } else {
+ num = TestUtil.nextInt(random(), 50, 250);
+ }
+ byte bytes[] = new byte[num];
+ random().nextBytes(bytes);
+ for (int i = 0; i < bytes.length; i++) {
+ output.writeByte(bytes[i]);
+ }
+ output.close();
+
+ IndexInput input = dir.openInput("bytes", newIOContext(random()));
// seek to a random spot shouldnt impact slicing.
- slice1.seek(TestUtil.nextLong(random(), 0, slice1.length()));
- for (int j = 0; j < slice1.length(); j += 16) {
- IndexInput slice2 = slice1.slice("slice2", j, num-i-j);
- assertEquals(0, slice2.getFilePointer());
- assertEquals(num-i-j, slice2.length());
- byte data[] = new byte[num];
- System.arraycopy(bytes, 0, data, 0, i+j);
- if (random().nextBoolean()) {
- // read the bytes for this slice-of-slice
- slice2.readBytes(data, i+j, num-i-j);
- } else {
- // seek to a random spot in between, read some, seek back and read the rest
- long seek = TestUtil.nextLong(random(), 0, slice2.length());
- slice2.seek(seek);
- slice2.readBytes(data, (int)(i+j+seek), (int)(num-i-j-seek));
- slice2.seek(0);
- slice2.readBytes(data, i+j, (int)seek);
+ input.seek(TestUtil.nextLong(random(), 0, input.length()));
+ for (int i = 0; i < num; i += 16) {
+ IndexInput slice1 = input.slice("slice1", i, num - i);
+ assertEquals(0, slice1.getFilePointer());
+ assertEquals(num - i, slice1.length());
+
+ // seek to a random spot shouldnt impact slicing.
+ slice1.seek(TestUtil.nextLong(random(), 0, slice1.length()));
+ for (int j = 0; j < slice1.length(); j += 16) {
+ IndexInput slice2 = slice1.slice("slice2", j, num - i - j);
+ assertEquals(0, slice2.getFilePointer());
+ assertEquals(num - i - j, slice2.length());
+ byte data[] = new byte[num];
+ System.arraycopy(bytes, 0, data, 0, i + j);
+ if (random().nextBoolean()) {
+ // read the bytes for this slice-of-slice
+ slice2.readBytes(data, i + j, num - i - j);
+ } else {
+ // seek to a random spot in between, read some, seek back and read the rest
+ long seek = TestUtil.nextLong(random(), 0, slice2.length());
+ slice2.seek(seek);
+ slice2.readBytes(data, (int) (i + j + seek), (int) (num - i - j - seek));
+ slice2.seek(0);
+ slice2.readBytes(data, i + j, (int) seek);
+ }
+ assertArrayEquals(bytes, data);
}
- assertArrayEquals(bytes, data);
}
+
+ input.close();
}
-
- input.close();
- dir.close();
}
/**
@@ -1023,82 +966,93 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {
* will correctly increment the file pointer.
*/
public void testLargeWrites() throws IOException {
- Directory dir = getDirectory(createTempDir("largeWrites"));
- IndexOutput os = dir.createOutput("testBufferStart.txt", newIOContext(random()));
-
- byte[] largeBuf = new byte[2048];
- random().nextBytes(largeBuf);
-
- long currentPos = os.getFilePointer();
- os.writeBytes(largeBuf, largeBuf.length);
-
- try {
- assertEquals(currentPos + largeBuf.length, os.getFilePointer());
- } finally {
- os.close();
+ try (Directory dir = getDirectory(createTempDir("largeWrites"))) {
+ IndexOutput os = dir.createOutput("testBufferStart.txt", newIOContext(random()));
+
+ byte[] largeBuf = new byte[2048];
+ random().nextBytes(largeBuf);
+
+ long currentPos = os.getFilePointer();
+ os.writeBytes(largeBuf, largeBuf.length);
+
+ try {
+ assertEquals(currentPos + largeBuf.length, os.getFilePointer());
+ } finally {
+ os.close();
+ }
}
- dir.close();
}
// LUCENE-6084
public void testIndexOutputToString() throws Throwable {
- Directory dir = getDirectory(createTempDir());
- IndexOutput out = dir.createOutput("camelCase.txt", newIOContext(random()));
- assertTrue(out.toString(), out.toString().contains("camelCase.txt"));
- out.close();
- dir.close();
- }
-
- public void testDoubleCloseDirectory() throws Throwable {
- Directory dir = getDirectory(createTempDir());
- IndexOutput out = dir.createOutput("foobar", newIOContext(random()));
- out.writeString("testing");
- out.close();
- dir.close();
- dir.close(); // close again
+ try (Directory dir = getDirectory(createTempDir())) {
+ IndexOutput out = dir.createOutput("camelCase.txt", newIOContext(random()));
+ assertTrue(out.toString(), out.toString().contains("camelCase.txt"));
+ out.close();
+ }
}
public void testDoubleCloseOutput() throws Throwable {
- Directory dir = getDirectory(createTempDir());
- IndexOutput out = dir.createOutput("foobar", newIOContext(random()));
- out.writeString("testing");
- out.close();
- out.close(); // close again
- dir.close();
+ try (Directory dir = getDirectory(createTempDir())) {
+ IndexOutput out = dir.createOutput("foobar", newIOContext(random()));
+ out.writeString("testing");
+ out.close();
+ out.close(); // close again
+ }
}
public void testDoubleCloseInput() throws Throwable {
- Directory dir = getDirectory(createTempDir());
- IndexOutput out = dir.createOutput("foobar", newIOContext(random()));
- out.writeString("testing");
- out.close();
- IndexInput in = dir.openInput("foobar", newIOContext(random()));
- assertEquals("testing", in.readString());
- in.close();
- in.close(); // close again
- dir.close();
+ try (Directory dir = getDirectory(createTempDir())) {
+ IndexOutput out = dir.createOutput("foobar", newIOContext(random()));
+ out.writeString("testing");
+ out.close();
+ IndexInput in = dir.openInput("foobar", newIOContext(random()));
+ assertEquals("testing", in.readString());
+ in.close();
+ in.close(); // close again
+ }
}
public void testCreateTempOutput() throws Throwable {
- Directory dir = getDirectory(createTempDir());
- List<String> names = new ArrayList<>();
- int iters = atLeast(50);
- for(int iter=0;iter<iters;iter++) {
- IndexOutput out = dir.createTempOutput("foo", "bar", newIOContext(random()));
- names.add(out.getName());
- out.writeVInt(iter);
- out.close();
+ try (Directory dir = getDirectory(createTempDir())) {
+ List<String> names = new ArrayList<>();
+ int iters = atLeast(50);
+ for (int iter = 0; iter < iters; iter++) {
+ IndexOutput out = dir.createTempOutput("foo", "bar", newIOContext(random()));
+ names.add(out.getName());
+ out.writeVInt(iter);
+ out.close();
+ }
+ for (int iter = 0; iter < iters; iter++) {
+ IndexInput in = dir.openInput(names.get(iter), newIOContext(random()));
+ assertEquals(iter, in.readVInt());
+ in.close();
+ }
+
+ Set<String> files = Arrays.stream(dir.listAll())
+ .filter(file -> !ExtrasFS.isExtra(file)) // remove any ExtrasFS stuff.
+ .collect(Collectors.toSet());
+
+ assertEquals(new HashSet<String>(names), files);
}
- for(int iter=0;iter<iters;iter++) {
- IndexInput in = dir.openInput(names.get(iter), newIOContext(random()));
- assertEquals(iter, in.readVInt());
- in.close();
+ }
+
+ public void testCreateOutputForExistingFile() throws IOException {
+ try (Directory dir = getDirectory(createTempDir())) {
+ String name = "file";
+ try (IndexOutput out = dir.createOutput(name, IOContext.DEFAULT)) {
+ }
+
+ // Try to create an existing file should fail.
+ expectThrows(FileAlreadyExistsException.class, () -> {
+ try (IndexOutput out = dir.createOutput(name, IOContext.DEFAULT)) {
+ }
+ });
+
+ // Delete file and try to recreate it.
+ dir.deleteFile(name);
+ dir.createOutput(name, IOContext.DEFAULT).close();
}
- Set<String> files = new HashSet<String>(Arrays.asList(dir.listAll()));
- // In case ExtrasFS struck:
- files.remove("extra0");
- assertEquals(new HashSet<String>(names), files);
- dir.close();
}
public void testSeekToEndOfFile() throws IOException {
@@ -1185,7 +1139,7 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {
try (Directory dir = getDirectory(createTempDir())) {
int count = atLeast(20);
Set<String> names = new HashSet<>();
- while(names.size() < count) {
+ while (names.size() < count) {
// create a random filename (segment file name style), so it cannot hit windows problem with special filenames ("con", "com1",...):
String name = IndexFileNames.segmentFileName(TestUtil.randomSimpleString(random(), 1, 6), TestUtil.randomSimpleString(random()), "test");
if (random().nextInt(5) == 1) {
@@ -1201,7 +1155,7 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {
String[] actual = dir.listAll();
String[] expected = actual.clone();
Arrays.sort(expected);
- assertEquals(expected, actual);
+ assertArrayEquals(expected, actual);
}
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.java b/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.java
index 0194177..ec0d4ff 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.java
@@ -19,6 +19,7 @@ package org.apache.lucene.store;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.nio.file.FileAlreadyExistsException;
import java.nio.file.NoSuchFileException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -649,11 +650,11 @@ public class MockDirectoryWrapper extends BaseDirectoryWrapper {
throw new IOException("cannot createOutput after crash");
}
init();
- synchronized(this) {
- if (createdFiles.contains(name) && !name.equals("segments.gen")) {
- throw new IOException("file \"" + name + "\" was already written to");
- }
+
+ if (createdFiles.contains(name)) {
+ throw new FileAlreadyExistsException("File \"" + name + "\" was already written to.");
}
+
if (assertNoDeleteOpenFile && openFiles.containsKey(name)) {
throw new AssertionError("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot overwrite");
}
@@ -666,19 +667,24 @@ public class MockDirectoryWrapper extends BaseDirectoryWrapper {
final IndexOutput io = new MockIndexOutputWrapper(this, delegateOutput, name);
addFileHandle(io, name, Handle.Output);
openFilesForWrite.add(name);
-
+ return maybeThrottle(name, io);
+
+
+ }
+
+ private IndexOutput maybeThrottle(String name, IndexOutput output) {
// throttling REALLY slows down tests, so don't do it very often for SOMETIMES.
- if (throttling == Throttling.ALWAYS ||
+ if (throttling == Throttling.ALWAYS ||
(throttling == Throttling.SOMETIMES && randomState.nextInt(200) == 0)) {
if (LuceneTestCase.VERBOSE) {
System.out.println("MockDirectoryWrapper: throttling indexOutput (" + name + ")");
}
- return throttledOutput.newFromDelegate(io);
+ return throttledOutput.newFromDelegate(output);
} else {
- return io;
+ return output;
}
}
-
+
@Override
public synchronized IndexOutput createTempOutput(String prefix, String suffix, IOContext context) throws IOException {
maybeThrowDeterministicException();
@@ -704,16 +710,7 @@ public class MockDirectoryWrapper extends BaseDirectoryWrapper {
addFileHandle(io, name, Handle.Output);
openFilesForWrite.add(name);
- // throttling REALLY slows down tests, so don't do it very often for SOMETIMES.
- if (throttling == Throttling.ALWAYS ||
- (throttling == Throttling.SOMETIMES && randomState.nextInt(200) == 0)) {
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockDirectoryWrapper: throttling indexOutput (" + name + ")");
- }
- return throttledOutput.newFromDelegate(io);
- } else {
- return io;
- }
+ return maybeThrottle(name, io);
}
private static enum Handle {
@@ -750,9 +747,8 @@ public class MockDirectoryWrapper extends BaseDirectoryWrapper {
throw randomState.nextBoolean() ? new FileNotFoundException(name + " in dir=" + in) : new NoSuchFileException(name + " in dir=" + in);
}
- // cannot open a file for input if it's still open for
- // output, except for segments.gen and segments_N
- if (!allowReadingFilesStillOpenForWrite && openFilesForWrite.contains(name) && !name.startsWith("segments")) {
+ // cannot open a file for input if it's still open for output.
+ if (!allowReadingFilesStillOpenForWrite && openFilesForWrite.contains(name)) {
throw (IOException) fillOpenTrace(new IOException("MockDirectoryWrapper: file \"" + name + "\" is still open for writing"), name, false);
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
index baf72c1..6390cc8 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
@@ -64,6 +64,7 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockAnalyzer;
@@ -2683,6 +2684,38 @@ public abstract class LuceneTestCase extends Assert {
throw new AssertionFailedError(noExceptionMessage);
}
+ /** Checks a specific exception class is thrown by the given runnable, and returns it. */
+ public static <T extends Throwable> T expectThrowsAnyOf(List<Class<? extends T>> expectedTypes, ThrowingRunnable runnable) {
+ if (expectedTypes.isEmpty()) {
+ throw new AssertionError("At least one expected exception type is required?");
+ }
+
+ Throwable thrown = null;
+ try {
+ runnable.run();
+ } catch (Throwable e) {
+ for (Class<? extends T> expectedType : expectedTypes) {
+ if (expectedType.isInstance(e)) {
+ return expectedType.cast(e);
+ }
+ }
+ thrown = e;
+ }
+
+ List<String> exceptionTypes = expectedTypes.stream().map(c -> c.getSimpleName()).collect(Collectors.toList());
+
+ if (thrown != null) {
+ AssertionFailedError assertion = new AssertionFailedError("Unexpected exception type, expected any of " +
+ exceptionTypes +
+ " but got: " + thrown);
+ assertion.initCause(thrown);
+ throw assertion;
+ } else {
+ throw new AssertionFailedError("Expected any of the following exception types: " +
+ exceptionTypes+ " but no exception was thrown.");
+ }
+ }
+
/**
* Checks that specific wrapped and outer exception classes are thrown
* by the given runnable, and returns the wrapped exception.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8892c0d9/lucene/test-framework/src/test/org/apache/lucene/store/TestMockDirectoryWrapper.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/test/org/apache/lucene/store/TestMockDirectoryWrapper.java b/lucene/test-framework/src/test/org/apache/lucene/store/TestMockDirectoryWrapper.java
index 7973256..2ea6ce0 100644
--- a/lucene/test-framework/src/test/org/apache/lucene/store/TestMockDirectoryWrapper.java
+++ b/lucene/test-framework/src/test/org/apache/lucene/store/TestMockDirectoryWrapper.java
@@ -40,11 +40,12 @@ public class TestMockDirectoryWrapper extends BaseDirectoryTestCase {
}
// we wrap the directory in slow stuff, so only run nightly
- @Override @Nightly
- public void testThreadSafety() throws Exception {
- super.testThreadSafety();
+ @Override
+ @Nightly
+ public void testThreadSafetyInListAll() throws Exception {
+ super.testThreadSafetyInListAll();
}
-
+
public void testDiskFull() throws IOException {
// test writeBytes
MockDirectoryWrapper dir = newMockDirectory();
[07/33] lucene-solr:jira/http2: SOLR-11598: Support more than 4 sort
fields in the export writer
Posted by da...@apache.org.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/FloatCmp.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/FloatCmp.java b/solr/core/src/java/org/apache/solr/handler/export/FloatCmp.java
new file mode 100644
index 0000000..7ef078c
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/FloatCmp.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+interface FloatComp {
+ int compare(float a, float b);
+ float resetValue();
+}
+
+class FloatAsc implements FloatComp {
+ public float resetValue() {
+ return Float.MAX_VALUE;
+ }
+
+ public int compare(float a, float b) {
+ return Float.compare(b, a);
+ }
+}
+
+class FloatDesc implements FloatComp {
+ public float resetValue() {
+ return -Float.MAX_VALUE;
+ }
+
+ public int compare(float a, float b) {
+ return Float.compare(a, b);
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/FloatFieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/FloatFieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/FloatFieldWriter.java
new file mode 100644
index 0000000..cfb2e25
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/FloatFieldWriter.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.NumericDocValues;
+import org.apache.solr.common.MapWriter;
+
+class FloatFieldWriter extends FieldWriter {
+ private String field;
+
+ public FloatFieldWriter(String field) {
+ this.field = field;
+ }
+
+ public boolean write(int docId, LeafReader reader, MapWriter.EntryWriter ew, int fieldIndex) throws IOException {
+ NumericDocValues vals = DocValues.getNumeric(reader, this.field);
+ int val;
+ if (vals.advance(docId) == docId) {
+ val = (int)vals.longValue();
+ } else {
+ return false;
+ }
+ ew.put(this.field, Float.intBitsToFloat(val));
+ return true;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/FloatValue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/FloatValue.java b/solr/core/src/java/org/apache/solr/handler/export/FloatValue.java
new file mode 100644
index 0000000..f6a5bbd
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/FloatValue.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.NumericDocValues;
+
+class FloatValue implements SortValue {
+
+ protected NumericDocValues vals;
+ protected String field;
+ protected float currentValue;
+ protected FloatComp comp;
+ private int lastDocID;
+
+ public FloatValue(String field, FloatComp comp) {
+ this.field = field;
+ this.comp = comp;
+ this.currentValue = comp.resetValue();
+ }
+
+ public FloatValue copy() {
+ return new FloatValue(field, comp);
+ }
+
+ public void setNextReader(LeafReaderContext context) throws IOException {
+ this.vals = DocValues.getNumeric(context.reader(), field);
+ lastDocID = 0;
+ }
+
+ public void setCurrentValue(int docId) throws IOException {
+ if (docId < lastDocID) {
+ throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
+ }
+ lastDocID = docId;
+ int curDocID = vals.docID();
+ if (docId > curDocID) {
+ curDocID = vals.advance(docId);
+ }
+ if (docId == curDocID) {
+ currentValue = Float.intBitsToFloat((int)vals.longValue());
+ } else {
+ currentValue = 0f;
+ }
+ }
+
+ public void setCurrentValue(SortValue sv) {
+ FloatValue fv = (FloatValue)sv;
+ this.currentValue = fv.currentValue;
+ }
+
+ public void reset() {
+ this.currentValue = comp.resetValue();
+ }
+
+ public int compareTo(SortValue o) {
+ FloatValue fv = (FloatValue)o;
+ return comp.compare(currentValue, fv.currentValue);
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/IntComp.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/IntComp.java b/solr/core/src/java/org/apache/solr/handler/export/IntComp.java
new file mode 100644
index 0000000..ac83d5d
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/IntComp.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+public interface IntComp {
+ int compare(int a, int b);
+ int resetValue();
+}
+
+class IntAsc implements IntComp {
+
+ public int resetValue() {
+ return Integer.MAX_VALUE;
+ }
+
+ public int compare(int a, int b) {
+ return Integer.compare(b, a);
+ }
+}
+
+class IntDesc implements IntComp {
+
+ public int resetValue() {
+ return Integer.MIN_VALUE;
+ }
+
+ public int compare(int a, int b) {
+ return Integer.compare(a, b);
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/IntFieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/IntFieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/IntFieldWriter.java
new file mode 100644
index 0000000..66e5936
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/IntFieldWriter.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.NumericDocValues;
+import org.apache.solr.common.MapWriter;
+
+class IntFieldWriter extends FieldWriter {
+ private String field;
+
+ public IntFieldWriter(String field) {
+ this.field = field;
+ }
+
+ public boolean write(int docId, LeafReader reader, MapWriter.EntryWriter ew, int fieldIndex) throws IOException {
+ NumericDocValues vals = DocValues.getNumeric(reader, this.field);
+ int val;
+ if (vals.advance(docId) == docId) {
+ val = (int) vals.longValue();
+ } else {
+ return false;
+ }
+ ew.put(this.field, val);
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/IntValue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/IntValue.java b/solr/core/src/java/org/apache/solr/handler/export/IntValue.java
new file mode 100644
index 0000000..d222aa3
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/IntValue.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.NumericDocValues;
+
+public class IntValue implements SortValue {
+
+ protected NumericDocValues vals;
+ protected String field;
+ protected int currentValue;
+ protected IntComp comp;
+ private int lastDocID;
+
+ public IntValue copy() {
+ return new IntValue(field, comp);
+ }
+
+ public IntValue(String field, IntComp comp) {
+ this.field = field;
+ this.comp = comp;
+ this.currentValue = comp.resetValue();
+ }
+
+ public void setNextReader(LeafReaderContext context) throws IOException {
+ this.vals = DocValues.getNumeric(context.reader(), field);
+ lastDocID = 0;
+ }
+
+ public void setCurrentValue(int docId) throws IOException {
+ if (docId < lastDocID) {
+ throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
+ }
+ lastDocID = docId;
+ int curDocID = vals.docID();
+ if (docId > curDocID) {
+ curDocID = vals.advance(docId);
+ }
+ if (docId == curDocID) {
+ currentValue = (int) vals.longValue();
+ } else {
+ currentValue = 0;
+ }
+ }
+
+ public int compareTo(SortValue o) {
+ IntValue iv = (IntValue)o;
+ return comp.compare(currentValue, iv.currentValue);
+ }
+
+ public void setCurrentValue (SortValue value) {
+ currentValue = ((IntValue)value).currentValue;
+ }
+
+ public void reset() {
+ currentValue = comp.resetValue();
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/LongCmp.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/LongCmp.java b/solr/core/src/java/org/apache/solr/handler/export/LongCmp.java
new file mode 100644
index 0000000..7d997ac
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/LongCmp.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+interface LongComp {
+ int compare(long a, long b);
+ long resetValue();
+}
+
+class LongAsc implements LongComp {
+
+ public long resetValue() {
+ return Long.MAX_VALUE;
+ }
+
+ public int compare(long a, long b) {
+ return Long.compare(b, a);
+ }
+}
+
+class LongDesc implements LongComp {
+
+ public long resetValue() {
+ return Long.MIN_VALUE;
+ }
+
+ public int compare(long a, long b) {
+ return Long.compare(a, b);
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/LongFieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/LongFieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/LongFieldWriter.java
new file mode 100644
index 0000000..87f2a32
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/LongFieldWriter.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.NumericDocValues;
+import org.apache.solr.common.MapWriter;
+
+class LongFieldWriter extends FieldWriter {
+ private String field;
+
+ public LongFieldWriter(String field) {
+ this.field = field;
+ }
+
+ public boolean write(int docId, LeafReader reader, MapWriter.EntryWriter ew, int fieldIndex) throws IOException {
+ NumericDocValues vals = DocValues.getNumeric(reader, this.field);
+ long val;
+ if (vals.advance(docId) == docId) {
+ val = vals.longValue();
+ } else {
+ return false;
+ }
+ ew.put(field, val);
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/LongValue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/LongValue.java b/solr/core/src/java/org/apache/solr/handler/export/LongValue.java
new file mode 100644
index 0000000..28b9a07
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/LongValue.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.NumericDocValues;
+
+public class LongValue implements SortValue {
+
+ protected NumericDocValues vals;
+ protected String field;
+ protected long currentValue;
+ protected LongComp comp;
+ private int lastDocID;
+
+ public LongValue(String field, LongComp comp) {
+ this.field = field;
+ this.comp = comp;
+ this.currentValue = comp.resetValue();
+ }
+
+ public LongValue copy() {
+ return new LongValue(field, comp);
+ }
+
+ public void setNextReader(LeafReaderContext context) throws IOException {
+ this.vals = DocValues.getNumeric(context.reader(), field);
+ lastDocID = 0;
+ }
+
+ public void setCurrentValue(int docId) throws IOException {
+ if (docId < lastDocID) {
+ throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
+ }
+ lastDocID = docId;
+ int curDocID = vals.docID();
+ if (docId > curDocID) {
+ curDocID = vals.advance(docId);
+ }
+ if (docId == curDocID) {
+ currentValue = vals.longValue();
+ } else {
+ currentValue = 0;
+ }
+ }
+
+ public void setCurrentValue(SortValue sv) {
+ LongValue lv = (LongValue)sv;
+ this.currentValue = lv.currentValue;
+ }
+
+ public int compareTo(SortValue o) {
+ LongValue l = (LongValue)o;
+ return comp.compare(currentValue, l.currentValue);
+ }
+
+ public void reset() {
+ this.currentValue = comp.resetValue();
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/MultiFieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/MultiFieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/MultiFieldWriter.java
new file mode 100644
index 0000000..2e43207
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/MultiFieldWriter.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.function.LongFunction;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.IndexableField;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.SortedNumericDocValues;
+import org.apache.lucene.index.SortedSetDocValues;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.CharsRefBuilder;
+import org.apache.lucene.util.NumericUtils;
+import org.apache.solr.common.IteratorWriter;
+import org.apache.solr.common.MapWriter;
+import org.apache.solr.schema.FieldType;
+import org.apache.solr.schema.SchemaField;
+
+class MultiFieldWriter extends FieldWriter {
+ private String field;
+ private FieldType fieldType;
+ private SchemaField schemaField;
+ private boolean numeric;
+ private CharsRefBuilder cref = new CharsRefBuilder();
+ private final LongFunction<Object> bitsToValue;
+
+ public MultiFieldWriter(String field, FieldType fieldType, SchemaField schemaField, boolean numeric) {
+ this.field = field;
+ this.fieldType = fieldType;
+ this.schemaField = schemaField;
+ this.numeric = numeric;
+ if (this.fieldType.isPointField()) {
+ bitsToValue = bitsToValue(fieldType);
+ } else {
+ bitsToValue = null;
+ }
+ }
+
+ public boolean write(int docId, LeafReader reader, MapWriter.EntryWriter out, int fieldIndex) throws IOException {
+ if (this.fieldType.isPointField()) {
+ SortedNumericDocValues vals = DocValues.getSortedNumeric(reader, this.field);
+ if (!vals.advanceExact(docId)) return false;
+ out.put(this.field,
+ (IteratorWriter) w -> {
+ for (int i = 0; i < vals.docValueCount(); i++) {
+ w.add(bitsToValue.apply(vals.nextValue()));
+ }
+ });
+ return true;
+ } else {
+ SortedSetDocValues vals = DocValues.getSortedSet(reader, this.field);
+ if (vals.advance(docId) != docId) return false;
+ out.put(this.field,
+ (IteratorWriter) w -> {
+ long o;
+ while((o = vals.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) {
+ BytesRef ref = vals.lookupOrd(o);
+ fieldType.indexedToReadable(ref, cref);
+ IndexableField f = fieldType.createField(schemaField, cref.toString());
+ if (f == null) w.add(cref.toString());
+ else w.add(fieldType.toObject(f));
+ }
+ });
+ return true;
+ }
+
+ }
+
+
+ static LongFunction<Object> bitsToValue(FieldType fieldType) {
+ switch (fieldType.getNumberType()) {
+ case LONG:
+ return (bits)-> bits;
+ case DATE:
+ return (bits)-> new Date(bits);
+ case INTEGER:
+ return (bits)-> (int)bits;
+ case FLOAT:
+ return (bits)-> NumericUtils.sortableIntToFloat((int)bits);
+ case DOUBLE:
+ return (bits)-> NumericUtils.sortableLongToDouble(bits);
+ default:
+ throw new AssertionError("Unsupported NumberType: " + fieldType.getNumberType());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/PriorityQueue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/PriorityQueue.java b/solr/core/src/java/org/apache/solr/handler/export/PriorityQueue.java
new file mode 100644
index 0000000..1552060
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/PriorityQueue.java
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import org.apache.lucene.util.ArrayUtil;
+
+public abstract class PriorityQueue<T> {
+ protected int size = 0;
+ protected final int maxSize;
+ private final T[] heap;
+
+ public PriorityQueue(int maxSize) {
+ this(maxSize, true);
+ }
+
+ public PriorityQueue(int maxSize, boolean prepopulate) {
+ final int heapSize;
+ if (0 == maxSize) {
+ // We allocate 1 extra to avoid if statement in top()
+ heapSize = 2;
+ } else {
+ if (maxSize > ArrayUtil.MAX_ARRAY_LENGTH) {
+ // Don't wrap heapSize to -1, in this case, which
+ // causes a confusing NegativeArraySizeException.
+ // Note that very likely this will simply then hit
+ // an OOME, but at least that's more indicative to
+ // caller that this values is too big. We don't +1
+ // in this case, but it's very unlikely in practice
+ // one will actually insert this many objects into
+ // the PQ:
+ // Throw exception to prevent confusing OOME:
+ throw new IllegalArgumentException("maxSize must be <= " + ArrayUtil.MAX_ARRAY_LENGTH + "; got: " + maxSize);
+ } else {
+ // NOTE: we add +1 because all access to heap is
+ // 1-based not 0-based. heap[0] is unused.
+ heapSize = maxSize + 1;
+ }
+ }
+ // T is unbounded type, so this unchecked cast works always:
+ @SuppressWarnings("unchecked") final T[] h = (T[]) new Object[heapSize];
+ this.heap = h;
+ this.maxSize = maxSize;
+
+ if (prepopulate) {
+ // If sentinel objects are supported, populate the queue with them
+ T sentinel = getSentinelObject();
+ if (sentinel != null) {
+ heap[1] = sentinel;
+ for (int i = 2; i < heap.length; i++) {
+ heap[i] = getSentinelObject();
+ }
+ size = maxSize;
+ }
+ }
+ }
+
+ /** Determines the ordering of objects in this priority queue. Subclasses
+ * must define this one method.
+ * @return <code>true</code> iff parameter <tt>a</tt> is less than parameter <tt>b</tt>.
+ */
+ protected abstract boolean lessThan(T a, T b);
+
+
+ protected T getSentinelObject() {
+ return null;
+ }
+
+ /**
+ * Adds an Object to a PriorityQueue in log(size) time. If one tries to add
+ * more objects than maxSize from initialize an
+ *
+ * @return the new 'top' element in the queue.
+ */
+ public final T add(T element) {
+ size++;
+ heap[size] = element;
+ upHeap();
+ return heap[1];
+ }
+
+ /**
+ * Adds an Object to a PriorityQueue in log(size) time.
+ * It returns the object (if any) that was
+ * dropped off the heap because it was full. This can be
+ * the given parameter (in case it is smaller than the
+ * full heap's minimum, and couldn't be added), or another
+ * object that was previously the smallest value in the
+ * heap and now has been replaced by a larger one, or null
+ * if the queue wasn't yet full with maxSize elements.
+ */
+ public T insertWithOverflow(T element) {
+ if (size < maxSize) {
+ add(element);
+ return null;
+ } else if (size > 0 && !lessThan(element, heap[1])) {
+ T ret = heap[1];
+ heap[1] = element;
+ updateTop();
+ return ret;
+ } else {
+ return element;
+ }
+ }
+
+ /** Returns the least element of the PriorityQueue in constant time. */
+ public final T top() {
+ // We don't need to check size here: if maxSize is 0,
+ // then heap is length 2 array with both entries null.
+ // If size is 0 then heap[1] is already null.
+ return heap[1];
+ }
+
+ /** Removes and returns the least element of the PriorityQueue in log(size)
+ time. */
+ public final T pop() {
+ if (size > 0) {
+ T result = heap[1]; // save first value
+ heap[1] = heap[size]; // move last to first
+ heap[size] = null; // permit GC of objects
+ size--;
+ downHeap(); // adjust heap
+ return result;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Should be called when the Object at top changes values. Still log(n) worst
+ * case, but it's at least twice as fast to
+ *
+ * <pre class="prettyprint">
+ * pq.top().change();
+ * pq.updateTop();
+ * </pre>
+ *
+ * instead of
+ *
+ * <pre class="prettyprint">
+ * o = pq.pop();
+ * o.change();
+ * pq.push(o);
+ * </pre>
+ *
+ * @return the new 'top' element.
+ */
+ public final T updateTop() {
+ downHeap();
+ return heap[1];
+ }
+
+ /** Returns the number of elements currently stored in the PriorityQueue. */
+ public final int size() {
+ return size;
+ }
+
+ /** Removes all entries from the PriorityQueue. */
+ public final void clear() {
+ for (int i = 0; i <= size; i++) {
+ heap[i] = null;
+ }
+ size = 0;
+ }
+
+ private final void upHeap() {
+ int i = size;
+ T node = heap[i]; // save bottom node
+ int j = i >>> 1;
+ while (j > 0 && lessThan(node, heap[j])) {
+ heap[i] = heap[j]; // shift parents down
+ i = j;
+ j = j >>> 1;
+ }
+ heap[i] = node; // install saved node
+ }
+
+ private final void downHeap() {
+ int i = 1;
+ T node = heap[i]; // save top node
+ int j = i << 1; // find smaller child
+ int k = j + 1;
+ if (k <= size && lessThan(heap[k], heap[j])) {
+ j = k;
+ }
+ while (j <= size && lessThan(heap[j], node)) {
+ heap[i] = heap[j]; // shift up child
+ i = j;
+ j = i << 1;
+ k = j + 1;
+ if (k <= size && lessThan(heap[k], heap[j])) {
+ j = k;
+ }
+ }
+ heap[i] = node; // install saved node
+ }
+
+ /** This method returns the internal heap array as Object[].
+ * @lucene.internal
+ */
+ public final Object[] getHeapArray() {
+ return (Object[]) heap;
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/SortDoc.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/SortDoc.java b/solr/core/src/java/org/apache/solr/handler/export/SortDoc.java
new file mode 100644
index 0000000..3cf478b
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/SortDoc.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.LeafReaderContext;
+
+class SortDoc {
+
+ protected int docId = -1;
+ protected int ord = -1;
+ protected int docBase = -1;
+
+ private SortValue[] sortValues;
+
+ public SortDoc(SortValue[] sortValues) {
+ this.sortValues = sortValues;
+ }
+
+ public void setNextReader(LeafReaderContext context) throws IOException {
+ this.ord = context.ord;
+ this.docBase = context.docBase;
+ for (SortValue value : sortValues) {
+ value.setNextReader(context);
+ }
+ }
+
+ public void reset() {
+ this.docId = -1;
+ for (SortValue value : sortValues) {
+ value.reset();
+ }
+ }
+
+ public void setValues(int docId) throws IOException {
+ this.docId = docId;
+ for(SortValue sortValue : sortValues) {
+ sortValue.setCurrentValue(docId);
+ }
+ }
+
+ public void setValues(SortDoc sortDoc) {
+ this.docId = sortDoc.docId;
+ this.ord = sortDoc.ord;
+ this.docBase = sortDoc.docBase;
+ SortValue[] vals = sortDoc.sortValues;
+ for(int i=0; i<vals.length; i++) {
+ sortValues[i].setCurrentValue(vals[i]);
+ }
+ }
+
+ public SortDoc copy() {
+ SortValue[] svs = new SortValue[sortValues.length];
+ for(int i=0; i<sortValues.length; i++) {
+ svs[i] = sortValues[i].copy();
+ }
+
+ return new SortDoc(svs);
+ }
+
+ public boolean lessThan(Object o) {
+ if(docId == -1) {
+ return true;
+ }
+ SortDoc sd = (SortDoc)o;
+ SortValue[] sortValues1 = sd.sortValues;
+ for(int i=0; i<sortValues.length; i++) {
+ int comp = sortValues[i].compareTo(sortValues1[i]);
+ if(comp < 0) {
+ return true;
+ } if(comp > 0) {
+ return false;
+ }
+ }
+ return docId+docBase > sd.docId+sd.docBase; //index order
+ }
+
+ public int compareTo(Object o) {
+ SortDoc sd = (SortDoc)o;
+ for (int i=0; i<sortValues.length; i++) {
+ int comp = sortValues[i].compareTo(sd.sortValues[i]);
+ if (comp != 0) {
+ return comp;
+ }
+ }
+ return 0;
+ }
+
+
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("docId: " + docId + "; ");
+ for (int i=0; i < sortValues.length; i++) {
+ builder.append("value" + i + ": " + sortValues[i] + ", ");
+ }
+ return builder.toString();
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/SortQueue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/SortQueue.java b/solr/core/src/java/org/apache/solr/handler/export/SortQueue.java
new file mode 100644
index 0000000..cf99d53
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/SortQueue.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+class SortQueue extends PriorityQueue<SortDoc> {
+
+ private SortDoc proto;
+ private Object[] cache;
+
+ public SortQueue(int len, SortDoc proto) {
+ super(len);
+ this.proto = proto;
+ }
+
+ protected boolean lessThan(SortDoc t1, SortDoc t2) {
+ return t1.lessThan(t2);
+ }
+
+ protected void populate() {
+ Object[] heap = getHeapArray();
+ cache = new SortDoc[heap.length];
+ for (int i = 1; i < heap.length; i++) {
+ cache[i] = heap[i] = proto.copy();
+ }
+ size = maxSize;
+ }
+
+ protected void reset() {
+ Object[] heap = getHeapArray();
+ if(cache != null) {
+ System.arraycopy(cache, 1, heap, 1, heap.length-1);
+ size = maxSize;
+ } else {
+ populate();
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/SortValue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/SortValue.java b/solr/core/src/java/org/apache/solr/handler/export/SortValue.java
new file mode 100644
index 0000000..98afd0a
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/SortValue.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.LeafReaderContext;
+
+public interface SortValue extends Comparable<SortValue> {
+ public void setCurrentValue(int docId) throws IOException;
+ public void setNextReader(LeafReaderContext context) throws IOException;
+ public void setCurrentValue(SortValue value);
+ public void reset();
+ public SortValue copy();
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/StringFieldWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/StringFieldWriter.java b/solr/core/src/java/org/apache/solr/handler/export/StringFieldWriter.java
new file mode 100644
index 0000000..9008f71
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/StringFieldWriter.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.CharsRefBuilder;
+import org.apache.solr.common.MapWriter;
+import org.apache.solr.schema.FieldType;
+
+class StringFieldWriter extends FieldWriter {
+ private String field;
+ private FieldType fieldType;
+ private CharsRefBuilder cref = new CharsRefBuilder();
+
+ public StringFieldWriter(String field, FieldType fieldType) {
+ this.field = field;
+ this.fieldType = fieldType;
+ }
+
+ public boolean write(int docId, LeafReader reader, MapWriter.EntryWriter ew, int fieldIndex) throws IOException {
+ SortedDocValues vals = DocValues.getSorted(reader, this.field);
+ if (vals.advance(docId) != docId) {
+ return false;
+ }
+ int ord = vals.ordValue();
+
+ BytesRef ref = vals.lookupOrd(ord);
+ fieldType.indexedToReadable(ref, cref);
+ ew.put(this.field, cref.toString());
+ return true;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/StringValue.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/StringValue.java b/solr/core/src/java/org/apache/solr/handler/export/StringValue.java
new file mode 100644
index 0000000..23b1413
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/StringValue.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.handler.export;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.MultiDocValues;
+import org.apache.lucene.index.OrdinalMap;
+import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.util.LongValues;
+
+class StringValue implements SortValue {
+
+ protected SortedDocValues globalDocValues;
+
+ protected OrdinalMap ordinalMap;
+ protected LongValues toGlobal = LongValues.IDENTITY; // this segment to global ordinal. NN;
+ protected SortedDocValues docValues;
+
+ protected String field;
+ protected int currentOrd;
+ protected IntComp comp;
+ protected int lastDocID;
+
+ public StringValue(SortedDocValues globalDocValues, String field, IntComp comp) {
+ this.globalDocValues = globalDocValues;
+ this.docValues = globalDocValues;
+ if (globalDocValues instanceof MultiDocValues.MultiSortedDocValues) {
+ this.ordinalMap = ((MultiDocValues.MultiSortedDocValues) globalDocValues).mapping;
+ }
+ this.field = field;
+ this.comp = comp;
+ this.currentOrd = comp.resetValue();
+ }
+
+ public StringValue copy() {
+ return new StringValue(globalDocValues, field, comp);
+ }
+
+ public void setCurrentValue(int docId) throws IOException {
+ if (docId < lastDocID) {
+ throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId);
+ }
+
+ lastDocID = docId;
+
+ if (docId > docValues.docID()) {
+ docValues.advance(docId);
+ }
+ if (docId == docValues.docID()) {
+ currentOrd = (int) toGlobal.get(docValues.ordValue());
+ } else {
+ currentOrd = -1;
+ }
+ }
+
+ public void setCurrentValue(SortValue sv) {
+ StringValue v = (StringValue)sv;
+ this.currentOrd = v.currentOrd;
+ }
+
+ public void setNextReader(LeafReaderContext context) throws IOException {
+ if (globalDocValues instanceof MultiDocValues.MultiSortedDocValues) {
+ toGlobal = ordinalMap.getGlobalOrds(context.ord);
+ docValues = DocValues.getSorted(context.reader(), field);
+ }
+ lastDocID = 0;
+ }
+
+ public void reset() {
+ this.currentOrd = comp.resetValue();
+ }
+
+ public int compareTo(SortValue o) {
+ StringValue sv = (StringValue)o;
+ return comp.compare(currentOrd, sv.currentOrd);
+ }
+
+ public String toString() {
+ return Integer.toString(this.currentOrd);
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/java/org/apache/solr/handler/export/package-info.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/export/package-info.java b/solr/core/src/java/org/apache/solr/handler/export/package-info.java
new file mode 100644
index 0000000..a516904
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/handler/export/package-info.java
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Solr's Export Handler Functionality
+ */
+package org.apache.solr.handler.export;
+
+
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/test-files/solr/collection1/conf/schema-sortingresponse.xml
----------------------------------------------------------------------
diff --git a/solr/core/src/test-files/solr/collection1/conf/schema-sortingresponse.xml b/solr/core/src/test-files/solr/collection1/conf/schema-sortingresponse.xml
index c45f178..57e684d 100644
--- a/solr/core/src/test-files/solr/collection1/conf/schema-sortingresponse.xml
+++ b/solr/core/src/test-files/solr/collection1/conf/schema-sortingresponse.xml
@@ -40,7 +40,7 @@
<fieldType name="uuid" class="solr.UUIDField"/>
- <field name="id" type="string" required="true" indexed="true"/>
+ <field name="id" type="string" required="true" indexed="true" docValues="true"/>
<field name="floatdv_m" type="float" indexed="false" stored="false" docValues="true" multiValued="true"/>
<field name="intdv_m" type="int" indexed="false" stored="false" docValues="true" multiValued="true"/>
<field name="doubledv_m" type="double" indexed="false" stored="false" docValues="true" multiValued="true"/>
@@ -54,6 +54,9 @@
<field name="longdv" type="long" indexed="false" stored="false" docValues="true"/>
<field name="datedv" type="date" indexed="false" stored="false" docValues="true"/>
<field name="stringdv" type="string" indexed="false" stored="false" docValues="true"/>
+ <field name="booleandv" type="boolean" indexed="false" stored="false" docValues="true" />
+
+ <dynamicField name="*_s_dv" type="string" indexed="true" stored="true" docValues="true" multiValued="false"/>
<!-- Point fields explicitly -->
<dynamicField name="*_i_p" type="pint" indexed="true" stored="true" docValues="true" multiValued="false"/>
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9d9c3a0c/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
new file mode 100644
index 0000000..55efdee
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
@@ -0,0 +1,749 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.handler.export;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.apache.lucene.util.TestUtil;
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.common.util.SuppressForbidden;
+import org.apache.solr.common.util.Utils;
+import org.apache.solr.request.SolrQueryRequest;
+import org.apache.solr.response.ResultContext;
+import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.schema.SchemaField;
+import org.apache.solr.search.DocIterator;
+import org.apache.solr.search.DocList;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class TestExportWriter extends SolrTestCaseJ4 {
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ System.setProperty("export.test", "true");
+ initCore("solrconfig-sortingresponse.xml","schema-sortingresponse.xml");
+ }
+
+ @Before
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ assertU(delQ("*:*"));
+ assertU(commit());
+ createIndex();
+ }
+
+ public static void createIndex() {
+ assertU(adoc("id","1",
+ "floatdv","2.1",
+ "intdv", "1",
+ "stringdv", "hello world",
+ "longdv", "323223232323",
+ "doubledv","2344.345",
+ "intdv_m","100",
+ "intdv_m","250",
+ "floatdv_m", "123.321",
+ "floatdv_m", "345.123",
+ "doubledv_m", "3444.222",
+ "doubledv_m", "23232.2",
+ "longdv_m", "43434343434",
+ "longdv_m", "343332",
+ "stringdv_m", "manchester \"city\"",
+ "stringdv_m", "liverpool",
+ "stringdv_m", "Everton",
+ "datedv", "2017-06-16T07:00:00Z",
+ "datedv_m", "2017-06-16T01:00:00Z",
+ "datedv_m", "2017-06-16T02:00:00Z",
+ "datedv_m", "2017-06-16T03:00:00Z",
+ "datedv_m", "2017-06-16T04:00:00Z"));
+
+ assertU(adoc("id","7",
+ "floatdv","2.1",
+ "intdv", "7",
+ "longdv", "323223232323",
+ "doubledv","2344.345",
+ "floatdv_m", "123.321",
+ "floatdv_m", "345.123",
+ "doubledv_m", "3444.222",
+ "doubledv_m", "23232.2",
+ "longdv_m", "43434343434",
+ "longdv_m", "343332"));
+
+ assertU(commit());
+ assertU(adoc("id","2", "floatdv","2.1", "intdv", "2", "stringdv", "hello world", "longdv", "323223232323","doubledv","2344.344"));
+ assertU(commit());
+ assertU(adoc("id","3",
+ "floatdv","2.1",
+ "intdv", "3",
+ "stringdv", "chello world",
+ "longdv", "323223232323",
+ "doubledv","2344.346",
+ "intdv_m","100",
+ "intdv_m","250",
+ "floatdv_m", "123.321",
+ "floatdv_m", "345.123",
+ "doubledv_m", "3444.222",
+ "doubledv_m", "23232.2",
+ "longdv_m", "43434343434",
+ "longdv_m", "343332",
+ "stringdv_m", "manchester \"city\"",
+ "stringdv_m", "liverpool",
+ "stringdv_m", "everton",
+ "int_is_t", "1",
+ "int_is_t", "1",
+ "int_is_t", "1",
+ "int_is_t", "1"));
+ assertU(commit());
+ assertU(adoc("id","8",
+ "floatdv","2.1",
+ "intdv", "10000000",
+ "stringdv", "chello \"world\"",
+ "longdv", "323223232323",
+ "doubledv","2344.346",
+ "intdv_m","100",
+ "intdv_m","250",
+ "floatdv_m", "123.321",
+ "floatdv_m", "345.123",
+ "doubledv_m", "3444.222",
+ "doubledv_m", "23232.2",
+ "longdv_m", "43434343434",
+ "longdv_m", "343332",
+ "stringdv_m", "manchester \"city\"",
+ "stringdv_m", "liverpool",
+ "stringdv_m", "everton",
+ "datedv", "2017-01-01T00:00:00Z",
+ "datedv_m", "2017-01-01T01:00:00Z",
+ "datedv_m", "2017-01-01T02:00:00Z",
+ "int_is_p", "1",
+ "int_is_p", "1",
+ "int_is_p", "1",
+ "int_is_p", "1"));
+ assertU(commit());
+
+
+ }
+
+ @Test
+ public void testSmallChains() throws Exception {
+ clearIndex();
+
+ assertU(adoc("id","1",
+ "field1_i_p",Integer.toString(Integer.MIN_VALUE),
+ "field2_i_p","1"));
+ assertU(commit());
+
+ assertU(adoc("id","2",
+ "field1_i_p",Integer.toString(Integer.MIN_VALUE),
+ "field2_i_p",Integer.toString(Integer.MIN_VALUE + 1)));
+ assertU(commit());
+
+ assertU(adoc("id","3",
+ "field1_i_p",Integer.toString(Integer.MIN_VALUE),
+ "field2_i_p",Integer.toString(Integer.MIN_VALUE)));
+ assertU(commit());
+
+ //Test single value DocValue output
+ //Expected for asc sort doc3 -> doc2 -> doc1
+ String s = h.query(req("q", "*:*", "qt", "/export", "fl", "id", "sort", "field1_i_p asc,field2_i_p asc"));
+ assertJsonEquals(s, "{\n" +
+ " \"responseHeader\":{\"status\":0},\n" +
+ " \"response\":{\n" +
+ " \"numFound\":3,\n" +
+ " \"docs\":[{\n" +
+ " \"id\":\"3\"}\n" +
+ " ,{\n" +
+ " \"id\":\"2\"}\n" +
+ " ,{\n" +
+ " \"id\":\"1\"}]}}");
+
+ clearIndex();
+ //Adding 3 docs of integers with the following values
+ // doc1: Integer.MIN_VALUE,1,2,Integer.MAX_VALUE,3,4,5,6
+ // doc2: Integer.MIN_VALUE,Integer.MIN_VALUE,2,Integer.MAX_VALUE,4,4,5,6
+ // doc3: Integer.MIN_VALUE,Integer.MIN_VALUE,2,Integer.MAX_VALUE,3,4,5,6
+
+ assertU(adoc("id","1",
+ "field1_i_p",Integer.toString(Integer.MIN_VALUE),
+ "field2_i_p","1",
+ "field3_i_p","2",
+ "field4_i_p",Integer.toString(Integer.MAX_VALUE),
+ "field5_i_p","3",
+ "field6_i_p","4",
+ "field7_i_p","5",
+ "field8_i_p","6"));
+ assertU(commit());
+
+ assertU(adoc("id","2",
+ "field1_i_p",Integer.toString(Integer.MIN_VALUE),
+ "field2_i_p",Integer.toString(Integer.MIN_VALUE),
+ "field3_i_p","2",
+ "field4_i_p",Integer.toString(Integer.MAX_VALUE),
+ "field5_i_p","4",
+ "field6_i_p","4",
+ "field7_i_p","5",
+ "field8_i_p","6"));
+ assertU(commit());
+
+ assertU(adoc("id","3",
+ "field1_i_p",Integer.toString(Integer.MIN_VALUE),
+ "field2_i_p",Integer.toString(Integer.MIN_VALUE),
+ "field3_i_p","2",
+ "field4_i_p",Integer.toString(Integer.MAX_VALUE),
+ "field5_i_p","3",
+ "field6_i_p","4",
+ "field7_i_p","5",
+ "field8_i_p","6"));
+ assertU(commit());
+
+ s = h.query(req("q", "*:*", "qt", "/export", "fl", "id", "sort", "field1_i_p asc,field2_i_p asc,field3_i_p asc,field4_i_p asc,field5_i_p desc,field6_i_p desc,field7_i_p desc,field8_i_p asc"));
+ assertJsonEquals(s, "{\n" +
+ " \"responseHeader\":{\"status\":0},\n" +
+ " \"response\":{\n" +
+ " \"numFound\":3,\n" +
+ " \"docs\":[{\n" +
+ " \"id\":\"2\"}\n" +
+ " ,{\n" +
+ " \"id\":\"3\"}\n" +
+ " ,{\n" +
+ " \"id\":\"1\"}]}}");
+
+ }
+
+ @Test
+ public void testIndexOrder() throws Exception {
+ clearIndex();
+
+ assertU(adoc("id","1", "stringdv","a"));
+ assertU(adoc("id","2", "stringdv","a"));
+
+ assertU(commit());
+
+ assertU(adoc("id","3", "stringdv","a"));
+ assertU(adoc("id","4", "stringdv","a"));
+
+ assertU(commit());
+
+ String expectedResult = "{\n" +
+ " \"responseHeader\":{\"status\":0},\n" +
+ " \"response\":{\n" +
+ " \"numFound\":4,\n" +
+ " \"docs\":[{\n" +
+ " \"id\":\"1\"}\n" +
+ " ,{\n" +
+ " \"id\":\"2\"}\n" +
+ " ,{\n" +
+ " \"id\":\"3\"}\n" +
+ " ,{\n" +
+ " \"id\":\"4\"}]}}";
+
+ String s = h.query(req("q", "*:*", "qt", "/export", "fl", "id", "sort", "stringdv asc"));
+ assertJsonEquals(s, expectedResult);
+
+ s = h.query(req("q", "*:*", "qt", "/export", "fl", "id", "sort", "stringdv desc"));
+ assertJsonEquals(s, expectedResult);
+
+ }
+
+ @Test
+ public void testStringWithCase() throws Exception {
+ clearIndex();
+
+ assertU(adoc("id","1", "stringdv","a"));
+ assertU(adoc("id","2", "stringdv","ABC"));
+
+ assertU(commit());
+
+ assertU(adoc("id","3", "stringdv","xyz"));
+ assertU(adoc("id","4", "stringdv","a"));
+
+ assertU(commit());
+
+ String s = h.query(req("q", "*:*", "qt", "/export", "fl", "id", "sort", "stringdv desc"));
+ assertJsonEquals(s, "{\n" +
+ " \"responseHeader\":{\"status\":0},\n" +
+ " \"response\":{\n" +
+ " \"numFound\":4,\n" +
+ " \"docs\":[{\n" +
+ " \"id\":\"3\"}\n" +
+ " ,{\n" +
+ " \"id\":\"1\"}\n" +
+ " ,{\n" +
+ " \"id\":\"4\"}\n" +
+ " ,{\n" +
+ " \"id\":\"2\"}]}}");
+ }
+
+ @Test
+ public void testBooleanField() throws Exception {
+ clearIndex();
+
+ assertU(adoc("id","1",
+ "booleandv","true"));
+ assertU(commit());
+
+ assertU(adoc("id","2",
+ "booleandv","false"));
+ assertU(commit());
+
+ String s = h.query(req("q", "*:*", "qt", "/export", "fl", "id", "sort", "booleandv asc"));
+ assertJsonEquals(s, "{\n" +
+ " \"responseHeader\":{\"status\":0},\n" +
+ " \"response\":{\n" +
+ " \"numFound\":2,\n" +
+ " \"docs\":[{\n" +
+ " \"id\":\"2\"}\n" +
+ " ,{\n" +
+ " \"id\":\"1\"}]}}");
+
+ s = h.query(req("q", "*:*", "qt", "/export", "fl", "id", "sort", "booleandv desc"));
+ assertJsonEquals(s, "{\n" +
+ " \"responseHeader\":{\"status\":0},\n" +
+ " \"response\":{\n" +
+ " \"numFound\":2,\n" +
+ " \"docs\":[{\n" +
+ " \"id\":\"1\"}\n" +
+ " ,{\n" +
+ " \"id\":\"2\"}]}}");
+ }
+
+ @Test
+ public void testSortingOutput() throws Exception {
+
+ //Test single value DocValue output
+ String s = h.query(req("q", "id:1", "qt", "/export", "fl", "floatdv,intdv,stringdv,longdv,doubledv", "sort", "intdv asc"));
+
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"floatdv\":2.1,\"intdv\":1,\"stringdv\":\"hello world\",\"longdv\":323223232323,\"doubledv\":2344.345}]}}");
+
+ //Test null value string:
+ s = h.query(req("q", "id:7", "qt", "/export", "fl", "floatdv,intdv,stringdv,longdv,doubledv", "sort", "intdv asc"));
+
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"floatdv\":2.1,\"intdv\":7,\"longdv\":323223232323,\"doubledv\":2344.345}]}}");
+
+ //Test multiValue docValues output
+ s = h.query(req("q", "id:1", "qt", "/export", "fl", "intdv_m,floatdv_m,doubledv_m,longdv_m,stringdv_m", "sort", "intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"intdv_m\":[100,250],\"floatdv_m\":[123.321,345.123],\"doubledv_m\":[3444.222,23232.2],\"longdv_m\":[343332,43434343434],\"stringdv_m\":[\"Everton\",\"liverpool\",\"manchester \\\"city\\\"\"]}]}}");
+
+ //Test multiValues docValues output with nulls
+ s = h.query(req("q", "id:7", "qt", "/export", "fl", "intdv_m,floatdv_m,doubledv_m,longdv_m,stringdv_m", "sort", "intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"floatdv_m\":[123.321,345.123],\"doubledv_m\":[3444.222,23232.2],\"longdv_m\":[343332,43434343434]}]}}");
+
+ //Test single sort param is working
+ s = h.query(req("q", "id:(1 2)", "qt", "/export", "fl", "intdv", "sort", "intdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":2},{\"intdv\":1}]}}");
+
+ s = h.query(req("q", "id:(1 2)", "qt", "/export", "fl", "intdv", "sort", "intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":1},{\"intdv\":2}]}}");
+
+ // Test sort on String will null value. Null value should sort last on desc and first on asc.
+
+ s = h.query(req("q", "id:(1 7)", "qt", "/export", "fl", "intdv", "sort", "stringdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":1},{\"intdv\":7}]}}");
+
+ s = h.query(req("q", "id:(1 7)", "qt", "/export", "fl", "intdv", "sort", "stringdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":7},{\"intdv\":1}]}}");
+
+
+ //Test multi-sort params
+ s = h.query(req("q", "id:(1 2)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,intdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":2},{\"intdv\":1}]}}");
+
+ s = h.query(req("q", "id:(1 2)", "qt", "/export", "fl", "intdv", "sort", "floatdv desc,intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":2, \"docs\":[{\"intdv\":1},{\"intdv\":2}]}}");
+
+ //Test three sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,stringdv asc,intdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
+
+ //Test three sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,stringdv desc,intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":1},{\"intdv\":2},{\"intdv\":3}]}}");
+
+ //Test four sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,floatdv desc,floatdv asc,intdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
+
+ //Test five sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "intdv desc,floatdv asc,floatdv desc,floatdv asc,intdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv desc,intdv asc,floatdv desc,floatdv desc,intdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":1},{\"intdv\":2},{\"intdv\":3}]}}");
+
+ //Test six sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,intdv desc,floatdv asc,floatdv desc,floatdv asc,intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
+
+ //Test seven sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv desc,intdv asc,floatdv desc,floatdv asc,floatdv desc,floatdv asc,intdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":1},{\"intdv\":2},{\"intdv\":3}]}}");
+
+ //Test eight sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,intdv desc,floatdv asc,floatdv desc,floatdv asc,floatdv desc,floatdv asc,intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "intdv asc,floatdv desc,floatdv asc,floatdv desc,floatdv asc,floatdv desc,floatdv asc,intdv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":1},{\"intdv\":2},{\"intdv\":3}]}}");
+
+ //Test nine sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "intdv asc,floatdv desc,floatdv asc,floatdv desc,floatdv asc,floatdv desc,intdv asc,intdv desc,floatdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":1},{\"intdv\":2},{\"intdv\":3}]}}");
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,intdv desc,floatdv asc,floatdv desc,floatdv asc,floatdv desc,intdv desc,intdv asc,floatdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
+
+ //Test ten sort fields
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "intdv asc,floatdv desc,floatdv asc,floatdv desc,floatdv asc,floatdv desc,intdv asc,intdv desc,floatdv desc,floatdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":1},{\"intdv\":2},{\"intdv\":3}]}}");
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "floatdv asc,intdv desc,floatdv asc,floatdv desc,floatdv asc,floatdv desc,intdv desc,intdv asc,floatdv desc,floatdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":2},{\"intdv\":1}]}}");
+
+ s = h.query(req("q", "id:(1 2 3)", "qt", "/export", "fl", "intdv", "sort", "doubledv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":1},{\"intdv\":2}]}}");
+
+ s = h.query(req("q", "intdv:[2 TO 1000]", "qt", "/export", "fl", "intdv", "sort", "doubledv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":3, \"docs\":[{\"intdv\":3},{\"intdv\":7},{\"intdv\":2}]}}");
+
+ s = h.query(req("q", "stringdv:blah", "qt", "/export", "fl", "intdv", "sort", "doubledv desc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":0, \"docs\":[]}}");
+
+ s = h.query(req("q", "id:8", "qt", "/export", "fl", "stringdv", "sort", "intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"stringdv\":\"chello \\\"world\\\"\"}]}}");
+ }
+
+ private void assertJsonEquals(String actual, String expected) {
+ assertEquals(Utils.toJSONString(Utils.fromJSONString(expected)), Utils.toJSONString(Utils.fromJSONString(actual)));
+ }
+
+ @Test
+ public void testExportRequiredParams() throws Exception {
+
+ //Test whether missing required parameters returns expected errors.
+
+ //String s = h.query(req("q", "id:1", "qt", "/export", "fl", "floatdv,intdv,stringdv,longdv,doubledv", "sort", "intdv asc"));
+ String s;
+ s = h.query(req("qt", "/export"));
+ assertTrue("Should have had a sort error", s.contains("No sort criteria"));
+ s = h.query(req("sort", "intdv asc", "qt", "/export"));
+ assertTrue("Should have had fl error", s.contains("export field list (fl) must be specified"));
+ s = h.query(req("sort", "intdv asc", "qt", "/export", "fl", "stringdv"));
+ // Interesting you don't even need to specify a "q" parameter.
+
+ }
+
+ @Test
+ public void testDates() throws Exception {
+ String s = h.query(req("q", "id:1", "qt", "/export", "fl", "datedv", "sort", "datedv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"datedv\":\"2017-06-16T07:00:00Z\"}]}}");
+ s = h.query(req("q", "id:1", "qt", "/export", "fl", "datedv_m", "sort", "datedv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"datedv_m\":[\"2017-06-16T01:00:00Z\",\"2017-06-16T02:00:00Z\",\"2017-06-16T03:00:00Z\",\"2017-06-16T04:00:00Z\"]}]}}");
+ }
+
+ @Test
+ public void testDuplicates() throws Exception {
+ // see SOLR-10924
+ String expected = h.getCore().getLatestSchema().getField("int_is_t").getType().isPointField()
+ ? "1,1,1,1" : "1";
+ String s = h.query(req("q", "id:3", "qt", "/export", "fl", "int_is_t", "sort", "intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"int_is_t\":["+expected+"]}]}}");
+ expected = h.getCore().getLatestSchema().getField("int_is_p").getType().isPointField()
+ ? "1,1,1,1" : "1";
+ s = h.query(req("q", "id:8", "qt", "/export", "fl", "int_is_p", "sort", "intdv asc"));
+ assertJsonEquals(s, "{\"responseHeader\": {\"status\": 0}, \"response\":{\"numFound\":1, \"docs\":[{\"int_is_p\":[1,1,1,1]}]}}");
+ }
+
+ /**
+ * This test doesn't validate the correctness of results, it just compares the response of the same request
+ * when asking for Trie fields vs Point fields. Can be removed once Trie fields are no longer supported
+ */
+ @Test
+ @SuppressForbidden(reason="using new Date(time) to create random dates")
+ public void testRandomNumerics() throws Exception {
+ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
+ assertU(delQ("*:*"));
+ assertU(commit());
+ List<String> trieFields = new ArrayList<String>();
+ List<String> pointFields = new ArrayList<String>();
+ for (String mv:new String[]{"s", ""}) {
+ for (String indexed:new String[]{"_ni", ""}) {
+ for (String type:new String[]{"i", "l", "f", "d", "dt"}) {
+ String field = "number_" + type + mv + indexed;
+ SchemaField sf = h.getCore().getLatestSchema().getField(field + "_t");
+ assertTrue(sf.hasDocValues());
+ assertTrue(sf.getType().getNumberType() != null);
+
+ sf = h.getCore().getLatestSchema().getField(field + "_p");
+ assertTrue(sf.hasDocValues());
+ assertTrue(sf.getType().getNumberType() != null);
+ assertTrue(sf.getType().isPointField());
+
+ trieFields.add(field + "_t");
+ pointFields.add(field + "_p");
+ }
+ }
+ }
+ for (int i = 0; i < atLeast(100); i++) {
+ if (random().nextInt(20) == 0) {
+ //have some empty docs
+ assertU(adoc("id", String.valueOf(i)));
+ continue;
+ }
+
+ if (random().nextInt(20) == 0 && i > 0) {
+ //delete some docs
+ assertU(delI(String.valueOf(i - 1)));
+ }
+
+ SolrInputDocument doc = new SolrInputDocument();
+ doc.addField("id", String.valueOf(i));
+ addInt(doc, random().nextInt(), false);
+ addLong(doc, random().nextLong(), false);
+ addFloat(doc, random().nextFloat() * 3000 * (random().nextBoolean()?1:-1), false);
+ addDouble(doc, random().nextDouble() * 3000 * (random().nextBoolean()?1:-1), false);
+ addDate(doc, dateFormat.format(new Date()), false);
+
+ // MV need to be unique in order to be the same in Trie vs Points
+ Set<Integer> ints = new HashSet<>();
+ Set<Long> longs = new HashSet<>();
+ Set<Float> floats = new HashSet<>();
+ Set<Double> doubles = new HashSet<>();
+ Set<String> dates = new HashSet<>();
+ for (int j=0; j < random().nextInt(20); j++) {
+ ints.add(random().nextInt());
+ longs.add(random().nextLong());
+ floats.add(random().nextFloat() * 3000 * (random().nextBoolean()?1:-1));
+ doubles.add(random().nextDouble() * 3000 * (random().nextBoolean()?1:-1));
+ dates.add(dateFormat.format(new Date(System.currentTimeMillis() + random().nextInt())));
+ }
+ ints.stream().forEach((val)->addInt(doc, val, true));
+ longs.stream().forEach((val)->addLong(doc, val, true));
+ floats.stream().forEach((val)->addFloat(doc, val, true));
+ doubles.stream().forEach((val)->addDouble(doc, val, true));
+ dates.stream().forEach((val)->addDate(doc, val, true));
+
+ assertU(adoc(doc));
+ if (random().nextInt(20) == 0) {
+ assertU(commit());
+ }
+ }
+ assertU(commit());
+ doTestQuery("id:1", trieFields, pointFields);
+ doTestQuery("*:*", trieFields, pointFields);
+ doTestQuery("id:[0 TO 2]", trieFields, pointFields);// "id" field is really a string, this is not a numeric range query
+ doTestQuery("id:[0 TO 9]", trieFields, pointFields);
+ doTestQuery("id:DOES_NOT_EXIST", trieFields, pointFields);
+ }
+
+ @Test
+ public void testMultipleSorts() throws Exception {
+ assertU(delQ("*:*"));
+ assertU(commit());
+
+ int numDocs = 1000;
+
+ //10 unique values
+ String[] str_vals = new String[10];
+ for (int i=0; i<str_vals.length; i++) {
+ str_vals[i] = TestUtil.randomSimpleString(random(), 10);
+ }
+
+ float[] float_vals = new float[10];
+ float_vals[0] = 0.0f;
+ float_vals[1] = +0.0f;
+ float_vals[2] = -0.0f;
+ float_vals[3] = +0.00001f;
+ float_vals[4] = +0.000011f;
+ float_vals[5] = Float.MAX_VALUE;
+ float_vals[6] = Float.MIN_VALUE;
+ float_vals[7] = 1/3f; //0.33333334
+ float_vals[8] = 0.33333333f;
+ float_vals[9] = random().nextFloat();
+
+ for (int i = 0; i < numDocs; i++) {
+ int number = TestUtil.nextInt(random(), 0, 9);
+ assertU(adoc("id", String.valueOf(i),
+ "floatdv", String.valueOf(number),
+ "intdv", String.valueOf(number),
+ "stringdv", String.valueOf(str_vals[number]),
+ "longdv", String.valueOf(number),
+ "doubledv", String.valueOf(number),
+ "datedv", randomSkewedDate(),
+ "booleandv", String.valueOf(random().nextBoolean()),
+ "field1_s_dv", String.valueOf(str_vals[number]),
+ "field2_i_p", String.valueOf(number),
+ "field3_l_p", String.valueOf(number)));
+ if (numDocs % 3000 ==0) {
+ assertU(commit());
+ }
+ }
+ assertU(commit());
+
+ validateSort(numDocs);
+ }
+
+ private void validateSort(int numDocs) throws Exception {
+ // 10 fields
+ List<String> fieldNames = new ArrayList<>(Arrays.asList("floatdv", "intdv", "stringdv", "longdv", "doubledv",
+ "datedv", "booleandv", "field1_s_dv", "field2_i_p", "field3_l_p"));
+
+ SortFields[] fieldSorts = new SortFields[TestUtil.nextInt(random(), 1, fieldNames.size())];
+ for (int i = 0; i < fieldSorts.length; i++) {
+ fieldSorts[i] = new SortFields(fieldNames.get(TestUtil.nextInt(random(), 0, fieldNames.size() - 1)));
+ fieldNames.remove(fieldSorts[i].getField());
+ }
+ String[] fieldWithOrderStrs = new String[fieldSorts.length];
+ String[] fieldStrs = new String[fieldSorts.length];
+ for (int i = 0; i < fieldSorts.length; i++) {
+ fieldWithOrderStrs[i] = fieldSorts[i].getFieldWithOrder();
+ fieldStrs[i] = fieldSorts[i].getField();
+ }
+
+ String sortStr = String.join(",", fieldWithOrderStrs); // sort : field1 asc, field2 desc
+ String fieldsStr = String.join(",", fieldStrs); // fl : field1, field2
+
+ String resp = h.query(req("q", "*:*", "qt", "/export", "fl", "id," + fieldsStr, "sort", sortStr));
+
+ //We cannot compare /select vs /export as for docs with the same values ( ties ) the ordering is different
+ SolrQueryRequest req = null;
+ try {
+ req = req("q", "*:*", "qt", "/select", "fl", "id," + fieldsStr, "sort", sortStr, "rows", Integer.toString(numDocs));
+
+ SolrQueryResponse selectRsp = h.queryAndResponse("", req);
+ DocList selectDocList = ((ResultContext)selectRsp.getResponse()).getDocList();
+ assert selectDocList.size() == numDocs;
+ DocIterator selectDocListIter = selectDocList.iterator();
+
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap respMap = mapper.readValue(resp, HashMap.class);
+ List docs = (ArrayList) ((HashMap) respMap.get("response")).get("docs");
+ assert docs.size() == numDocs;
+
+ for (int i = 0; i < docs.size() - 1; i++) { // docs..
+ assertEquals("Position:" + i + " has different id value" , String.valueOf(selectDocListIter.nextDoc()), String.valueOf(((HashMap) docs.get(i)).get("id")));
+
+ for (int j = 0; j < fieldSorts.length; j++) { // fields ..
+ String field = fieldSorts[j].getField();
+ String sort = fieldSorts[j].getSort();
+ String fieldVal1 = String.valueOf(((HashMap) docs.get(i)).get(field)); // 1st doc
+ String fieldVal2 = String.valueOf(((HashMap) docs.get(i + 1)).get(field)); // 2nd obj
+ if (fieldVal1.equals(fieldVal2)) {
+ continue;
+ } else {
+ if (sort.equals("asc")) {
+ if (field.equals("stringdv") || field.equals("field1_s_dv")|| field.equals("datedv") || field.equals("booleandv")) { // use string comparator
+ assertTrue(fieldVal1.compareTo(fieldVal2) < 0);
+ } else if (field.equals("doubledv")){
+ assertTrue(Double.compare(Double.valueOf(fieldVal1), Double.valueOf(fieldVal2)) <= 0);
+ } else if(field.equals("floatdv")) {
+ assertTrue(Float.compare(Float.valueOf(fieldVal1), Float.valueOf(fieldVal2)) <= 0);
+ } else if(field.equals("intdv") || "field2_i_p".equals(field)) {
+ assertTrue(Integer.compare(Integer.valueOf(fieldVal1), Integer.valueOf(fieldVal2)) <= 0);
+ } else if(field.equals("longdv") || field.equals("field3_l_p")) {
+ assertTrue(Long.compare(Integer.valueOf(fieldVal1), Long.valueOf(fieldVal2)) <= 0);
+ }
+ } else {
+ if (field.equals("stringdv") || field.equals("field1_s_dv")|| field.equals("datedv") || field.equals("booleandv")) { // use string comparator
+ assertTrue(fieldVal1.compareTo(fieldVal2) > 0);
+ } else if (field.equals("doubledv")){
+ assertTrue(Double.compare(Double.valueOf(fieldVal1), Double.valueOf(fieldVal2)) >= 0);
+ } else if(field.equals("floatdv")) {
+ assertTrue(Float.compare(Float.valueOf(fieldVal1), Float.valueOf(fieldVal2)) >= 0);
+ } else if(field.equals("intdv") || "field2_i_p".equals(field)) {
+ assertTrue(Integer.compare(Integer.valueOf(fieldVal1), Integer.valueOf(fieldVal2)) >= 0);
+ } else if(field.equals("longdv") || field.equals("field3_l_p")) {
+ assertTrue(Long.compare(Integer.valueOf(fieldVal1), Long.valueOf(fieldVal2)) >= 0);
+ }
+ }
+ break;
+ }
+ }
+ }
+ } finally {
+ if (req != null) {
+ req.close();
+ }
+ }
+ }
+
+ private class SortFields {
+ String fieldName;
+ String sortOrder;
+ String[] orders = {"asc", "desc"};
+
+ SortFields(String fn) {
+ this.fieldName = fn;
+ this.sortOrder = orders[random().nextInt(2)];
+ }
+
+ public String getFieldWithOrder() {
+ return this.fieldName + " " + this.sortOrder;
+ }
+
+ public String getField() {
+ return this.fieldName;
+ }
+
+ public String getSort() {
+ return this.sortOrder;
+ }
+ }
+
+ private void doTestQuery(String query, List<String> trieFields, List<String> pointFields) throws Exception {
+ String trieFieldsFl = String.join(",", trieFields);
+ String pointFieldsFl = String.join(",", pointFields);
+ String sort = pickRandom((String)pickRandom(trieFields.toArray()), (String)pickRandom(pointFields.toArray())).replace("s_", "_") + pickRandom(" asc", " desc");
+ String resultPoints = h.query(req("q", query, "qt", "/export", "fl", pointFieldsFl, "sort", sort));
+ String resultTries = h.query(req("q", query, "qt", "/export", "fl", trieFieldsFl, "sort", sort));
+ assertJsonEquals(resultPoints.replaceAll("_p", ""), resultTries.replaceAll("_t", ""));
+ }
+
+ private void addFloat(SolrInputDocument doc, float value, boolean mv) {
+ addField(doc, "f", String.valueOf(value), mv);
+ }
+
+ private void addDouble(SolrInputDocument doc, double value, boolean mv) {
+ addField(doc, "d", String.valueOf(value), mv);
+ }
+
+ private void addLong(SolrInputDocument doc, long value, boolean mv) {
+ addField(doc, "l", String.valueOf(value), mv);
+ }
+
+ private void addInt(SolrInputDocument doc, int value, boolean mv) {
+ addField(doc, "i", String.valueOf(value), mv);
+ }
+
+ private void addDate(SolrInputDocument doc, String value, boolean mv) {
+ addField(doc, "dt", value, mv);
+ }
+
+ private void addField(SolrInputDocument doc, String type, String value, boolean mv) {
+ doc.addField("number_" + type + (mv?"s":"") + "_t", value);
+ doc.addField("number_" + type + (mv?"s":"") + "_p", value);
+ doc.addField("number_" + type + (mv?"s":"") + "_ni_t", value);
+ doc.addField("number_" + type + (mv?"s":"") + "_ni_p", value);
+ }
+
+}
[13/33] lucene-solr:jira/http2: Revert "LUCENE-8306: Allow iteration
over submatches"
Posted by da...@apache.org.
Revert "LUCENE-8306: Allow iteration over submatches"
Incorrect patch committed in error
This reverts commit a8839b7eab122037ed1c1674b2f909666718e331.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/6e3f61f6
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/6e3f61f6
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/6e3f61f6
Branch: refs/heads/jira/http2
Commit: 6e3f61f6f9b42cb11f45b0eb97587f07e5198ba4
Parents: a8839b7
Author: Alan Woodward <ro...@apache.org>
Authored: Sun Jul 22 22:36:46 2018 +0100
Committer: Alan Woodward <ro...@apache.org>
Committed: Sun Jul 22 22:36:46 2018 +0100
----------------------------------------------------------------------
lucene/CHANGES.txt | 3 -
.../search/DisjunctionMatchesIterator.java | 9 -
.../lucene/search/ExactPhraseMatcher.java | 44 ----
.../apache/lucene/search/MatchesIterator.java | 58 -----
.../apache/lucene/search/MultiPhraseQuery.java | 5 +-
.../org/apache/lucene/search/PhraseMatcher.java | 2 -
.../org/apache/lucene/search/PhraseQuery.java | 4 +-
.../org/apache/lucene/search/PhraseWeight.java | 10 -
.../lucene/search/SloppyPhraseMatcher.java | 121 +++------
.../lucene/search/TermMatchesIterator.java | 50 ----
.../apache/lucene/search/spans/SpanWeight.java | 131 ----------
.../lucene/search/TestMatchesIterator.java | 252 +------------------
.../lucene/search/AssertingMatchesIterator.java | 11 -
13 files changed, 44 insertions(+), 656 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 47769cd..8257dbc 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -198,9 +198,6 @@ Improvements
* LUCENE-8345, GitHub PR #392: Remove instantiation of redundant wrapper classes for primitives;
add wrapper class constructors to forbiddenapis. (Michael Braun via Uwe Schindler)
-* LUCENE-8306: Matches API now allows iteration over sub-matches in Spans (Alan Woodward,
- Jim Ferenczi, David Smiley)
-
Other:
* LUCENE-8366: Upgrade to ICU 62.1. Emoji handling now uses Unicode 11's
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
index cff723b..975199b 100644
--- a/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
@@ -158,13 +158,4 @@ final class DisjunctionMatchesIterator implements MatchesIterator {
return queue.top().endOffset();
}
- @Override
- public MatchesIterator getSubMatches() throws IOException {
- return queue.top().getSubMatches();
- }
-
- @Override
- public Object label() {
- return queue.top().label();
- }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
index 6fb49b1..b95077d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
@@ -149,48 +149,4 @@ final class ExactPhraseMatcher extends PhraseMatcher {
return postings[postings.length - 1].postings.endOffset();
}
- @Override
- MatchesIterator getSubMatches() {
- return new MatchesIterator() {
-
- int upTo = -1;
-
- @Override
- public boolean next() throws IOException {
- upTo++;
- return upTo < postings.length;
- }
-
- @Override
- public int startPosition() {
- return postings[upTo].pos;
- }
-
- @Override
- public int endPosition() {
- return postings[upTo].pos;
- }
-
- @Override
- public int startOffset() throws IOException {
- return postings[upTo].postings.startOffset();
- }
-
- @Override
- public int endOffset() throws IOException {
- return postings[upTo].postings.endOffset();
- }
-
- @Override
- public MatchesIterator getSubMatches() throws IOException {
- return MatchesIterator.EMPTY_ITERATOR;
- }
-
- @Override
- public Object label() {
- return this;
- }
- };
- }
-
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
index 5814d7c..450a352 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
@@ -28,9 +28,6 @@ import org.apache.lucene.index.LeafReaderContext;
* positions and/or offsets after each call. You should not call the position or offset methods
* before {@link #next()} has been called, or after {@link #next()} has returned {@code false}.
*
- * Matches from some queries may span multiple positions. You can retrieve the positions of
- * individual matching terms on the current match by calling {@link #getSubMatches()}.
- *
* Matches are ordered by start position, and then by end position. Match intervals may overlap.
*
* @see Weight#matches(LeafReaderContext, int)
@@ -73,59 +70,4 @@ public interface MatchesIterator {
*/
int endOffset() throws IOException;
- /**
- * Returns a MatchesIterator that iterates over the positions and offsets of individual
- * terms within the current match
- *
- * Should only be called after {@link #next()} has returned {@code true}
- */
- MatchesIterator getSubMatches() throws IOException;
-
- /**
- * Returns a label identifying the leaf query causing the current match
- *
- * Should only be called after {@link #next()} has returned {@code true}
- */
- Object label();
-
- /**
- * A MatchesIterator that is immediately exhausted
- */
- MatchesIterator EMPTY_ITERATOR = new MatchesIterator() {
- @Override
- public boolean next() throws IOException {
- return false;
- }
-
- @Override
- public int startPosition() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int endPosition() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int startOffset() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int endOffset() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public MatchesIterator getSubMatches() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Object label() {
- return this;
- }
- };
-
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
index c8d22ba..22b7127 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
@@ -269,7 +269,7 @@ public class MultiPhraseQuery extends Query {
TermState termState = termStates.get(term).get(context);
if (termState != null) {
termsEnum.seekExact(term.bytes(), termState);
- postings.add(termsEnum.postings(null, exposeOffsets ? PostingsEnum.ALL : PostingsEnum.POSITIONS));
+ postings.add(termsEnum.postings(null, exposeOffsets ? PostingsEnum.OFFSETS : PostingsEnum.POSITIONS));
totalMatchCost += PhraseQuery.termPositionsCost(termsEnum);
}
}
@@ -294,7 +294,7 @@ public class MultiPhraseQuery extends Query {
return new ExactPhraseMatcher(postingsFreqs, totalMatchCost);
}
else {
- return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost, exposeOffsets);
+ return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost);
}
}
@@ -647,6 +647,5 @@ public class MultiPhraseQuery extends Query {
public BytesRef getPayload() throws IOException {
return posQueue.top().pe.getPayload();
}
-
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
index c4b1e36..81040d5 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
@@ -88,6 +88,4 @@ abstract class PhraseMatcher {
public float getMatchCost() {
return matchCost;
}
-
- abstract MatchesIterator getSubMatches() throws IOException;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
index 8f04271..70d2e09 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
@@ -446,7 +446,7 @@ public class PhraseQuery extends Query {
return null;
}
te.seekExact(t.bytes(), state);
- PostingsEnum postingsEnum = te.postings(null, exposeOffsets ? PostingsEnum.ALL : PostingsEnum.POSITIONS);
+ PostingsEnum postingsEnum = te.postings(null, exposeOffsets ? PostingsEnum.OFFSETS : PostingsEnum.POSITIONS);
postingsFreqs[i] = new PostingsAndFreq(postingsEnum, positions[i], t);
totalMatchCost += termPositionsCost(te);
}
@@ -457,7 +457,7 @@ public class PhraseQuery extends Query {
return new ExactPhraseMatcher(postingsFreqs, totalMatchCost);
}
else {
- return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost, exposeOffsets);
+ return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java b/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
index 2547b8c..90fa537 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
@@ -123,16 +123,6 @@ abstract class PhraseWeight extends Weight {
public int endOffset() throws IOException {
return matcher.endOffset();
}
-
- @Override
- public MatchesIterator getSubMatches() throws IOException {
- return matcher.getSubMatches();
- }
-
- @Override
- public Object label() {
- return matcher;
- }
};
});
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
index e9c4519..326816d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
@@ -54,14 +54,13 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
private final int slop;
private final int numPostings;
private final PhraseQueue pq; // for advancing min position
- private final boolean captureLeadMatch;
private int end; // current largest phrase position
private int leadPosition;
private int leadOffset;
- private int leadEndOffset;
- private int leadOrd;
+ private int currentEndPostings;
+ private int advanceEndPostings;
private boolean hasRpts; // flag indicating that there are repetitions (as checked in first candidate doc)
private boolean checkedRpts; // flag to only check for repetitions in first candidate doc
@@ -72,11 +71,10 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
private boolean positioned;
private int matchLength;
- SloppyPhraseMatcher(PhraseQuery.PostingsAndFreq[] postings, int slop, float matchCost, boolean captureLeadMatch) {
+ SloppyPhraseMatcher(PhraseQuery.PostingsAndFreq[] postings, int slop, float matchCost) {
super(approximation(postings), matchCost);
this.slop = slop;
this.numPostings = postings.length;
- this.captureLeadMatch = captureLeadMatch;
pq = new PhraseQueue(postings.length);
phrasePositions = new PhrasePositions[postings.length];
for (int i = 0; i < postings.length; ++i) {
@@ -122,8 +120,10 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
return false;
}
PhrasePositions pp = pq.pop();
- assert pp != null; // if the pq is not full, then positioned == false
- captureLead(pp);
+ assert pp != null; // if the pq is empty, then positioned == false
+ leadPosition = pp.position + pp.offset;
+ leadOffset = pp.postings.startOffset();
+ currentEndPostings = advanceEndPostings;
matchLength = end - pp.position;
int next = pq.top().position;
while (advancePP(pp)) {
@@ -137,7 +137,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
}
pp = pq.pop();
next = pq.top().position;
- assert pp != null; // if the pq is not full, then positioned == false
matchLength = end - pp.position;
} else {
int matchLength2 = end - pp.position;
@@ -145,22 +144,14 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
matchLength = matchLength2;
}
}
- captureLead(pp);
+ leadPosition = pp.position + pp.offset;
+ leadOffset = pp.postings.startOffset();
+ currentEndPostings = advanceEndPostings;
}
positioned = false;
return matchLength <= slop;
}
- private void captureLead(PhrasePositions pp) throws IOException {
- if (captureLeadMatch == false) {
- return;
- }
- leadOrd = pp.ord;
- leadPosition = pp.position + pp.offset;
- leadOffset = pp.postings.startOffset();
- leadEndOffset = pp.postings.endOffset();
- }
-
@Override
public int startPosition() {
// when a match is detected, the top postings is advanced until it has moved
@@ -169,7 +160,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
// However, the priority queue doesn't guarantee that the top postings is in fact the
// earliest in the list, so we need to cycle through all terms to check.
// this is slow, but Matches is slow anyway...
- int leadPosition = this.leadPosition;
for (PhrasePositions pp : phrasePositions) {
leadPosition = Math.min(leadPosition, pp.position + pp.offset);
}
@@ -178,13 +168,7 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
@Override
public int endPosition() {
- int endPosition = leadPosition;
- for (PhrasePositions pp : phrasePositions) {
- if (pp.ord != leadOrd) {
- endPosition = Math.max(endPosition, pp.position + pp.offset);
- }
- }
- return endPosition;
+ return phrasePositions[currentEndPostings].position + phrasePositions[currentEndPostings].offset;
}
@Override
@@ -195,7 +179,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
// However, the priority queue doesn't guarantee that the top postings is in fact the
// earliest in the list, so we need to cycle through all terms to check
// this is slow, but Matches is slow anyway...
- int leadOffset = this.leadOffset;
for (PhrasePositions pp : phrasePositions) {
leadOffset = Math.min(leadOffset, pp.postings.startOffset());
}
@@ -204,69 +187,7 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
@Override
public int endOffset() throws IOException {
- int endOffset = leadEndOffset;
- for (PhrasePositions pp : phrasePositions) {
- if (pp.ord != leadOrd) {
- endOffset = Math.max(endOffset, pp.postings.endOffset());
- }
- }
- return endOffset;
- }
-
- @Override
- MatchesIterator getSubMatches() throws IOException {
- int[][] submatches = new int[phrasePositions.length][3];
- for (PhrasePositions pp : phrasePositions) {
- if (pp.ord == leadOrd) {
- submatches[pp.ord][0] = leadPosition;
- submatches[pp.ord][1] = leadOffset;
- submatches[pp.ord][2] = leadEndOffset;
- }
- else {
- submatches[pp.ord][0] = pp.position + pp.offset;
- submatches[pp.ord][1] = pp.postings.startOffset();
- submatches[pp.ord][2] = pp.postings.endOffset();
- }
- }
- Arrays.sort(submatches, Comparator.comparingInt(a -> a[0]));
- return new MatchesIterator() {
- int upTo = -1;
- @Override
- public boolean next() throws IOException {
- upTo++;
- return upTo < submatches.length;
- }
-
- @Override
- public int startPosition() {
- return submatches[upTo][0];
- }
-
- @Override
- public int endPosition() {
- return submatches[upTo][0];
- }
-
- @Override
- public int startOffset() {
- return submatches[upTo][1];
- }
-
- @Override
- public int endOffset() {
- return submatches[upTo][2];
- }
-
- @Override
- public MatchesIterator getSubMatches() {
- return MatchesIterator.EMPTY_ITERATOR;
- }
-
- @Override
- public Object label() {
- return this;
- }
- };
+ return phrasePositions[currentEndPostings].postings.endOffset();
}
/** advance a PhrasePosition and update 'end', return false if exhausted */
@@ -276,6 +197,12 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
}
if (pp.position > end) {
end = pp.position;
+ advanceEndPostings = pp.ord;
+ }
+ if (pp.position == end) {
+ if (pp.ord > advanceEndPostings) {
+ advanceEndPostings = pp.ord;
+ }
}
return true;
}
@@ -380,6 +307,12 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
pp.firstPosition();
if (pp.position > end) {
end = pp.position;
+ advanceEndPostings = pp.ord;
+ }
+ if (pp.position == end) {
+ if (pp.ord > advanceEndPostings) {
+ advanceEndPostings = pp.ord;
+ }
}
pq.add(pp);
}
@@ -409,6 +342,12 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
for (PhrasePositions pp : phrasePositions) { // iterate cyclic list: done once handled max
if (pp.position > end) {
end = pp.position;
+ advanceEndPostings = pp.ord;
+ }
+ if (pp.position == end) {
+ if (pp.ord > advanceEndPostings) {
+ advanceEndPostings = pp.ord;
+ }
}
pq.add(pp);
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
index 23858c6..defc3af 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
@@ -67,54 +67,4 @@ class TermMatchesIterator implements MatchesIterator {
return pe.endOffset();
}
- @Override
- public Object label() {
- return pe;
- }
-
- @Override
- public MatchesIterator getSubMatches() throws IOException {
- return new MatchesIterator() {
-
- boolean exhausted = false;
-
- @Override
- public boolean next() {
- if (exhausted) {
- return false;
- }
- return exhausted = true;
- }
-
- @Override
- public int startPosition() {
- return pos;
- }
-
- @Override
- public int endPosition() {
- return pos;
- }
-
- @Override
- public int startOffset() throws IOException {
- return pe.startOffset();
- }
-
- @Override
- public int endOffset() throws IOException {
- return pe.endOffset();
- }
-
- @Override
- public MatchesIterator getSubMatches() {
- return MatchesIterator.EMPTY_ITERATOR;
- }
-
- @Override
- public Object label() {
- return this;
- }
- };
- }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
index ca789ce..0313d56 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
@@ -18,8 +18,6 @@ package org.apache.lucene.search.spans;
import java.io.IOException;
-import java.util.Arrays;
-import java.util.Comparator;
import java.util.Map;
import org.apache.lucene.index.LeafReaderContext;
@@ -30,8 +28,6 @@ import org.apache.lucene.search.CollectionStatistics;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.LeafSimScorer;
-import org.apache.lucene.search.Matches;
-import org.apache.lucene.search.MatchesIterator;
import org.apache.lucene.search.TermStatistics;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.similarities.Similarity;
@@ -165,131 +161,4 @@ public abstract class SpanWeight extends Weight {
return Explanation.noMatch("no matching term");
}
-
- @Override
- public Matches matches(LeafReaderContext context, int doc) throws IOException {
- return Matches.forField(field, () -> {
- Spans spans = getSpans(context, Postings.OFFSETS);
- if (spans == null) {
- return null;
- }
- if (spans.advance(doc) != doc) {
- return null;
- }
- return new MatchesIterator() {
-
- int innerTermCount = 0;
- int[][] innerTerms = new int[2][3];
- SpanCollector termCollector = new SpanCollector() {
- @Override
- public void collectLeaf(PostingsEnum postings, int position, Term term) throws IOException {
- innerTermCount++;
- if (innerTermCount > innerTerms.length) {
- int[][] temp = new int[innerTermCount][3];
- System.arraycopy(innerTerms, 0, temp, 0, innerTermCount - 1);
- innerTerms = temp;
- }
- innerTerms[innerTermCount - 1][0] = position;
- innerTerms[innerTermCount - 1][1] = postings.startOffset();
- innerTerms[innerTermCount - 1][2] = postings.endOffset();
- }
-
- @Override
- public void reset() {
- innerTermCount = 0;
- }
- };
-
- @Override
- public boolean next() throws IOException {
- innerTermCount = 0;
- return spans.nextStartPosition() != Spans.NO_MORE_POSITIONS;
- }
-
- @Override
- public int startPosition() {
- return spans.startPosition();
- }
-
- @Override
- public int endPosition() {
- return spans.endPosition() - 1;
- }
-
- @Override
- public int startOffset() throws IOException {
- if (innerTermCount == 0) {
- collectInnerTerms();
- }
- return innerTerms[0][1];
- }
-
- @Override
- public int endOffset() throws IOException {
- if (innerTermCount == 0) {
- collectInnerTerms();
- }
- return innerTerms[innerTermCount - 1][2];
- }
-
- @Override
- public MatchesIterator getSubMatches() throws IOException {
- if (innerTermCount == 0) {
- collectInnerTerms();
- }
- return new MatchesIterator() {
-
- int upto = -1;
-
- @Override
- public boolean next() throws IOException {
- upto++;
- return upto < innerTermCount;
- }
-
- @Override
- public int startPosition() {
- return innerTerms[upto][0];
- }
-
- @Override
- public int endPosition() {
- return innerTerms[upto][0];
- }
-
- @Override
- public int startOffset() throws IOException {
- return innerTerms[upto][1];
- }
-
- @Override
- public int endOffset() throws IOException {
- return innerTerms[upto][2];
- }
-
- @Override
- public MatchesIterator getSubMatches() throws IOException {
- return MatchesIterator.EMPTY_ITERATOR;
- }
-
- @Override
- public Object label() {
- return this;
- }
- };
- }
-
- @Override
- public Object label() {
- return SpanWeight.this;
- }
-
- void collectInnerTerms() throws IOException {
- termCollector.reset();
- spans.collect(termCollector);
- Arrays.sort(innerTerms, 0, innerTermCount, Comparator.comparing(a -> a[0]));
- }
- };
- });
- }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
index 86e4399..3855b04 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
@@ -18,12 +18,8 @@
package org.apache.lucene.search;
import java.io.IOException;
-import java.util.Arrays;
import java.util.HashSet;
-import java.util.IdentityHashMap;
-import java.util.Objects;
import java.util.Set;
-import java.util.stream.Collectors;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
@@ -33,14 +29,9 @@ import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
-import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.index.Term;
-import org.apache.lucene.search.spans.SpanNearQuery;
-import org.apache.lucene.search.spans.SpanOrQuery;
-import org.apache.lucene.search.spans.SpanQuery;
-import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
@@ -108,7 +99,7 @@ public class TestMatchesIterator extends LuceneTestCase {
"nothing matches this document"
};
- private void checkMatches(Query q, String field, int[][] expected) throws IOException {
+ void checkMatches(Query q, String field, int[][] expected) throws IOException {
Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
for (int i = 0; i < expected.length; i++) {
LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(expected[i][0], searcher.leafContexts));
@@ -121,40 +112,14 @@ public class TestMatchesIterator extends LuceneTestCase {
MatchesIterator it = matches.getMatches(field);
if (expected[i].length == 1) {
assertNull(it);
- continue;
+ return;
}
checkFieldMatches(it, expected[i]);
checkFieldMatches(matches.getMatches(field), expected[i]); // test multiple calls
}
}
- private void checkLabelCount(Query q, String field, int[] expected) throws IOException {
- Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
- for (int i = 0; i < expected.length; i++) {
- LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
- int doc = i - ctx.docBase;
- Matches matches = w.matches(ctx, doc);
- if (matches == null) {
- assertEquals("Expected to get matches on document " + i, 0, expected[i]);
- continue;
- }
- MatchesIterator it = matches.getMatches(field);
- if (expected[i] == 0) {
- assertNull(it);
- continue;
- }
- else {
- assertNotNull(it);
- }
- IdentityHashMap<Object, Integer> labels = new IdentityHashMap<>();
- while (it.next()) {
- labels.put(it.label(), 1);
- }
- assertEquals(expected[i], labels.size());
- }
- }
-
- private void checkFieldMatches(MatchesIterator it, int[] expected) throws IOException {
+ void checkFieldMatches(MatchesIterator it, int[] expected) throws IOException {
int pos = 1;
while (it.next()) {
//System.out.println(expected[i][pos] + "->" + expected[i][pos + 1] + "[" + expected[i][pos + 2] + "->" + expected[i][pos + 3] + "]");
@@ -167,7 +132,7 @@ public class TestMatchesIterator extends LuceneTestCase {
assertEquals(expected.length, pos);
}
- private void checkNoPositionsMatches(Query q, String field, boolean[] expected) throws IOException {
+ void checkNoPositionsMatches(Query q, String field, boolean[] expected) throws IOException {
Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
for (int i = 0; i < expected.length; i++) {
LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
@@ -183,90 +148,8 @@ public class TestMatchesIterator extends LuceneTestCase {
}
}
- private void checkTermMatches(Query q, String field, TermMatch[][][] expected) throws IOException {
- Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
- for (int i = 0; i < expected.length; i++) {
- LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
- int doc = i - ctx.docBase;
- Matches matches = w.matches(ctx, doc);
- if (matches == null) {
- assertEquals(expected[i].length, 0);
- continue;
- }
- MatchesIterator it = matches.getMatches(field);
- if (expected[i].length == 0) {
- assertNull(it);
- continue;
- }
- checkTerms(expected[i], it);
- }
- }
-
- private void checkTerms(TermMatch[][] expected, MatchesIterator it) throws IOException {
- int upTo = 0;
- while (it.next()) {
- Set<TermMatch> expectedMatches = new HashSet<>(Arrays.asList(expected[upTo]));
- MatchesIterator submatches = it.getSubMatches();
- while (submatches.next()) {
- TermMatch tm = new TermMatch(submatches.startPosition(), submatches.startOffset(), submatches.endOffset());
- if (expectedMatches.remove(tm) == false) {
- fail("Unexpected term match: " + tm);
- }
- }
- if (expectedMatches.size() != 0) {
- fail("Missing term matches: " + expectedMatches.stream().map(Object::toString).collect(Collectors.joining(", ")));
- }
- upTo++;
- }
- if (upTo < expected.length - 1) {
- fail("Missing expected match");
- }
- }
-
- static class TermMatch {
-
- public final int position;
-
- public final int startOffset;
-
- public final int endOffset;
-
- public TermMatch(PostingsEnum pe, int position) throws IOException {
- this.position = position;
- this.startOffset = pe.startOffset();
- this.endOffset = pe.endOffset();
- }
-
- public TermMatch(int position, int startOffset, int endOffset) {
- this.position = position;
- this.startOffset = startOffset;
- this.endOffset = endOffset;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- TermMatch termMatch = (TermMatch) o;
- return position == termMatch.position &&
- startOffset == termMatch.startOffset &&
- endOffset == termMatch.endOffset;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(position, startOffset, endOffset);
- }
-
- @Override
- public String toString() {
- return position + "[" + startOffset + "->" + endOffset + "]";
- }
- }
-
public void testTermQuery() throws IOException {
- Term t = new Term(FIELD_WITH_OFFSETS, "w1");
- Query q = new TermQuery(t);
+ Query q = new TermQuery(new Term(FIELD_WITH_OFFSETS, "w1"));
checkMatches(q, FIELD_WITH_OFFSETS, new int[][]{
{ 0, 0, 0, 0, 2 },
{ 1, 0, 0, 0, 2 },
@@ -274,14 +157,6 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8 },
{ 4 }
});
- checkTermMatches(q, FIELD_WITH_OFFSETS, new TermMatch[][][]{
- { { new TermMatch(0, 0, 2) } },
- { { new TermMatch(0, 0, 2) } },
- { { new TermMatch(0, 0, 2) } },
- { { new TermMatch(0, 0, 2) }, { new TermMatch(2, 6, 8) } },
- {}
- });
- checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 1, 1, 1, 1, 0, 0 });
}
public void testTermQueryNoStoredOffsets() throws IOException {
@@ -316,7 +191,6 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 5, 5, 15, 17 },
{ 4 }
});
- checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 2, 2, 1, 2, 0, 0 });
}
public void testDisjunctionNoPositions() throws IOException {
@@ -341,7 +215,6 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 5, 5, 15, 17 },
{ 4 }
});
- checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 2, 2, 0, 2, 0, 0 });
}
public void testReqOptNoPositions() throws IOException {
@@ -375,7 +248,6 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 3, 3, 9, 11, 5, 5, 15, 17 },
{ 4 }
});
- checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 3, 1, 3, 3, 0, 0 });
}
public void testMinShouldMatchNoPositions() throws IOException {
@@ -459,7 +331,6 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 1, 1, 3, 5, 2, 2, 6, 8, 4, 4, 12, 14 },
{ 4 }
});
- checkLabelCount(rq, FIELD_WITH_OFFSETS, new int[]{ 2, 2, 2, 2, 0 });
}
@@ -521,55 +392,12 @@ public class TestMatchesIterator extends LuceneTestCase {
// 0 1 2 3 4 5 6 7
// "a phrase sentence with many phrase sentence iterations of a phrase sentence",
- public void testSloppyPhraseQueryWithRepeats() throws IOException {
- Term p = new Term(FIELD_WITH_OFFSETS, "phrase");
- Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
- PhraseQuery pq = new PhraseQuery(10, FIELD_WITH_OFFSETS, "phrase", "sentence", "sentence");
- checkMatches(pq, FIELD_WITH_OFFSETS, new int[][]{
- { 0 }, { 1 }, { 2 }, { 3 },
- { 4, 1, 6, 2, 43, 2, 11, 9, 75, 5, 11, 28, 75, 6, 11, 35, 75 }
- });
- checkLabelCount(pq, FIELD_WITH_OFFSETS, new int[]{ 0, 0, 0, 0, 1 });
- checkTermMatches(pq, FIELD_WITH_OFFSETS, new TermMatch[][][]{
- {}, {}, {}, {},
- { {
- new TermMatch(1, 2, 8),
- new TermMatch(2, 9, 17),
- new TermMatch(6, 35, 43)
- }, {
- new TermMatch(5, 28, 34),
- new TermMatch(2, 9, 17),
- new TermMatch(11, 67, 75)
- }, {
- new TermMatch(5, 28, 34),
- new TermMatch(6, 35, 43),
- new TermMatch(11, 67, 75)
- }, {
- new TermMatch(10, 60, 66),
- new TermMatch(6, 35, 43),
- new TermMatch(11, 67, 75)
- } }
- });
- }
-
public void testSloppyPhraseQuery() throws IOException {
- Term a = new Term(FIELD_WITH_OFFSETS, "a");
- Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
PhraseQuery pq = new PhraseQuery(4, FIELD_WITH_OFFSETS, "a", "sentence");
checkMatches(pq, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
{ 4, 0, 2, 0, 17, 6, 9, 35, 59, 9, 11, 58, 75 }
});
- checkTermMatches(pq, FIELD_WITH_OFFSETS, new TermMatch[][][]{
- {}, {}, {}, {},
- { {
- new TermMatch(0, 0, 1), new TermMatch(2, 9, 17)
- }, {
- new TermMatch(9, 58, 59), new TermMatch(6, 35, 43)
- }, {
- new TermMatch(9, 58, 59), new TermMatch(11, 67, 75)
- } }
- });
}
public void testExactPhraseQuery() throws IOException {
@@ -579,57 +407,28 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 4, 1, 2, 2, 17, 5, 6, 28, 43, 10, 11, 60, 75 }
});
- Term a = new Term(FIELD_WITH_OFFSETS, "a");
- Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
PhraseQuery pq2 = new PhraseQuery.Builder()
- .add(a)
- .add(s, 2)
+ .add(new Term(FIELD_WITH_OFFSETS, "a"))
+ .add(new Term(FIELD_WITH_OFFSETS, "sentence"), 2)
.build();
checkMatches(pq2, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
{ 4, 0, 2, 0, 17, 9, 11, 58, 75 }
});
- checkTermMatches(pq2, FIELD_WITH_OFFSETS, new TermMatch[][][]{
- {}, {}, {}, {},
- { {
- new TermMatch(0, 0, 1), new TermMatch(2, 9, 17)
- }, {
- new TermMatch(9, 58, 59), new TermMatch(11, 67, 75)
- } }
- });
}
// 0 1 2 3 4 5 6 7
// "a phrase sentence with many phrase sentence iterations of a phrase sentence",
public void testSloppyMultiPhraseQuery() throws IOException {
- Term p = new Term(FIELD_WITH_OFFSETS, "phrase");
- Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
- Term i = new Term(FIELD_WITH_OFFSETS, "iterations");
MultiPhraseQuery mpq = new MultiPhraseQuery.Builder()
- .add(p)
- .add(new Term[]{ s, i })
+ .add(new Term(FIELD_WITH_OFFSETS, "phrase"))
+ .add(new Term[]{ new Term(FIELD_WITH_OFFSETS, "sentence"), new Term(FIELD_WITH_OFFSETS, "iterations") })
.setSlop(4)
.build();
checkMatches(mpq, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
- { 4, 1, 2, 2, 17, 5, 6, 28, 43, 5, 7, 28, 54, 10, 11, 60, 75 }
- });
- checkTermMatches(mpq, FIELD_WITH_OFFSETS, new TermMatch[][][]{
- {}, {}, {}, {},
- { {
- new TermMatch(1, 2, 8),
- new TermMatch(2, 9, 17)
- }, {
- new TermMatch(5, 28, 34),
- new TermMatch(6, 35, 43)
- }, {
- new TermMatch(5, 28, 34),
- new TermMatch(7, 44, 54)
- }, {
- new TermMatch(10, 60, 66),
- new TermMatch(11, 67, 75)
- } }
+ { 4, 1, 2, 2, 17, 5, 7, 28, 54, 5, 7, 28, 54, 10, 11, 60, 75 }
});
}
@@ -653,35 +452,4 @@ public class TestMatchesIterator extends LuceneTestCase {
});
}
- // 0 1 2 3 4 5 6 7
- // "a phrase sentence with many phrase sentence iterations of a phrase sentence",
-
- public void testSpanQuery() throws IOException {
- SpanQuery subq = SpanNearQuery.newOrderedNearQuery(FIELD_WITH_OFFSETS)
- .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "with")))
- .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "many")))
- .build();
- Query q = SpanNearQuery.newOrderedNearQuery(FIELD_WITH_OFFSETS)
- .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "sentence")))
- .addClause(new SpanOrQuery(subq, new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "iterations"))))
- .build();
- checkMatches(q, FIELD_WITH_OFFSETS, new int[][]{
- { 0 }, { 1 }, { 2 }, { 3 },
- { 4, 2, 4, 9, 27, 6, 7, 35, 54 }
- });
- checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 0, 0, 0, 0, 1 });
- checkTermMatches(q, FIELD_WITH_OFFSETS, new TermMatch[][][]{
- {}, {}, {}, {},
- {
- {
- new TermMatch(2, 9, 17),
- new TermMatch(3, 18, 22),
- new TermMatch(4, 23, 27)
- }, {
- new TermMatch(6, 35, 43), new TermMatch(7, 44, 54)
- }
- }
- });
- }
-
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e3f61f6/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
index 5f7e307..4f06512 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
@@ -67,15 +67,4 @@ class AssertingMatchesIterator implements MatchesIterator {
return in.endOffset();
}
- @Override
- public MatchesIterator getSubMatches() throws IOException {
- assert state == State.ITERATING : state;
- return in.getSubMatches();
- }
-
- @Override
- public Object label() {
- assert state == State.ITERATING : state;
- return in.label();
- }
}
[20/33] lucene-solr:jira/http2: SOLR-12570:
OpenNLPExtractNamedEntitiesUpdateProcessor cannot support multi fields
because pattern replacement doesn't work correctly
Posted by da...@apache.org.
SOLR-12570: OpenNLPExtractNamedEntitiesUpdateProcessor cannot support multi fields because pattern replacement doesn't work correctly
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/995a902d
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/995a902d
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/995a902d
Branch: refs/heads/jira/http2
Commit: 995a902d1ad40860ee082b57e4e47c1be52c856e
Parents: 55bfadb
Author: koji <ko...@apache.org>
Authored: Mon Jul 23 16:58:46 2018 +0900
Committer: koji <ko...@apache.org>
Committed: Mon Jul 23 16:58:46 2018 +0900
----------------------------------------------------------------------
solr/CHANGES.txt | 3 +++
...PExtractNamedEntitiesUpdateProcessorFactory.java | 16 ++++++++--------
...PExtractNamedEntitiesUpdateProcessorFactory.java | 9 ++++++---
3 files changed, 17 insertions(+), 11 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/995a902d/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index e93e0e7..e1069d8 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -159,6 +159,9 @@ Bug Fixes
* SOLR-12553: Allow SignificantTerms Query Parser to use local parameters (Alexandre Rafalovitch)
+* SOLR-12570: OpenNLPExtractNamedEntitiesUpdateProcessor cannot support multi fields because pattern replacement
+ doesn't work correctly. (Koji Sekiguchi)
+
Optimizations
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/995a902d/solr/contrib/analysis-extras/src/java/org/apache/solr/update/processor/OpenNLPExtractNamedEntitiesUpdateProcessorFactory.java
----------------------------------------------------------------------
diff --git a/solr/contrib/analysis-extras/src/java/org/apache/solr/update/processor/OpenNLPExtractNamedEntitiesUpdateProcessorFactory.java b/solr/contrib/analysis-extras/src/java/org/apache/solr/update/processor/OpenNLPExtractNamedEntitiesUpdateProcessorFactory.java
index 2a7514d..d69c367 100644
--- a/solr/contrib/analysis-extras/src/java/org/apache/solr/update/processor/OpenNLPExtractNamedEntitiesUpdateProcessorFactory.java
+++ b/solr/contrib/analysis-extras/src/java/org/apache/solr/update/processor/OpenNLPExtractNamedEntitiesUpdateProcessorFactory.java
@@ -17,8 +17,6 @@
package org.apache.solr.update.processor;
-import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;
-
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
@@ -57,6 +55,8 @@ import org.apache.solr.util.plugin.SolrCoreAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;
+
/**
* Extracts named entities using an OpenNLP NER <code>modelFile</code> from the values found in
* any matching <code>source</code> field into a configured <code>dest</code> field, after
@@ -500,13 +500,13 @@ public class OpenNLPExtractNamedEntitiesUpdateProcessorFactory
SolrInputField destField = null;
String entityName = entity.first();
String entityType = entity.second();
- resolvedDest = resolvedDest.replace(ENTITY_TYPE, entityType);
- if (doc.containsKey(resolvedDest)) {
- destField = doc.getField(resolvedDest);
+ final String resolved = resolvedDest.replace(ENTITY_TYPE, entityType);
+ if (doc.containsKey(resolved)) {
+ destField = doc.getField(resolved);
} else {
- SolrInputField targetField = destMap.get(resolvedDest);
+ SolrInputField targetField = destMap.get(resolved);
if (targetField == null) {
- destField = new SolrInputField(resolvedDest);
+ destField = new SolrInputField(resolved);
} else {
destField = targetField;
}
@@ -514,7 +514,7 @@ public class OpenNLPExtractNamedEntitiesUpdateProcessorFactory
destField.addValue(entityName);
// put it in map to avoid concurrent modification...
- destMap.put(resolvedDest, destField);
+ destMap.put(resolved, destField);
}
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/995a902d/solr/contrib/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.java
----------------------------------------------------------------------
diff --git a/solr/contrib/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.java b/solr/contrib/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.java
index dad06a8..851fea0 100644
--- a/solr/contrib/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.java
+++ b/solr/contrib/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.java
@@ -82,7 +82,7 @@ public class TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory extends Updat
f("subtitle", "Ineluctably, Flashman."),
f("corrolary_txt", "Forsooth thou bringeth Flashman."),
f("notes_txt", "Yes Flashman."),
- f("summary", "Many aspire to be Flashman."),
+ f("summary", "Many aspire to be Flashman in London."),
f("descs", "Courage, Flashman.", "Ain't he Flashman."),
f("descriptions", "Flashman. Flashman. Flashman.")));
@@ -91,6 +91,7 @@ public class TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory extends Updat
assertEquals(Arrays.asList("Flashman", "Flashman"), doc.getFieldValues("key_desc_people"));
assertEquals(Arrays.asList("Flashman", "Flashman", "Flashman"), doc.getFieldValues("key_description_people"));
assertEquals("Flashman", doc.getFieldValue("summary_person_s")); // {EntityType} field name interpolation
+ assertEquals("London", doc.getFieldValue("summary_location_s")); // {EntityType} field name interpolation
}
public void testEquivalentExtraction() throws Exception {
@@ -182,11 +183,13 @@ public class TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory extends Updat
public void testExtractFieldRegexReplaceAllWithEntityType() throws Exception {
SolrInputDocument d = processAdd("extract-regex-replaceall-with-entity-type",
doc(f("id", "1111"),
- f("foo_x2_s", "Infrequently Flashman.", "In the words of Flashman."),
- f("foo_x3_x7_s", "Flashman. Whoa.")));
+ f("foo_x2_s", "Infrequently Flashman in London.", "In the words of Flashman in London."),
+ f("foo_x3_x7_s", "Flashman in London. Whoa.")));
assertNotNull(d);
assertEquals(d.getFieldNames().toString(), Arrays.asList("Flashman", "Flashman"), d.getFieldValues("foo_person_y2_s"));
+ assertEquals(d.getFieldNames().toString(), Arrays.asList("London", "London"), d.getFieldValues("foo_location_y2_s"));
assertEquals(d.getFieldNames().toString(),"Flashman", d.getFieldValue("foo_person_y3_person_y7_s"));
+ assertEquals(d.getFieldNames().toString(),"London", d.getFieldValue("foo_location_y3_location_y7_s"));
}
}
[21/33] lucene-solr:jira/http2: LUCENE-8306: Allow iteration over
submatches
Posted by da...@apache.org.
LUCENE-8306: Allow iteration over submatches
Also includes LUCENE-8404, adding match iteration to SpanQuery
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/028c86b1
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/028c86b1
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/028c86b1
Branch: refs/heads/jira/http2
Commit: 028c86b1fa70faeec4f7705698a59557f58bcbb0
Parents: 995a902
Author: Alan Woodward <ro...@apache.org>
Authored: Sun Jul 22 22:38:55 2018 +0100
Committer: Alan Woodward <ro...@apache.org>
Committed: Mon Jul 23 10:02:01 2018 +0100
----------------------------------------------------------------------
.../search/DisjunctionMatchesIterator.java | 17 +-
.../lucene/search/DocValuesRewriteMethod.java | 2 +-
.../apache/lucene/search/MatchesIterator.java | 24 ++
.../apache/lucene/search/MultiPhraseQuery.java | 5 +-
.../MultiTermQueryConstantScoreWrapper.java | 2 +-
.../org/apache/lucene/search/PhraseMatcher.java | 1 +
.../org/apache/lucene/search/PhraseQuery.java | 4 +-
.../org/apache/lucene/search/PhraseWeight.java | 10 +
.../lucene/search/SloppyPhraseMatcher.java | 65 +++---
.../org/apache/lucene/search/SynonymQuery.java | 2 +-
.../apache/lucene/search/TermInSetQuery.java | 2 +-
.../lucene/search/TermMatchesIterator.java | 13 +-
.../org/apache/lucene/search/TermQuery.java | 2 +-
.../apache/lucene/search/spans/SpanWeight.java | 140 ++++++++++++
.../lucene/search/TestMatchesIterator.java | 218 ++++++++++++++++++-
.../lucene/search/AssertingMatchesIterator.java | 11 +
16 files changed, 464 insertions(+), 54 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
index 975199b..f28c051 100644
--- a/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/DisjunctionMatchesIterator.java
@@ -45,14 +45,14 @@ final class DisjunctionMatchesIterator implements MatchesIterator {
*
* Only terms that have at least one match in the given document will be included
*/
- static MatchesIterator fromTerms(LeafReaderContext context, int doc, String field, List<Term> terms) throws IOException {
+ static MatchesIterator fromTerms(LeafReaderContext context, int doc, Query query, String field, List<Term> terms) throws IOException {
Objects.requireNonNull(field);
for (Term term : terms) {
if (Objects.equals(field, term.field()) == false) {
throw new IllegalArgumentException("Tried to generate iterator from terms in multiple fields: expected [" + field + "] but got [" + term.field() + "]");
}
}
- return fromTermsEnum(context, doc, field, asBytesRefIterator(terms));
+ return fromTermsEnum(context, doc, query, field, asBytesRefIterator(terms));
}
private static BytesRefIterator asBytesRefIterator(List<Term> terms) {
@@ -72,7 +72,7 @@ final class DisjunctionMatchesIterator implements MatchesIterator {
*
* Only terms that have at least one match in the given document will be included
*/
- static MatchesIterator fromTermsEnum(LeafReaderContext context, int doc, String field, BytesRefIterator terms) throws IOException {
+ static MatchesIterator fromTermsEnum(LeafReaderContext context, int doc, Query query, String field, BytesRefIterator terms) throws IOException {
Objects.requireNonNull(field);
List<MatchesIterator> mis = new ArrayList<>();
Terms t = context.reader().terms(field);
@@ -84,7 +84,7 @@ final class DisjunctionMatchesIterator implements MatchesIterator {
if (te.seekExact(term)) {
PostingsEnum pe = te.postings(reuse, PostingsEnum.OFFSETS);
if (pe.advance(doc) == doc) {
- mis.add(new TermMatchesIterator(pe));
+ mis.add(new TermMatchesIterator(query, pe));
reuse = null;
}
else {
@@ -158,4 +158,13 @@ final class DisjunctionMatchesIterator implements MatchesIterator {
return queue.top().endOffset();
}
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return queue.top().getSubMatches();
+ }
+
+ @Override
+ public Query getQuery() {
+ return queue.top().getQuery();
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java b/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
index 99720b7..fe6d551 100644
--- a/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
+++ b/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
@@ -78,7 +78,7 @@ public final class DocValuesRewriteMethod extends MultiTermQuery.RewriteMethod {
@Override
public Matches matches(LeafReaderContext context, int doc) throws IOException {
final SortedSetDocValues fcsi = DocValues.getSortedSet(context.reader(), query.field);
- return Matches.forField(query.field, () -> DisjunctionMatchesIterator.fromTermsEnum(context, doc, query.field, getTermsEnum(fcsi)));
+ return Matches.forField(query.field, () -> DisjunctionMatchesIterator.fromTermsEnum(context, doc, query, query.field, getTermsEnum(fcsi)));
}
private TermsEnum getTermsEnum(SortedSetDocValues fcsi) throws IOException {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
index 450a352..47ab5f5 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MatchesIterator.java
@@ -28,6 +28,9 @@ import org.apache.lucene.index.LeafReaderContext;
* positions and/or offsets after each call. You should not call the position or offset methods
* before {@link #next()} has been called, or after {@link #next()} has returned {@code false}.
*
+ * Matches from some queries may span multiple positions. You can retrieve the positions of
+ * individual matching terms on the current match by calling {@link #getSubMatches()}.
+ *
* Matches are ordered by start position, and then by end position. Match intervals may overlap.
*
* @see Weight#matches(LeafReaderContext, int)
@@ -70,4 +73,25 @@ public interface MatchesIterator {
*/
int endOffset() throws IOException;
+ /**
+ * Returns a MatchesIterator that iterates over the positions and offsets of individual
+ * terms within the current match
+ *
+ * Returns {@code null} if there are no submatches (ie the current iterator is at the
+ * leaf level)
+ *
+ * Should only be called after {@link #next()} has returned {@code true}
+ */
+ MatchesIterator getSubMatches() throws IOException;
+
+ /**
+ * Returns the Query causing the current match
+ *
+ * If this {@link MatchesIterator} has been returned from a {@link #getSubMatches()}
+ * call, then returns a {@link TermQuery} equivalent to the current match
+ *
+ * Should only be called after {@link #next()} has returned {@code true}
+ */
+ Query getQuery();
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
index 22b7127..c8d22ba 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
@@ -269,7 +269,7 @@ public class MultiPhraseQuery extends Query {
TermState termState = termStates.get(term).get(context);
if (termState != null) {
termsEnum.seekExact(term.bytes(), termState);
- postings.add(termsEnum.postings(null, exposeOffsets ? PostingsEnum.OFFSETS : PostingsEnum.POSITIONS));
+ postings.add(termsEnum.postings(null, exposeOffsets ? PostingsEnum.ALL : PostingsEnum.POSITIONS));
totalMatchCost += PhraseQuery.termPositionsCost(termsEnum);
}
}
@@ -294,7 +294,7 @@ public class MultiPhraseQuery extends Query {
return new ExactPhraseMatcher(postingsFreqs, totalMatchCost);
}
else {
- return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost);
+ return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost, exposeOffsets);
}
}
@@ -647,5 +647,6 @@ public class MultiPhraseQuery extends Query {
public BytesRef getPayload() throws IOException {
return posQueue.top().pe.getPayload();
}
+
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java b/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java
index 2299776..1e59ef9 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java
@@ -211,7 +211,7 @@ final class MultiTermQueryConstantScoreWrapper<Q extends MultiTermQuery> extends
if (terms.hasPositions() == false) {
return super.matches(context, doc);
}
- return Matches.forField(query.field, () -> DisjunctionMatchesIterator.fromTermsEnum(context, doc, query.field, query.getTermsEnum(terms)));
+ return Matches.forField(query.field, () -> DisjunctionMatchesIterator.fromTermsEnum(context, doc, query, query.field, query.getTermsEnum(terms)));
}
@Override
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
index 81040d5..a3cbd34 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
@@ -88,4 +88,5 @@ abstract class PhraseMatcher {
public float getMatchCost() {
return matchCost;
}
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
index 70d2e09..8f04271 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
@@ -446,7 +446,7 @@ public class PhraseQuery extends Query {
return null;
}
te.seekExact(t.bytes(), state);
- PostingsEnum postingsEnum = te.postings(null, exposeOffsets ? PostingsEnum.OFFSETS : PostingsEnum.POSITIONS);
+ PostingsEnum postingsEnum = te.postings(null, exposeOffsets ? PostingsEnum.ALL : PostingsEnum.POSITIONS);
postingsFreqs[i] = new PostingsAndFreq(postingsEnum, positions[i], t);
totalMatchCost += termPositionsCost(te);
}
@@ -457,7 +457,7 @@ public class PhraseQuery extends Query {
return new ExactPhraseMatcher(postingsFreqs, totalMatchCost);
}
else {
- return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost);
+ return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost, exposeOffsets);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java b/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
index 90fa537..94e57d6 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
@@ -123,6 +123,16 @@ abstract class PhraseWeight extends Weight {
public int endOffset() throws IOException {
return matcher.endOffset();
}
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return null; // phrases are treated as leaves
+ }
+
+ @Override
+ public Query getQuery() {
+ return PhraseWeight.this.getQuery();
+ }
};
});
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
index 326816d..bfe0682 100644
--- a/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
@@ -54,13 +54,14 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
private final int slop;
private final int numPostings;
private final PhraseQueue pq; // for advancing min position
+ private final boolean captureLeadMatch;
private int end; // current largest phrase position
private int leadPosition;
private int leadOffset;
- private int currentEndPostings;
- private int advanceEndPostings;
+ private int leadEndOffset;
+ private int leadOrd;
private boolean hasRpts; // flag indicating that there are repetitions (as checked in first candidate doc)
private boolean checkedRpts; // flag to only check for repetitions in first candidate doc
@@ -71,10 +72,11 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
private boolean positioned;
private int matchLength;
- SloppyPhraseMatcher(PhraseQuery.PostingsAndFreq[] postings, int slop, float matchCost) {
+ SloppyPhraseMatcher(PhraseQuery.PostingsAndFreq[] postings, int slop, float matchCost, boolean captureLeadMatch) {
super(approximation(postings), matchCost);
this.slop = slop;
this.numPostings = postings.length;
+ this.captureLeadMatch = captureLeadMatch;
pq = new PhraseQueue(postings.length);
phrasePositions = new PhrasePositions[postings.length];
for (int i = 0; i < postings.length; ++i) {
@@ -120,10 +122,8 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
return false;
}
PhrasePositions pp = pq.pop();
- assert pp != null; // if the pq is empty, then positioned == false
- leadPosition = pp.position + pp.offset;
- leadOffset = pp.postings.startOffset();
- currentEndPostings = advanceEndPostings;
+ assert pp != null; // if the pq is not full, then positioned == false
+ captureLead(pp);
matchLength = end - pp.position;
int next = pq.top().position;
while (advancePP(pp)) {
@@ -137,6 +137,7 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
}
pp = pq.pop();
next = pq.top().position;
+ assert pp != null; // if the pq is not full, then positioned == false
matchLength = end - pp.position;
} else {
int matchLength2 = end - pp.position;
@@ -144,14 +145,22 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
matchLength = matchLength2;
}
}
- leadPosition = pp.position + pp.offset;
- leadOffset = pp.postings.startOffset();
- currentEndPostings = advanceEndPostings;
+ captureLead(pp);
}
positioned = false;
return matchLength <= slop;
}
+ private void captureLead(PhrasePositions pp) throws IOException {
+ if (captureLeadMatch == false) {
+ return;
+ }
+ leadOrd = pp.ord;
+ leadPosition = pp.position + pp.offset;
+ leadOffset = pp.postings.startOffset();
+ leadEndOffset = pp.postings.endOffset();
+ }
+
@Override
public int startPosition() {
// when a match is detected, the top postings is advanced until it has moved
@@ -160,6 +169,7 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
// However, the priority queue doesn't guarantee that the top postings is in fact the
// earliest in the list, so we need to cycle through all terms to check.
// this is slow, but Matches is slow anyway...
+ int leadPosition = this.leadPosition;
for (PhrasePositions pp : phrasePositions) {
leadPosition = Math.min(leadPosition, pp.position + pp.offset);
}
@@ -168,7 +178,13 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
@Override
public int endPosition() {
- return phrasePositions[currentEndPostings].position + phrasePositions[currentEndPostings].offset;
+ int endPosition = leadPosition;
+ for (PhrasePositions pp : phrasePositions) {
+ if (pp.ord != leadOrd) {
+ endPosition = Math.max(endPosition, pp.position + pp.offset);
+ }
+ }
+ return endPosition;
}
@Override
@@ -179,6 +195,7 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
// However, the priority queue doesn't guarantee that the top postings is in fact the
// earliest in the list, so we need to cycle through all terms to check
// this is slow, but Matches is slow anyway...
+ int leadOffset = this.leadOffset;
for (PhrasePositions pp : phrasePositions) {
leadOffset = Math.min(leadOffset, pp.postings.startOffset());
}
@@ -187,7 +204,13 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
@Override
public int endOffset() throws IOException {
- return phrasePositions[currentEndPostings].postings.endOffset();
+ int endOffset = leadEndOffset;
+ for (PhrasePositions pp : phrasePositions) {
+ if (pp.ord != leadOrd) {
+ endOffset = Math.max(endOffset, pp.postings.endOffset());
+ }
+ }
+ return endOffset;
}
/** advance a PhrasePosition and update 'end', return false if exhausted */
@@ -197,12 +220,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
}
if (pp.position > end) {
end = pp.position;
- advanceEndPostings = pp.ord;
- }
- if (pp.position == end) {
- if (pp.ord > advanceEndPostings) {
- advanceEndPostings = pp.ord;
- }
}
return true;
}
@@ -307,12 +324,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
pp.firstPosition();
if (pp.position > end) {
end = pp.position;
- advanceEndPostings = pp.ord;
- }
- if (pp.position == end) {
- if (pp.ord > advanceEndPostings) {
- advanceEndPostings = pp.ord;
- }
}
pq.add(pp);
}
@@ -342,12 +353,6 @@ final class SloppyPhraseMatcher extends PhraseMatcher {
for (PhrasePositions pp : phrasePositions) { // iterate cyclic list: done once handled max
if (pp.position > end) {
end = pp.position;
- advanceEndPostings = pp.ord;
- }
- if (pp.position == end) {
- if (pp.ord > advanceEndPostings) {
- advanceEndPostings = pp.ord;
- }
}
pq.add(pp);
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java b/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java
index 68453ac..97e127a 100644
--- a/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java
@@ -176,7 +176,7 @@ public final class SynonymQuery extends Query {
if (terms == null || terms.hasPositions() == false) {
return super.matches(context, doc);
}
- return Matches.forField(field, () -> DisjunctionMatchesIterator.fromTerms(context, doc, field, Arrays.asList(SynonymQuery.this.terms)));
+ return Matches.forField(field, () -> DisjunctionMatchesIterator.fromTerms(context, doc, getQuery(), field, Arrays.asList(SynonymQuery.this.terms)));
}
@Override
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/TermInSetQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermInSetQuery.java b/lucene/core/src/java/org/apache/lucene/search/TermInSetQuery.java
index 7145a83..3ec7380 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermInSetQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermInSetQuery.java
@@ -226,7 +226,7 @@ public class TermInSetQuery extends Query implements Accountable {
if (terms == null || terms.hasPositions() == false) {
return super.matches(context, doc);
}
- return Matches.forField(field, () -> DisjunctionMatchesIterator.fromTermsEnum(context, doc, field, termData.iterator()));
+ return Matches.forField(field, () -> DisjunctionMatchesIterator.fromTermsEnum(context, doc, getQuery(), field, termData.iterator()));
}
/**
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java b/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
index defc3af..968b815 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermMatchesIterator.java
@@ -29,12 +29,14 @@ class TermMatchesIterator implements MatchesIterator {
private int upto;
private int pos;
private final PostingsEnum pe;
+ private final Query query;
/**
* Create a new {@link TermMatchesIterator} for the given term and postings list
*/
- TermMatchesIterator(PostingsEnum pe) throws IOException {
+ TermMatchesIterator(Query query, PostingsEnum pe) throws IOException {
this.pe = pe;
+ this.query = query;
this.upto = pe.freq();
}
@@ -67,4 +69,13 @@ class TermMatchesIterator implements MatchesIterator {
return pe.endOffset();
}
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return null;
+ }
+
+ @Override
+ public Query getQuery() {
+ return query;
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermQuery.java b/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
index ccb1de6..46901f2 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
@@ -94,7 +94,7 @@ public class TermQuery extends Query {
if (pe.advance(doc) != doc) {
return null;
}
- return new TermMatchesIterator(pe);
+ return new TermMatchesIterator(getQuery(), pe);
});
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
index 0313d56..edde8bb 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
@@ -18,6 +18,8 @@ package org.apache.lucene.search.spans;
import java.io.IOException;
+import java.util.Arrays;
+import java.util.Comparator;
import java.util.Map;
import org.apache.lucene.index.LeafReaderContext;
@@ -28,6 +30,10 @@ import org.apache.lucene.search.CollectionStatistics;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.LeafSimScorer;
+import org.apache.lucene.search.Matches;
+import org.apache.lucene.search.MatchesIterator;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermStatistics;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.similarities.Similarity;
@@ -161,4 +167,138 @@ public abstract class SpanWeight extends Weight {
return Explanation.noMatch("no matching term");
}
+
+ private static class TermMatch {
+ Term term;
+ int position;
+ int startOffset;
+ int endOffset;
+ }
+
+ @Override
+ public Matches matches(LeafReaderContext context, int doc) throws IOException {
+ return Matches.forField(field, () -> {
+ Spans spans = getSpans(context, Postings.OFFSETS);
+ if (spans == null || spans.advance(doc) != doc) {
+ return null;
+ }
+ return new MatchesIterator() {
+
+ int innerTermCount = 0;
+ TermMatch[] innerTerms = new TermMatch[0];
+
+ SpanCollector termCollector = new SpanCollector() {
+ @Override
+ public void collectLeaf(PostingsEnum postings, int position, Term term) throws IOException {
+ innerTermCount++;
+ if (innerTermCount > innerTerms.length) {
+ TermMatch[] temp = new TermMatch[innerTermCount];
+ System.arraycopy(innerTerms, 0, temp, 0, innerTermCount - 1);
+ innerTerms = temp;
+ innerTerms[innerTermCount - 1] = new TermMatch();
+ }
+ innerTerms[innerTermCount - 1].term = term;
+ innerTerms[innerTermCount - 1].position = position;
+ innerTerms[innerTermCount - 1].startOffset = postings.startOffset();
+ innerTerms[innerTermCount - 1].endOffset = postings.endOffset();
+ }
+
+ @Override
+ public void reset() {
+ innerTermCount = 0;
+ }
+ };
+
+ @Override
+ public boolean next() throws IOException {
+ innerTermCount = 0;
+ return spans.nextStartPosition() != Spans.NO_MORE_POSITIONS;
+ }
+
+ @Override
+ public int startPosition() {
+ return spans.startPosition();
+ }
+
+ @Override
+ public int endPosition() {
+ return spans.endPosition() - 1;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ if (innerTermCount == 0) {
+ collectInnerTerms();
+ }
+ return innerTerms[0].startOffset;
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ if (innerTermCount == 0) {
+ collectInnerTerms();
+ }
+ return innerTerms[innerTermCount - 1].endOffset;
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ if (innerTermCount == 0) {
+ collectInnerTerms();
+ }
+ return new MatchesIterator() {
+
+ int upto = -1;
+
+ @Override
+ public boolean next() throws IOException {
+ upto++;
+ return upto < innerTermCount;
+ }
+
+ @Override
+ public int startPosition() {
+ return innerTerms[upto].position;
+ }
+
+ @Override
+ public int endPosition() {
+ return innerTerms[upto].position;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ return innerTerms[upto].startOffset;
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return innerTerms[upto].endOffset;
+ }
+
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ return null;
+ }
+
+ @Override
+ public Query getQuery() {
+ return new TermQuery(innerTerms[upto].term);
+ }
+ };
+ }
+
+ @Override
+ public Query getQuery() {
+ return SpanWeight.this.getQuery();
+ }
+
+ void collectInnerTerms() throws IOException {
+ termCollector.reset();
+ spans.collect(termCollector);
+ Arrays.sort(innerTerms, 0, innerTermCount, Comparator.comparing(a -> a.position));
+ }
+ };
+ });
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
index 3855b04..e77fca6 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
@@ -18,8 +18,12 @@
package org.apache.lucene.search;
import java.io.IOException;
+import java.util.Arrays;
import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.Objects;
import java.util.Set;
+import java.util.stream.Collectors;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
@@ -29,9 +33,14 @@ import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.index.Term;
+import org.apache.lucene.search.spans.SpanNearQuery;
+import org.apache.lucene.search.spans.SpanOrQuery;
+import org.apache.lucene.search.spans.SpanQuery;
+import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
@@ -99,7 +108,7 @@ public class TestMatchesIterator extends LuceneTestCase {
"nothing matches this document"
};
- void checkMatches(Query q, String field, int[][] expected) throws IOException {
+ private void checkMatches(Query q, String field, int[][] expected) throws IOException {
Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
for (int i = 0; i < expected.length; i++) {
LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(expected[i][0], searcher.leafContexts));
@@ -112,14 +121,40 @@ public class TestMatchesIterator extends LuceneTestCase {
MatchesIterator it = matches.getMatches(field);
if (expected[i].length == 1) {
assertNull(it);
- return;
+ continue;
}
checkFieldMatches(it, expected[i]);
checkFieldMatches(matches.getMatches(field), expected[i]); // test multiple calls
}
}
- void checkFieldMatches(MatchesIterator it, int[] expected) throws IOException {
+ private void checkLabelCount(Query q, String field, int[] expected) throws IOException {
+ Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
+ for (int i = 0; i < expected.length; i++) {
+ LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
+ int doc = i - ctx.docBase;
+ Matches matches = w.matches(ctx, doc);
+ if (matches == null) {
+ assertEquals("Expected to get matches on document " + i, 0, expected[i]);
+ continue;
+ }
+ MatchesIterator it = matches.getMatches(field);
+ if (expected[i] == 0) {
+ assertNull(it);
+ continue;
+ }
+ else {
+ assertNotNull(it);
+ }
+ IdentityHashMap<Query, Integer> labels = new IdentityHashMap<>();
+ while (it.next()) {
+ labels.put(it.getQuery(), 1);
+ }
+ assertEquals(expected[i], labels.size());
+ }
+ }
+
+ private void checkFieldMatches(MatchesIterator it, int[] expected) throws IOException {
int pos = 1;
while (it.next()) {
//System.out.println(expected[i][pos] + "->" + expected[i][pos + 1] + "[" + expected[i][pos + 2] + "->" + expected[i][pos + 3] + "]");
@@ -132,7 +167,7 @@ public class TestMatchesIterator extends LuceneTestCase {
assertEquals(expected.length, pos);
}
- void checkNoPositionsMatches(Query q, String field, boolean[] expected) throws IOException {
+ private void checkNoPositionsMatches(Query q, String field, boolean[] expected) throws IOException {
Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
for (int i = 0; i < expected.length; i++) {
LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
@@ -148,8 +183,109 @@ public class TestMatchesIterator extends LuceneTestCase {
}
}
+ private void assertIsLeafMatch(Query q, String field) throws IOException {
+ Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
+ for (int i = 0; i < searcher.reader.maxDoc(); i++) {
+ LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
+ int doc = i - ctx.docBase;
+ Matches matches = w.matches(ctx, doc);
+ if (matches == null) {
+ return;
+ }
+ MatchesIterator mi = matches.getMatches(field);
+ if (mi == null) {
+ return;
+ }
+ while (mi.next()) {
+ assertNull(mi.getSubMatches());
+ }
+ }
+ }
+
+ private void checkTermMatches(Query q, String field, TermMatch[][][] expected) throws IOException {
+ Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE_NO_SCORES, 1);
+ for (int i = 0; i < expected.length; i++) {
+ LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
+ int doc = i - ctx.docBase;
+ Matches matches = w.matches(ctx, doc);
+ if (matches == null) {
+ assertEquals(expected[i].length, 0);
+ continue;
+ }
+ MatchesIterator it = matches.getMatches(field);
+ if (expected[i].length == 0) {
+ assertNull(it);
+ continue;
+ }
+ checkTerms(expected[i], it);
+ }
+ }
+
+ private void checkTerms(TermMatch[][] expected, MatchesIterator it) throws IOException {
+ int upTo = 0;
+ while (it.next()) {
+ Set<TermMatch> expectedMatches = new HashSet<>(Arrays.asList(expected[upTo]));
+ MatchesIterator submatches = it.getSubMatches();
+ while (submatches.next()) {
+ TermMatch tm = new TermMatch(submatches.startPosition(), submatches.startOffset(), submatches.endOffset());
+ if (expectedMatches.remove(tm) == false) {
+ fail("Unexpected term match: " + tm);
+ }
+ }
+ if (expectedMatches.size() != 0) {
+ fail("Missing term matches: " + expectedMatches.stream().map(Object::toString).collect(Collectors.joining(", ")));
+ }
+ upTo++;
+ }
+ if (upTo < expected.length - 1) {
+ fail("Missing expected match");
+ }
+ }
+
+ static class TermMatch {
+
+ public final int position;
+
+ public final int startOffset;
+
+ public final int endOffset;
+
+ public TermMatch(PostingsEnum pe, int position) throws IOException {
+ this.position = position;
+ this.startOffset = pe.startOffset();
+ this.endOffset = pe.endOffset();
+ }
+
+ public TermMatch(int position, int startOffset, int endOffset) {
+ this.position = position;
+ this.startOffset = startOffset;
+ this.endOffset = endOffset;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ TermMatch termMatch = (TermMatch) o;
+ return position == termMatch.position &&
+ startOffset == termMatch.startOffset &&
+ endOffset == termMatch.endOffset;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(position, startOffset, endOffset);
+ }
+
+ @Override
+ public String toString() {
+ return position + "[" + startOffset + "->" + endOffset + "]";
+ }
+ }
+
public void testTermQuery() throws IOException {
- Query q = new TermQuery(new Term(FIELD_WITH_OFFSETS, "w1"));
+ Term t = new Term(FIELD_WITH_OFFSETS, "w1");
+ Query q = new TermQuery(t);
checkMatches(q, FIELD_WITH_OFFSETS, new int[][]{
{ 0, 0, 0, 0, 2 },
{ 1, 0, 0, 0, 2 },
@@ -157,6 +293,8 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8 },
{ 4 }
});
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 1, 1, 1, 1, 0, 0 });
+ assertIsLeafMatch(q, FIELD_WITH_OFFSETS);
}
public void testTermQueryNoStoredOffsets() throws IOException {
@@ -191,6 +329,8 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 5, 5, 15, 17 },
{ 4 }
});
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 2, 2, 1, 2, 0, 0 });
+ assertIsLeafMatch(q, FIELD_WITH_OFFSETS);
}
public void testDisjunctionNoPositions() throws IOException {
@@ -215,6 +355,7 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 5, 5, 15, 17 },
{ 4 }
});
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 2, 2, 0, 2, 0, 0 });
}
public void testReqOptNoPositions() throws IOException {
@@ -248,6 +389,8 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 2, 2, 6, 8, 3, 3, 9, 11, 5, 5, 15, 17 },
{ 4 }
});
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 3, 1, 3, 3, 0, 0 });
+ assertIsLeafMatch(q, FIELD_WITH_OFFSETS);
}
public void testMinShouldMatchNoPositions() throws IOException {
@@ -331,6 +474,8 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 1, 1, 3, 5, 2, 2, 6, 8, 4, 4, 12, 14 },
{ 4 }
});
+ checkLabelCount(rq, FIELD_WITH_OFFSETS, new int[]{ 1, 1, 1, 1, 0 });
+ assertIsLeafMatch(rq, FIELD_WITH_OFFSETS);
}
@@ -357,6 +502,7 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 3, 0, 0, 0, 2, 1, 1, 3, 5, 2, 2, 6, 8, 4, 4, 12, 14 },
{ 4 }
});
+ assertIsLeafMatch(q, FIELD_WITH_OFFSETS);
}
public void testSynonymQueryNoPositions() throws IOException {
@@ -392,12 +538,25 @@ public class TestMatchesIterator extends LuceneTestCase {
// 0 1 2 3 4 5 6 7
// "a phrase sentence with many phrase sentence iterations of a phrase sentence",
+ public void testSloppyPhraseQueryWithRepeats() throws IOException {
+ Term p = new Term(FIELD_WITH_OFFSETS, "phrase");
+ Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
+ PhraseQuery pq = new PhraseQuery(10, FIELD_WITH_OFFSETS, "phrase", "sentence", "sentence");
+ checkMatches(pq, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 1, 6, 2, 43, 2, 11, 9, 75, 5, 11, 28, 75, 6, 11, 35, 75 }
+ });
+ checkLabelCount(pq, FIELD_WITH_OFFSETS, new int[]{ 0, 0, 0, 0, 1 });
+ assertIsLeafMatch(pq, FIELD_WITH_OFFSETS);
+ }
+
public void testSloppyPhraseQuery() throws IOException {
PhraseQuery pq = new PhraseQuery(4, FIELD_WITH_OFFSETS, "a", "sentence");
checkMatches(pq, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
{ 4, 0, 2, 0, 17, 6, 9, 35, 59, 9, 11, 58, 75 }
});
+ assertIsLeafMatch(pq, FIELD_WITH_OFFSETS);
}
public void testExactPhraseQuery() throws IOException {
@@ -407,29 +566,36 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 4, 1, 2, 2, 17, 5, 6, 28, 43, 10, 11, 60, 75 }
});
+ Term a = new Term(FIELD_WITH_OFFSETS, "a");
+ Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
PhraseQuery pq2 = new PhraseQuery.Builder()
- .add(new Term(FIELD_WITH_OFFSETS, "a"))
- .add(new Term(FIELD_WITH_OFFSETS, "sentence"), 2)
+ .add(a)
+ .add(s, 2)
.build();
checkMatches(pq2, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
{ 4, 0, 2, 0, 17, 9, 11, 58, 75 }
});
+ assertIsLeafMatch(pq2, FIELD_WITH_OFFSETS);
}
// 0 1 2 3 4 5 6 7
// "a phrase sentence with many phrase sentence iterations of a phrase sentence",
public void testSloppyMultiPhraseQuery() throws IOException {
+ Term p = new Term(FIELD_WITH_OFFSETS, "phrase");
+ Term s = new Term(FIELD_WITH_OFFSETS, "sentence");
+ Term i = new Term(FIELD_WITH_OFFSETS, "iterations");
MultiPhraseQuery mpq = new MultiPhraseQuery.Builder()
- .add(new Term(FIELD_WITH_OFFSETS, "phrase"))
- .add(new Term[]{ new Term(FIELD_WITH_OFFSETS, "sentence"), new Term(FIELD_WITH_OFFSETS, "iterations") })
+ .add(p)
+ .add(new Term[]{ s, i })
.setSlop(4)
.build();
checkMatches(mpq, FIELD_WITH_OFFSETS, new int[][]{
{ 0 }, { 1 }, { 2 }, { 3 },
- { 4, 1, 2, 2, 17, 5, 7, 28, 54, 5, 7, 28, 54, 10, 11, 60, 75 }
+ { 4, 1, 2, 2, 17, 5, 6, 28, 43, 5, 7, 28, 54, 10, 11, 60, 75 }
});
+ assertIsLeafMatch(mpq, FIELD_WITH_OFFSETS);
}
public void testExactMultiPhraseQuery() throws IOException {
@@ -450,6 +616,38 @@ public class TestMatchesIterator extends LuceneTestCase {
{ 0 }, { 1 }, { 2 }, { 3 },
{ 4, 0, 1, 0, 8, 4, 5, 23, 34, 9, 10, 58, 66 }
});
+ assertIsLeafMatch(mpq2, FIELD_WITH_OFFSETS);
+ }
+
+ // 0 1 2 3 4 5 6 7
+ // "a phrase sentence with many phrase sentence iterations of a phrase sentence",
+
+ public void testSpanQuery() throws IOException {
+ SpanQuery subq = SpanNearQuery.newOrderedNearQuery(FIELD_WITH_OFFSETS)
+ .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "with")))
+ .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "many")))
+ .build();
+ Query q = SpanNearQuery.newOrderedNearQuery(FIELD_WITH_OFFSETS)
+ .addClause(new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "sentence")))
+ .addClause(new SpanOrQuery(subq, new SpanTermQuery(new Term(FIELD_WITH_OFFSETS, "iterations"))))
+ .build();
+ checkMatches(q, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 2, 4, 9, 27, 6, 7, 35, 54 }
+ });
+ checkLabelCount(q, FIELD_WITH_OFFSETS, new int[]{ 0, 0, 0, 0, 1 });
+ checkTermMatches(q, FIELD_WITH_OFFSETS, new TermMatch[][][]{
+ {}, {}, {}, {},
+ {
+ {
+ new TermMatch(2, 9, 17),
+ new TermMatch(3, 18, 22),
+ new TermMatch(4, 23, 27)
+ }, {
+ new TermMatch(6, 35, 43), new TermMatch(7, 44, 54)
+ }
+ }
+ });
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/028c86b1/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
index 4f06512..36a5633 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingMatchesIterator.java
@@ -67,4 +67,15 @@ class AssertingMatchesIterator implements MatchesIterator {
return in.endOffset();
}
+ @Override
+ public MatchesIterator getSubMatches() throws IOException {
+ assert state == State.ITERATING : state;
+ return in.getSubMatches();
+ }
+
+ @Override
+ public Query getQuery() {
+ assert state == State.ITERATING : state;
+ return in.getQuery();
+ }
}
[32/33] lucene-solr:jira/http2: LUCENE-8425: Expose hard live docs on
SegmentReader level
Posted by da...@apache.org.
LUCENE-8425: Expose hard live docs on SegmentReader level
Today if soft deletes are used we expose a union of hard and soft deletes
via LeafReader#getLiveDocs. Yet, if a users wants to take advantage of
searching also soft-deleted documents the only option today is to search
all documents even though some of them are hard deleted. The recommendation
is to not mix those but in exceptional cases ie. when a document hits a
non-aborting exception during indexing the document is marked as hard
deleted which is the correct action. In order to filter those out having
access to the hard live docs on the segment reader level allows to filter out
these documents.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/35fa0b4f
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/35fa0b4f
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/35fa0b4f
Branch: refs/heads/jira/http2
Commit: 35fa0b4f55f95ca0c8d8b21c77e78e478fba8e74
Parents: a254e7d
Author: Simon Willnauer <si...@apache.org>
Authored: Tue Jul 24 13:41:11 2018 +0200
Committer: Simon Willnauer <si...@apache.org>
Committed: Wed Jul 25 09:34:36 2018 +0200
----------------------------------------------------------------------
.../org/apache/lucene/index/ReaderPool.java | 2 +-
.../apache/lucene/index/ReadersAndUpdates.java | 5 +-
.../org/apache/lucene/index/SegmentReader.java | 49 +++++++------
.../lucene/index/StandardDirectoryReader.java | 16 +++--
.../apache/lucene/index/TestIndexWriter.java | 75 ++++++++++++++++++++
.../nrt/SegmentInfosSearcherManager.java | 2 +-
6 files changed, 118 insertions(+), 31 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/35fa0b4f/lucene/core/src/java/org/apache/lucene/index/ReaderPool.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/ReaderPool.java b/lucene/core/src/java/org/apache/lucene/index/ReaderPool.java
index 980f4a1..b792be2 100644
--- a/lucene/core/src/java/org/apache/lucene/index/ReaderPool.java
+++ b/lucene/core/src/java/org/apache/lucene/index/ReaderPool.java
@@ -89,7 +89,7 @@ final class ReaderPool implements Closeable {
LeafReaderContext leaf = leaves.get(i);
SegmentReader segReader = (SegmentReader) leaf.reader();
SegmentReader newReader = new SegmentReader(segmentInfos.info(i), segReader, segReader.getLiveDocs(),
- segReader.numDocs());
+ segReader.getHardLiveDocs(), segReader.numDocs(), true);
readerMap.put(newReader.getOriginalSegmentInfo(), new ReadersAndUpdates(segmentInfos.getIndexCreatedVersionMajor(),
newReader, newPendingDeletes(newReader, newReader.getOriginalSegmentInfo())));
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/35fa0b4f/lucene/core/src/java/org/apache/lucene/index/ReadersAndUpdates.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/ReadersAndUpdates.java b/lucene/core/src/java/org/apache/lucene/index/ReadersAndUpdates.java
index 3453447..b09338f 100644
--- a/lucene/core/src/java/org/apache/lucene/index/ReadersAndUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/ReadersAndUpdates.java
@@ -214,7 +214,7 @@ final class ReadersAndUpdates {
// force new liveDocs
Bits liveDocs = pendingDeletes.getLiveDocs();
if (liveDocs != null) {
- return new SegmentReader(info, reader, liveDocs, pendingDeletes.numDocs());
+ return new SegmentReader(info, reader, liveDocs, pendingDeletes.getHardLiveDocs(), pendingDeletes.numDocs(), true);
} else {
// liveDocs == null and reader != null. That can only be if there are no deletes
assert reader.getLiveDocs() == null;
@@ -645,7 +645,8 @@ final class ReadersAndUpdates {
private SegmentReader createNewReaderWithLatestLiveDocs(SegmentReader reader) throws IOException {
assert reader != null;
assert Thread.holdsLock(this) : Thread.currentThread().getName();
- SegmentReader newReader = new SegmentReader(info, reader, pendingDeletes.getLiveDocs(), pendingDeletes.numDocs());
+ SegmentReader newReader = new SegmentReader(info, reader, pendingDeletes.getLiveDocs(),
+ pendingDeletes.getHardLiveDocs(), pendingDeletes.numDocs(), true);
boolean success2 = false;
try {
pendingDeletes.onNewReader(newReader, info);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/35fa0b4f/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java b/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java
index 9373718..b368b96 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java
@@ -51,6 +51,7 @@ public final class SegmentReader extends CodecReader {
private final SegmentCommitInfo originalSi;
private final LeafMetaData metaData;
private final Bits liveDocs;
+ private final Bits hardLiveDocs;
// Normally set to si.maxDoc - si.delDocCount, unless we
// were created as an NRT reader from IW, in which case IW
@@ -65,7 +66,7 @@ public final class SegmentReader extends CodecReader {
final DocValuesProducer docValuesProducer;
final FieldInfos fieldInfos;
-
+
/**
* Constructs a new SegmentReader with a new core.
* @throws CorruptIndexException if the index is corrupt
@@ -87,16 +88,16 @@ public final class SegmentReader extends CodecReader {
try {
if (si.hasDeletions()) {
// NOTE: the bitvector is stored using the regular directory, not cfs
- liveDocs = codec.liveDocsFormat().readLiveDocs(directory(), si, IOContext.READONCE);
+ hardLiveDocs = liveDocs = codec.liveDocsFormat().readLiveDocs(directory(), si, IOContext.READONCE);
} else {
assert si.getDelCount() == 0;
- liveDocs = null;
+ hardLiveDocs = liveDocs = null;
}
numDocs = si.info.maxDoc() - si.getDelCount();
fieldInfos = initFieldInfos();
docValuesProducer = initDocValuesProducer();
-
+ assert assertLiveDocs(isNRT, hardLiveDocs, liveDocs);
success = true;
} finally {
// With lock-less commits, it's entirely possible (and
@@ -111,26 +112,9 @@ public final class SegmentReader extends CodecReader {
}
/** Create new SegmentReader sharing core from a previous
- * SegmentReader and loading new live docs from a new
- * deletes file. Used by openIfChanged. */
- SegmentReader(SegmentCommitInfo si, SegmentReader sr) throws IOException {
- this(si, sr,
- si.hasDeletions() ? si.info.getCodec().liveDocsFormat().readLiveDocs(si.info.dir, si, IOContext.READONCE) : null,
- si.info.maxDoc() - si.getDelCount(), false);
- }
-
- /** Create new SegmentReader sharing core from a previous
- * SegmentReader and using the provided in-memory
- * liveDocs. Used by IndexWriter to provide a new NRT
- * reader */
- SegmentReader(SegmentCommitInfo si, SegmentReader sr, Bits liveDocs, int numDocs) throws IOException {
- this(si, sr, liveDocs, numDocs, true);
- }
-
- /** Create new SegmentReader sharing core from a previous
* SegmentReader and using the provided liveDocs, and recording
* whether those liveDocs were carried in ram (isNRT=true). */
- SegmentReader(SegmentCommitInfo si, SegmentReader sr, Bits liveDocs, int numDocs, boolean isNRT) throws IOException {
+ SegmentReader(SegmentCommitInfo si, SegmentReader sr, Bits liveDocs, Bits hardLiveDocs, int numDocs, boolean isNRT) throws IOException {
if (numDocs > si.info.maxDoc()) {
throw new IllegalArgumentException("numDocs=" + numDocs + " but maxDoc=" + si.info.maxDoc());
}
@@ -141,6 +125,8 @@ public final class SegmentReader extends CodecReader {
this.originalSi = si;
this.metaData = sr.getMetaData();
this.liveDocs = liveDocs;
+ this.hardLiveDocs = hardLiveDocs;
+ assert assertLiveDocs(isNRT, hardLiveDocs, liveDocs);
this.isNRT = isNRT;
this.numDocs = numDocs;
this.core = sr.core;
@@ -159,6 +145,15 @@ public final class SegmentReader extends CodecReader {
}
}
+ private static boolean assertLiveDocs(boolean isNRT, Bits hardLiveDocs, Bits liveDocs) {
+ if (isNRT) {
+ assert hardLiveDocs == null || liveDocs != null : " liveDocs must be non null if hardLiveDocs are non null";
+ } else {
+ assert hardLiveDocs == liveDocs : "non-nrt case must have identical liveDocs";
+ }
+ return true;
+ }
+
/**
* init most recent DocValues for the current commit
*/
@@ -361,4 +356,14 @@ public final class SegmentReader extends CodecReader {
SegmentCommitInfo getOriginalSegmentInfo() {
return originalSi;
}
+
+ /**
+ * Returns the live docs that are not hard-deleted. This is an expert API to be used with
+ * soft-deletes to filter out document that hard deleted for instance due to aborted documents or to distinguish
+ * soft and hard deleted documents ie. a rolled back tombstone.
+ * @lucene.experimental
+ */
+ public Bits getHardLiveDocs() {
+ return hardLiveDocs;
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/35fa0b4f/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java b/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java
index 3b1b72f..5b2b049 100644
--- a/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java
@@ -32,6 +32,7 @@ import java.util.concurrent.CopyOnWriteArraySet;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
+import org.apache.lucene.util.Bits;
import org.apache.lucene.util.IOUtils;
/** Default implementation of {@link DirectoryReader}. */
@@ -174,16 +175,17 @@ public final class StandardDirectoryReader extends DirectoryReader {
try {
SegmentReader newReader;
if (oldReader == null || commitInfo.info.getUseCompoundFile() != oldReader.getSegmentInfo().info.getUseCompoundFile()) {
-
// this is a new reader; in case we hit an exception we can decRef it safely
newReader = new SegmentReader(commitInfo, infos.getIndexCreatedVersionMajor(), IOContext.READ);
newReaders[i] = newReader;
} else {
if (oldReader.isNRT) {
// We must load liveDocs/DV updates from disk:
- newReaders[i] = new SegmentReader(commitInfo, oldReader);
+ Bits liveDocs = commitInfo.hasDeletions() ? commitInfo.info.getCodec().liveDocsFormat()
+ .readLiveDocs(commitInfo.info.dir, commitInfo, IOContext.READONCE) : null;
+ newReaders[i] = new SegmentReader(commitInfo, oldReader, liveDocs, liveDocs,
+ commitInfo.info.maxDoc() - commitInfo.getDelCount(), false);
} else {
-
if (oldReader.getSegmentInfo().getDelGen() == commitInfo.getDelGen()
&& oldReader.getSegmentInfo().getFieldInfosGen() == commitInfo.getFieldInfosGen()) {
// No change; this reader will be shared between
@@ -197,10 +199,14 @@ public final class StandardDirectoryReader extends DirectoryReader {
if (oldReader.getSegmentInfo().getDelGen() == commitInfo.getDelGen()) {
// only DV updates
- newReaders[i] = new SegmentReader(commitInfo, oldReader, oldReader.getLiveDocs(), oldReader.numDocs(), false); // this is not an NRT reader!
+ newReaders[i] = new SegmentReader(commitInfo, oldReader, oldReader.getLiveDocs(),
+ oldReader.getHardLiveDocs(), oldReader.numDocs(), false); // this is not an NRT reader!
} else {
// both DV and liveDocs have changed
- newReaders[i] = new SegmentReader(commitInfo, oldReader);
+ Bits liveDocs = commitInfo.hasDeletions() ? commitInfo.info.getCodec().liveDocsFormat()
+ .readLiveDocs(commitInfo.info.dir, commitInfo, IOContext.READONCE) : null;
+ newReaders[i] = new SegmentReader(commitInfo, oldReader, liveDocs, liveDocs,
+ commitInfo.info.maxDoc() - commitInfo.getDelCount(), false);
}
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/35fa0b4f/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
index 85e6979..4861929 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
@@ -3144,6 +3144,10 @@ public class TestIndexWriter extends LuceneTestCase {
numSoftDeleted += info.getSoftDelCount();
}
assertEquals(writer.maxDoc() - writer.numDocs(), numSoftDeleted);
+ for (LeafReaderContext context : reader.leaves()) {
+ LeafReader leaf = context.reader();
+ assertNull(((SegmentReader) leaf).getHardLiveDocs());
+ }
writer.close();
reader.close();
dir.close();
@@ -3263,6 +3267,12 @@ public class TestIndexWriter extends LuceneTestCase {
assertEquals(1, topDocs.totalHits);
}
}
+ if (mixDeletes == false) {
+ for (LeafReaderContext context : reader.leaves()) {
+ LeafReader leaf = context.reader();
+ assertNull(((SegmentReader) leaf).getHardLiveDocs());
+ }
+ }
mergeAwaySoftDeletes.set(true);
writer.addDocument(new Document()); // add a dummy doc to trigger a segment here
writer.flush();
@@ -3524,4 +3534,69 @@ public class TestIndexWriter extends LuceneTestCase {
w.close();
d.close();
}
+
+ public void testSoftAndHardLiveDocs() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriterConfig indexWriterConfig = newIndexWriterConfig();
+ String softDeletesField = "soft_delete";
+ indexWriterConfig.setSoftDeletesField(softDeletesField);
+ IndexWriter writer = new IndexWriter(dir, indexWriterConfig);
+ Set<Integer> uniqueDocs = new HashSet<>();
+ for (int i = 0; i < 100; i++) {
+ int docId = random().nextInt(5);
+ uniqueDocs.add(docId);
+ Document doc = new Document();
+ doc.add(new StringField("id", String.valueOf(docId), Field.Store.YES));
+ if (docId % 2 == 0) {
+ writer.updateDocument(new Term("id", String.valueOf(docId)), doc);
+ } else {
+ writer.softUpdateDocument(new Term("id", String.valueOf(docId)), doc,
+ new NumericDocValuesField(softDeletesField, 0));
+ }
+ if (random().nextBoolean()) {
+ assertHardLiveDocs(writer, uniqueDocs);
+ }
+ }
+
+ if (random().nextBoolean()) {
+ writer.commit();
+ }
+ assertHardLiveDocs(writer, uniqueDocs);
+
+
+ IOUtils.close(writer, dir);
+ }
+
+ private void assertHardLiveDocs(IndexWriter writer, Set<Integer> uniqueDocs) throws IOException {
+ try (DirectoryReader reader = DirectoryReader.open(writer)) {
+ assertEquals(uniqueDocs.size(), reader.numDocs());
+ List<LeafReaderContext> leaves = reader.leaves();
+ for (LeafReaderContext ctx : leaves) {
+ LeafReader leaf = ctx.reader();
+ assertTrue(leaf instanceof SegmentReader);
+ SegmentReader sr = (SegmentReader) leaf;
+ if (sr.getHardLiveDocs() != null) {
+ Terms id = sr.terms("id");
+ TermsEnum iterator = id.iterator();
+ Bits hardLiveDocs = sr.getHardLiveDocs();
+ Bits liveDocs = sr.getLiveDocs();
+ for (Integer dId : uniqueDocs) {
+ boolean mustBeHardDeleted = dId % 2 == 0;
+ if (iterator.seekExact(new BytesRef(dId.toString()))) {
+ PostingsEnum postings = iterator.postings(null);
+ while (postings.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
+ if (liveDocs.get(postings.docID())) {
+ assertTrue(hardLiveDocs.get(postings.docID()));
+ } else if (mustBeHardDeleted) {
+ assertFalse(hardLiveDocs.get(postings.docID()));
+ } else {
+ assertTrue(hardLiveDocs.get(postings.docID()));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/35fa0b4f/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/SegmentInfosSearcherManager.java
----------------------------------------------------------------------
diff --git a/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/SegmentInfosSearcherManager.java b/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/SegmentInfosSearcherManager.java
index a04464a..d18ee10 100644
--- a/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/SegmentInfosSearcherManager.java
+++ b/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/SegmentInfosSearcherManager.java
@@ -107,7 +107,7 @@ class SegmentInfosSearcherManager extends ReferenceManager<IndexSearcher> {
DirectoryReader r = StandardDirectoryReader.open(dir, currentInfos, subs);
addReaderClosedListener(r);
node.message("refreshed to version=" + currentInfos.getVersion() + " r=" + r);
- return SearcherManager.getSearcher(searcherFactory, r, (DirectoryReader) old.getIndexReader());
+ return SearcherManager.getSearcher(searcherFactory, r, old.getIndexReader());
}
private void addReaderClosedListener(IndexReader r) {
[33/33] lucene-solr:jira/http2: Merge branch 'master' into jira/http2
Posted by da...@apache.org.
Merge branch 'master' into jira/http2
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/5bac295b
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/5bac295b
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/5bac295b
Branch: refs/heads/jira/http2
Commit: 5bac295be1fb8bc6c737d06bd0ea92c30181635f
Parents: 1d1ef15 35fa0b4
Author: Cao Manh Dat <da...@apache.org>
Authored: Wed Jul 25 15:33:00 2018 +0700
Committer: Cao Manh Dat <da...@apache.org>
Committed: Wed Jul 25 15:33:00 2018 +0700
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 +
.../lucene/index/FrozenBufferedUpdates.java | 12 +-
.../org/apache/lucene/index/IndexWriter.java | 17 +-
.../org/apache/lucene/index/ReaderPool.java | 2 +-
.../apache/lucene/index/ReadersAndUpdates.java | 5 +-
.../org/apache/lucene/index/SegmentReader.java | 49 +-
.../lucene/index/StandardDirectoryReader.java | 16 +-
.../search/DisjunctionMatchesIterator.java | 17 +-
.../lucene/search/DocValuesRewriteMethod.java | 2 +-
.../apache/lucene/search/MatchesIterator.java | 24 +
.../apache/lucene/search/MultiPhraseQuery.java | 5 +-
.../MultiTermQueryConstantScoreWrapper.java | 2 +-
.../org/apache/lucene/search/PhraseMatcher.java | 1 +
.../org/apache/lucene/search/PhraseQuery.java | 4 +-
.../org/apache/lucene/search/PhraseWeight.java | 10 +
.../lucene/search/SloppyPhraseMatcher.java | 65 +-
.../org/apache/lucene/search/SynonymQuery.java | 2 +-
.../apache/lucene/search/TermInSetQuery.java | 2 +-
.../lucene/search/TermMatchesIterator.java | 13 +-
.../org/apache/lucene/search/TermQuery.java | 2 +-
.../apache/lucene/search/spans/SpanWeight.java | 140 ++
.../java/org/apache/lucene/store/Directory.java | 194 +-
.../org/apache/lucene/store/IndexOutput.java | 13 +-
.../org/apache/lucene/index/TestAddIndexes.java | 2 +-
.../lucene/index/TestForceMergeForever.java | 2 +-
.../apache/lucene/index/TestIndexWriter.java | 105 +-
.../lucene/index/TestPerSegmentDeletes.java | 6 +-
.../TestSoftDeletesRetentionMergePolicy.java | 14 +-
.../lucene/index/TestTieredMergePolicy.java | 16 +-
.../lucene/search/TestMatchesIterator.java | 218 ++-
.../org/apache/lucene/util/bkd/TestBKD.java | 7 +-
.../nrt/SegmentInfosSearcherManager.java | 2 +-
.../org/apache/lucene/mockfile/ExtrasFS.java | 18 +-
.../lucene/search/AssertingMatchesIterator.java | 11 +
.../lucene/store/BaseDirectoryTestCase.java | 1652 +++++++++---------
.../lucene/store/MockDirectoryWrapper.java | 40 +-
.../org/apache/lucene/util/LuceneTestCase.java | 40 +-
.../lucene/store/TestMockDirectoryWrapper.java | 9 +-
solr/CHANGES.txt | 9 +
...ractNamedEntitiesUpdateProcessorFactory.java | 16 +-
...ractNamedEntitiesUpdateProcessorFactory.java | 9 +-
.../apache/solr/handler/export/DoubeValue.java | 81 -
.../apache/solr/handler/export/DoubleValue.java | 81 +
.../apache/solr/search/facet/FacetRequest.java | 56 +-
.../command/TopGroupsFieldCommand.java | 6 +-
.../solr/handler/export/TestExportWriter.java | 140 +-
.../org/apache/solr/search/facet/DebugAgg.java | 16 +-
.../facet/TestJsonFacetsStatsParsing.java | 106 ++
solr/solr-ref-guide/src/cloud-screens.adoc | 14 +-
.../src/images/cloud-screens/cloud-graph.png | Bin 54929 -> 94496 bytes
.../src/images/cloud-screens/cloud-hover.png | Bin 0 -> 83343 bytes
.../src/images/cloud-screens/cloud-radial.png | Bin 62572 -> 102878 bytes
.../src/images/cloud-screens/cloud-tree.png | Bin 105371 -> 122158 bytes
solr/solr-ref-guide/src/json-facet-api.adoc | 29 +-
54 files changed, 2011 insertions(+), 1295 deletions(-)
----------------------------------------------------------------------
[29/33] lucene-solr:jira/http2: LUCENE-8414: Make segmentInfos
private in IndexWriter
Posted by da...@apache.org.
LUCENE-8414: Make segmentInfos private in IndexWriter
Today IW#SegmentInfos is package-private and can be accessed directly.
Unlike the production code which accesses the SegmentInfo with IW lock,
tests can access it without holding IW lock. This causes these tests
sometimes fail because they are checking an inconsistent view of
SegmentInfos due to a concurrent modification.
This commit makes SegmentInfos private in IndexWriter and ensures that
we snapshot SegmentInfos in our tests.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/d66c05ce
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/d66c05ce
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/d66c05ce
Branch: refs/heads/jira/http2
Commit: d66c05ce4f9ebe107f9589007f6899681ce2444a
Parents: d010cdd
Author: Nhat Nguyen <nh...@elastic.co>
Authored: Mon Jul 23 23:02:07 2018 -0400
Committer: Nhat Nguyen <nh...@elastic.co>
Committed: Tue Jul 24 12:39:27 2018 -0400
----------------------------------------------------------------------
lucene/CHANGES.txt | 2 ++
.../apache/lucene/index/FrozenBufferedUpdates.java | 12 ++++++------
.../java/org/apache/lucene/index/IndexWriter.java | 17 ++++++++++++++++-
.../org/apache/lucene/index/TestAddIndexes.java | 2 +-
.../apache/lucene/index/TestForceMergeForever.java | 2 +-
.../org/apache/lucene/index/TestIndexWriter.java | 16 ++++++++--------
.../apache/lucene/index/TestPerSegmentDeletes.java | 6 +++---
.../index/TestSoftDeletesRetentionMergePolicy.java | 14 +++++++-------
.../apache/lucene/index/TestTieredMergePolicy.java | 16 ++++++++--------
9 files changed, 52 insertions(+), 35 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index e324f2c..9757505 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -204,6 +204,8 @@ Improvements
* LUCENE-8415: Clean up Directory contracts and JavaDoc comments. (Dawid Weiss)
+* LUCENE-8414: Make segmentInfos private in IndexWriter (Simon Willnauer, Nhat Nguyen)
+
Other:
* LUCENE-8366: Upgrade to ICU 62.1. Emoji handling now uses Unicode 11's
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java b/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
index ee36cf4..1e234b7 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
@@ -196,18 +196,18 @@ final class FrozenBufferedUpdates {
* if the private segment was already merged away. */
private List<SegmentCommitInfo> getInfosToApply(IndexWriter writer) {
assert Thread.holdsLock(writer);
- List<SegmentCommitInfo> infos;
+ final List<SegmentCommitInfo> infos;
if (privateSegment != null) {
- if (writer.segmentInfos.indexOf(privateSegment) == -1) {
+ if (writer.segmentCommitInfoExist(privateSegment)) {
+ infos = Collections.singletonList(privateSegment);
+ }else {
if (infoStream.isEnabled("BD")) {
infoStream.message("BD", "private segment already gone; skip processing updates");
}
- return null;
- } else {
- infos = Collections.singletonList(privateSegment);
+ infos = null;
}
} else {
- infos = writer.segmentInfos.asList();
+ infos = writer.listOfSegmentCommitInfos();
}
return infos;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
index 3782843..ca977a9 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
@@ -291,7 +291,7 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable,
private Collection<String> filesToCommit;
- final SegmentInfos segmentInfos; // the segments
+ private final SegmentInfos segmentInfos;
final FieldNumbers globalFieldNumberMap;
final DocumentsWriter docWriter;
@@ -5229,4 +5229,19 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable,
throw new IllegalArgumentException("SegmentCommitInfo must be from the same directory");
}
}
+
+ /** Checks if the provided segment exists in the current segmentInfos */
+ final synchronized boolean segmentCommitInfoExist(SegmentCommitInfo sci) {
+ return segmentInfos.contains(sci);
+ }
+
+ /** Returns an unmodifiable view of the list of all segments of the current segmentInfos */
+ final synchronized List<SegmentCommitInfo> listOfSegmentCommitInfos() {
+ return segmentInfos.asList();
+ }
+
+ /** Tests should use this method to snapshot the current segmentInfos to have a consistent view */
+ final synchronized SegmentInfos cloneSegmentInfos() {
+ return segmentInfos.clone();
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java b/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java
index 1307318..6b9312b 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java
@@ -1442,7 +1442,7 @@ public class TestAddIndexes extends LuceneTestCase {
assertEquals(wrappedReader.numDocs(), writer.numDocs());
assertEquals(maxDoc, writer.maxDoc());
writer.commit();
- SegmentCommitInfo commitInfo = writer.segmentInfos.asList().get(0);
+ SegmentCommitInfo commitInfo = writer.listOfSegmentCommitInfos().get(0);
assertEquals(maxDoc-wrappedReader.numDocs(), commitInfo.getSoftDelCount());
writer.close();
Directory dir3 = newDirectory();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/core/src/test/org/apache/lucene/index/TestForceMergeForever.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestForceMergeForever.java b/lucene/core/src/test/org/apache/lucene/index/TestForceMergeForever.java
index 8626fe5..c2152f0 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestForceMergeForever.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestForceMergeForever.java
@@ -70,7 +70,7 @@ public class TestForceMergeForever extends LuceneTestCase {
w.addDocument(docs.nextDoc());
}
MergePolicy mp = w.getConfig().getMergePolicy();
- final int mergeAtOnce = 1+w.segmentInfos.size();
+ final int mergeAtOnce = 1+w.listOfSegmentCommitInfos().size();
if (mp instanceof TieredMergePolicy) {
((TieredMergePolicy) mp).setMaxMergeAtOnce(mergeAtOnce);
} else if (mp instanceof LogMergePolicy) {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
index 31740f9..85e6979 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
@@ -3140,7 +3140,7 @@ public class TestIndexWriter extends LuceneTestCase {
topDocs = searcher.search(new TermQuery(new Term("id", "1")), 10);
assertEquals(0, topDocs.totalHits);
int numSoftDeleted = 0;
- for (SegmentCommitInfo info : writer.segmentInfos) {
+ for (SegmentCommitInfo info : writer.cloneSegmentInfos()) {
numSoftDeleted += info.getSoftDelCount();
}
assertEquals(writer.maxDoc() - writer.numDocs(), numSoftDeleted);
@@ -3283,7 +3283,7 @@ public class TestIndexWriter extends LuceneTestCase {
}
}
int numSoftDeleted = 0;
- for (SegmentCommitInfo info : writer.segmentInfos) {
+ for (SegmentCommitInfo info : writer.cloneSegmentInfos()) {
numSoftDeleted += info.getSoftDelCount() + info.getDelCount();
}
assertEquals(writer.maxDoc() - writer.numDocs(), numSoftDeleted);
@@ -3349,7 +3349,7 @@ public class TestIndexWriter extends LuceneTestCase {
private static void assertFiles(IndexWriter writer) throws IOException {
Predicate<String> filter = file -> file.startsWith("segments") == false && file.equals("write.lock") == false;
// remove segment files we don't know if we have committed and what is kept around
- Set<String> segFiles = writer.segmentInfos.files(true).stream()
+ Set<String> segFiles = new HashSet<>(writer.cloneSegmentInfos().files(true)).stream()
.filter(filter).collect(Collectors.toSet());
Set<String> dirFiles = Arrays.stream(writer.getDirectory().listAll())
.filter(file -> !ExtrasFS.isExtra(file)) // ExtraFS might add an files, ignore them
@@ -3371,12 +3371,12 @@ public class TestIndexWriter extends LuceneTestCase {
d.add(new StringField("id", "doc-1", Field.Store.YES));
writer.addDocument(d);
writer.deleteDocuments(new Term("id", "doc-1"));
- assertEquals(1, writer.segmentInfos.asList().size());
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
writer.flush();
- assertEquals(1, writer.segmentInfos.asList().size());
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
writer.commit();
assertFiles(writer);
- assertEquals(1, writer.segmentInfos.asList().size());
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
IOUtils.close(writer, dir);
}
@@ -3437,7 +3437,7 @@ public class TestIndexWriter extends LuceneTestCase {
tombstone.add(new NumericDocValuesField("my_deletes", 1));
writer.addDocument(tombstone);
writer.flush();
- for (SegmentCommitInfo si : writer.segmentInfos) {
+ for (SegmentCommitInfo si : writer.cloneSegmentInfos()) {
FieldInfos fieldInfos = IndexWriter.readFieldInfos(si);
assertEquals("my_deletes", fieldInfos.getSoftDeletesField());
assertTrue(fieldInfos.fieldInfo("my_deletes").isSoftDeletesField());
@@ -3475,7 +3475,7 @@ public class TestIndexWriter extends LuceneTestCase {
IndexWriterConfig config = newIndexWriterConfig().setSoftDeletesField("soft_deletes_1");
IndexWriter w3 = new IndexWriter(dir3, config);
w3.addIndexes(dir1);
- for (SegmentCommitInfo si : w3.segmentInfos) {
+ for (SegmentCommitInfo si : w3.cloneSegmentInfos()) {
FieldInfo softDeleteField = IndexWriter.readFieldInfos(si).fieldInfo("soft_deletes_1");
assertTrue(softDeleteField.isSoftDeletesField());
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/core/src/test/org/apache/lucene/index/TestPerSegmentDeletes.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPerSegmentDeletes.java b/lucene/core/src/test/org/apache/lucene/index/TestPerSegmentDeletes.java
index 6e2bd13..c1032dc 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestPerSegmentDeletes.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestPerSegmentDeletes.java
@@ -49,14 +49,14 @@ public class TestPerSegmentDeletes extends LuceneTestCase {
}
//System.out.println("commit1");
writer.commit();
- assertEquals(1, writer.segmentInfos.size());
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
for (int x = 5; x < 10; x++) {
writer.addDocument(DocHelper.createDocument(x, "2", 2));
//System.out.println("numRamDocs(" + x + ")" + writer.numRamDocs());
}
//System.out.println("commit2");
writer.commit();
- assertEquals(2, writer.segmentInfos.size());
+ assertEquals(2, writer.listOfSegmentCommitInfos().size());
for (int x = 10; x < 15; x++) {
writer.addDocument(DocHelper.createDocument(x, "3", 2));
@@ -90,7 +90,7 @@ public class TestPerSegmentDeletes extends LuceneTestCase {
fsmp.length = 2;
writer.maybeMerge();
- assertEquals(2, writer.segmentInfos.size());
+ assertEquals(2, writer.listOfSegmentCommitInfos().size());
// id:2 shouldn't exist anymore because
// it's been applied in the merge and now it's gone
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/core/src/test/org/apache/lucene/index/TestSoftDeletesRetentionMergePolicy.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestSoftDeletesRetentionMergePolicy.java b/lucene/core/src/test/org/apache/lucene/index/TestSoftDeletesRetentionMergePolicy.java
index fec55ac..f6c1f6c 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestSoftDeletesRetentionMergePolicy.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestSoftDeletesRetentionMergePolicy.java
@@ -392,7 +392,7 @@ public class TestSoftDeletesRetentionMergePolicy extends LuceneTestCase {
// We expect any MP to merge these segments into one segment
// when calling forceMergeDeletes.
writer.forceMergeDeletes(true);
- assertEquals(1, writer.segmentInfos.asList().size());
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
assertEquals(1, writer.numDocs());
assertEquals(1, writer.maxDoc());
writer.close();
@@ -415,7 +415,7 @@ public class TestSoftDeletesRetentionMergePolicy extends LuceneTestCase {
writer.addDocument(d);
}
writer.flush();
- assertEquals(1, writer.segmentInfos.asList().size());
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
if (softDelete != null) {
// the newly created segment should be dropped as it is fully deleted (i.e. only contains deleted docs).
@@ -443,7 +443,7 @@ public class TestSoftDeletesRetentionMergePolicy extends LuceneTestCase {
IndexReader reader = writer.getReader();
assertEquals(reader.numDocs(), 1);
reader.close();
- assertEquals(1, writer.segmentInfos.asList().size());
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
writer.close();
dir.close();
@@ -602,8 +602,8 @@ public class TestSoftDeletesRetentionMergePolicy extends LuceneTestCase {
}
}
writer.forceMergeDeletes(true);
- assertEquals(1, writer.segmentInfos.size());
- SegmentCommitInfo si = writer.segmentInfos.info(0);
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
+ SegmentCommitInfo si = writer.listOfSegmentCommitInfos().get(0);
assertEquals(0, si.getSoftDelCount()); // hard-delete should supersede the soft-delete
assertEquals(0, si.getDelCount());
assertEquals(1, si.info.maxDoc());
@@ -623,8 +623,8 @@ public class TestSoftDeletesRetentionMergePolicy extends LuceneTestCase {
doUpdate(new Term("id", "0"), writer,
new NumericDocValuesField("soft_delete", 1), new NumericDocValuesField("other-field", 1));
sm.maybeRefreshBlocking();
- assertEquals(1, writer.segmentInfos.asList().size());
- SegmentCommitInfo si = writer.segmentInfos.asList().get(0);
+ assertEquals(1, writer.listOfSegmentCommitInfos().size());
+ SegmentCommitInfo si = writer.listOfSegmentCommitInfos().get(0);
assertEquals(1, si.getSoftDelCount());
assertEquals(1, si.info.maxDoc());
IOUtils.close(sm, writer, dir);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d66c05ce/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java b/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java
index 02a919f..a7f2111 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java
@@ -181,7 +181,7 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {
//
// 2> We could have 10 segments and a target count of 2. In that case there could be 5 segments resulting.
// as long as they're all < 125% max seg size, that's valid.
- Iterator<SegmentCommitInfo> iterator = w.segmentInfos.iterator();
+ Iterator<SegmentCommitInfo> iterator = w.cloneSegmentInfos().iterator();
while (iterator.hasNext()) {
SegmentCommitInfo info = iterator.next();
assertTrue("No segment should be more than 125% of max segment size ",
@@ -275,7 +275,7 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {
w.forceMerge(Integer.MAX_VALUE);
checkSegmentsInExpectations(w, segNamesBefore, true);
- checkSegmentSizeNotExceeded(w.segmentInfos, maxSegBytes);
+ checkSegmentSizeNotExceeded(w.cloneSegmentInfos(), maxSegBytes);
// Delete 12-17% of each segment and expungeDeletes. This should result in:
@@ -285,7 +285,7 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {
int remainingDocs = numDocs - deletePctDocsFromEachSeg(w, random().nextInt(5) + 12, true);
w.forceMergeDeletes();
w.commit();
- checkSegmentSizeNotExceeded(w.segmentInfos, maxSegBytes);
+ checkSegmentSizeNotExceeded(w.cloneSegmentInfos(), maxSegBytes);
assertFalse("There should be no deleted docs in the index.", w.hasDeletions());
// Check that deleting _fewer_ than 10% doesn't merge inappropriately. Nothing should be merged since no segment
@@ -301,7 +301,7 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {
// This time, forceMerge. By default this should respect max segment size.
// Will change for LUCENE-8236
w.forceMerge(Integer.MAX_VALUE);
- checkSegmentSizeNotExceeded(w.segmentInfos, maxSegBytes);
+ checkSegmentSizeNotExceeded(w.cloneSegmentInfos(), maxSegBytes);
// Now forceMerge down to one segment, there should be exactly remainingDocs in exactly one segment.
w.forceMerge(1);
@@ -346,9 +346,9 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {
w.commit(); // want to trigger merge no matter what.
- assertEquals("There should be exactly one very large and one small segment", w.segmentInfos.size(), 2);
- SegmentCommitInfo info0 = w.segmentInfos.info(0);
- SegmentCommitInfo info1 = w.segmentInfos.info(1);
+ assertEquals("There should be exactly one very large and one small segment", 2, w.listOfSegmentCommitInfos().size());
+ SegmentCommitInfo info0 = w.listOfSegmentCommitInfos().get(0);
+ SegmentCommitInfo info1 = w.listOfSegmentCommitInfos().get(1);
int largeSegDocCount = Math.max(info0.info.maxDoc(), info1.info.maxDoc());
int smallSegDocCount = Math.min(info0.info.maxDoc(), info1.info.maxDoc());
assertEquals("The large segment should have a bunch of docs", largeSegDocCount, remainingDocs);
@@ -413,7 +413,7 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {
List<String> getSegmentNames(IndexWriter w) {
List<String> names = new ArrayList<>();
- for (SegmentCommitInfo info : w.segmentInfos) {
+ for (SegmentCommitInfo info : w.cloneSegmentInfos()) {
names.add(info.info.name);
}
return names;