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/12/07 09:57:16 UTC
[01/37] lucene-solr:jira/http2: SOLR-12801: Raise
THREAD_POOL_MAX_IDLE_TIME_MS.
Repository: lucene-solr
Updated Branches:
refs/heads/jira/http2 cb3ebcb12 -> 9f765aaf8
SOLR-12801: Raise THREAD_POOL_MAX_IDLE_TIME_MS.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/b5a9cca1
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/b5a9cca1
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/b5a9cca1
Branch: refs/heads/jira/http2
Commit: b5a9cca1685108655cda111c798fd99cbbc1f5d0
Parents: cbe9f82
Author: markrmiller <ma...@gmail.com>
Authored: Sat Dec 1 12:42:28 2018 -0600
Committer: markrmiller <ma...@gmail.com>
Committed: Sat Dec 1 12:42:28 2018 -0600
----------------------------------------------------------------------
.../org/apache/solr/client/solrj/embedded/JettySolrRunner.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b5a9cca1/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java b/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
index 5b5a032..e9d8419 100644
--- a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
+++ b/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
@@ -85,7 +85,7 @@ public class JettySolrRunner {
private static final int THREAD_POOL_MAX_THREADS = 10000;
// NOTE: needs to be larger than SolrHttpClient.threadPoolSweeperMaxIdleTime
- private static final int THREAD_POOL_MAX_IDLE_TIME_MS = 120000;
+ private static final int THREAD_POOL_MAX_IDLE_TIME_MS = 160000;
Server server;
[14/37] lucene-solr:jira/http2: SOLR-12801: Disable
TimeRoutedAliasUpdateProcessorTest because the feature leaks threads.
Posted by da...@apache.org.
SOLR-12801: Disable TimeRoutedAliasUpdateProcessorTest because the feature leaks threads.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/1408f525
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/1408f525
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/1408f525
Branch: refs/heads/jira/http2
Commit: 1408f5255fbcde6e843845375349a694f783d247
Parents: e356d79
Author: markrmiller <ma...@apache.org>
Authored: Mon Dec 3 09:06:53 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Mon Dec 3 09:07:27 2018 -0600
----------------------------------------------------------------------
.../solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java | 3 +++
1 file changed, 3 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1408f525/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java b/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
index 1fc1e25..e592654 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
@@ -36,6 +36,7 @@ import java.util.concurrent.Future;
import java.util.stream.Collectors;
import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.LuceneTestCase.AwaitsFix;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
@@ -74,6 +75,8 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+// This feature has a leak
+@AwaitsFix(bugUrl="https://issues.apache.org/jira/browse/SOLR-12801")
public class TimeRoutedAliasUpdateProcessorTest extends SolrCloudTestCase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
[28/37] lucene-solr:jira/http2: Ref Guide: typo in "parameter"
Posted by da...@apache.org.
Ref Guide: typo in "parameter"
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/ad373ff3
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/ad373ff3
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/ad373ff3
Branch: refs/heads/jira/http2
Commit: ad373ff36e81da27e75d4b7099aa6cba471bbb7f
Parents: a5fb6f8
Author: Cassandra Targett <ct...@apache.org>
Authored: Sat Dec 1 08:03:34 2018 -0600
Committer: Cassandra Targett <ct...@apache.org>
Committed: Tue Dec 4 15:08:22 2018 -0600
----------------------------------------------------------------------
solr/solr-ref-guide/src/enabling-ssl.adoc | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ad373ff3/solr/solr-ref-guide/src/enabling-ssl.adoc
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/enabling-ssl.adoc b/solr/solr-ref-guide/src/enabling-ssl.adoc
index 607064b..5edff5c 100644
--- a/solr/solr-ref-guide/src/enabling-ssl.adoc
+++ b/solr/solr-ref-guide/src/enabling-ssl.adoc
@@ -319,7 +319,7 @@ bin\solr.cmd -cloud -s cloud\node2 -z localhost:2181 -p 7574
====
curl on OS X Mavericks (10.9) has degraded SSL support. For more information and workarounds to allow one-way SSL, see http://curl.haxx.se/mail/archive-2013-10/0036.html. curl on OS X Yosemite (10.10) is improved - 2-way SSL is possible - see http://curl.haxx.se/mail/archive-2014-10/0053.html.
-The curl commands in the following sections will not work with the system `curl` on OS X Yosemite (10.10). Instead, the certificate supplied with the `-E` parameter must be in PKCS12 format, and the file supplied with the `--cacert` parametr must contain only the CA certificate, and no key (see <<Convert the Certificate and Key to PEM Format for Use with curl,above>> for instructions on creating this file):
+The curl commands in the following sections will not work with the system `curl` on OS X Yosemite (10.10). Instead, the certificate supplied with the `-E` parameter must be in PKCS12 format, and the file supplied with the `--cacert` parameter must contain only the CA certificate, and no key (see <<Convert the Certificate and Key to PEM Format for Use with curl,above>> for instructions on creating this file):
[source,bash]
curl -E solr-ssl.keystore.p12:secret --cacert solr-ssl.cacert.pem ...
[35/37] lucene-solr:jira/http2: LUCENE-8594: DV update are broken for
updates on new field
Posted by da...@apache.org.
LUCENE-8594: DV update are broken for updates on new field
A segmemnt written with Lucene70Codec failes if it ties to update
a DV field that didn't exist in the index before it was upgraded to
Lucene80Codec. We bake the DV format into the FieldInfo when it's used
the first time and therefor never go to the codec if we need to update.
yet on a field that didn't exist before and was added during an indexing
operation we have to consult the coded and get an exception.
This change fixes this issue and adds the relevant bwc 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/aaa64d70
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/aaa64d70
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/aaa64d70
Branch: refs/heads/jira/http2
Commit: aaa64d7015998f28aaffac031c4032abf73bebd6
Parents: 2e586a7
Author: Simon Willnauer <si...@apache.org>
Authored: Thu Dec 6 11:31:02 2018 +0100
Committer: Simon Willnauer <si...@apache.org>
Committed: Thu Dec 6 20:16:03 2018 +0100
----------------------------------------------------------------------
.../lucene/codecs/lucene70/Lucene70Codec.java | 5 +-
.../index/TestBackwardsCompatibility.java | 76 +++++++++++++++++++-
2 files changed, 77 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/aaa64d70/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70Codec.java
----------------------------------------------------------------------
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70Codec.java b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70Codec.java
index 6841345..0f397b1 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70Codec.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70Codec.java
@@ -55,7 +55,8 @@ public class Lucene70Codec extends Codec {
private final SegmentInfoFormat segmentInfosFormat = new Lucene70SegmentInfoFormat();
private final LiveDocsFormat liveDocsFormat = new Lucene50LiveDocsFormat();
private final CompoundFormat compoundFormat = new Lucene50CompoundFormat();
-
+ private final DocValuesFormat defaultDVFormat = DocValuesFormat.forName("Lucene70");
+
private final PostingsFormat postingsFormat = new PerFieldPostingsFormat() {
@Override
public PostingsFormat getPostingsFormatForField(String field) {
@@ -66,7 +67,7 @@ public class Lucene70Codec extends Codec {
private final DocValuesFormat docValuesFormat = new PerFieldDocValuesFormat() {
@Override
public DocValuesFormat getDocValuesFormatForField(String field) {
- throw new IllegalStateException("This codec should only be used for reading, not writing");
+ return defaultDVFormat;
}
};
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/aaa64d70/lucene/backward-codecs/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
----------------------------------------------------------------------
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java b/lucene/backward-codecs/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
index bc7b6d8..6f28797 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
@@ -1538,7 +1538,7 @@ public class TestBackwardsCompatibility extends LuceneTestCase {
assertEquals(ndvcf.longValue(), ndvf.longValue()*2);
}
}
-
+
private void assertBinaryDocValues(LeafReader r, String f, String cf) throws IOException {
BinaryDocValues bdvf = r.getBinaryDocValues(f);
BinaryDocValues bdvcf = r.getBinaryDocValues(cf);
@@ -1548,7 +1548,7 @@ public class TestBackwardsCompatibility extends LuceneTestCase {
assertEquals(getValue(bdvcf), getValue(bdvf)*2);
}
}
-
+
private void verifyDocValues(Directory dir) throws IOException {
DirectoryReader reader = DirectoryReader.open(dir);
for (LeafReaderContext context : reader.leaves()) {
@@ -1576,6 +1576,7 @@ public class TestBackwardsCompatibility extends LuceneTestCase {
updateNumeric(writer, "1", "ndv2", "ndv2_c", 300L);
updateBinary(writer, "1", "bdv1", "bdv1_c", 300L);
updateBinary(writer, "1", "bdv2", "bdv2_c", 300L);
+
writer.commit();
verifyDocValues(dir);
@@ -1587,6 +1588,77 @@ public class TestBackwardsCompatibility extends LuceneTestCase {
writer.close();
dir.close();
}
+
+ public void testSoftDeletes() throws Exception {
+ Path oldIndexDir = createTempDir("dvupdates");
+ TestUtil.unzip(getDataInputStream(dvUpdatesIndex), oldIndexDir);
+ Directory dir = newFSDirectory(oldIndexDir);
+ verifyUsesDefaultCodec(dir, dvUpdatesIndex);
+ IndexWriterConfig conf = new IndexWriterConfig(new MockAnalyzer(random())).setSoftDeletesField("__soft_delete");
+ IndexWriter writer = new IndexWriter(dir, conf);
+ int maxDoc = writer.maxDoc();
+ writer.updateDocValues(new Term("id", "1"),new NumericDocValuesField("__soft_delete", 1));
+
+ if (random().nextBoolean()) {
+ writer.commit();
+ }
+ writer.forceMerge(1);
+ writer.commit();
+ assertEquals(maxDoc-1, writer.maxDoc());
+ writer.close();
+ dir.close();
+ }
+
+ public void testDocValuesUpdatesWithNewField() throws Exception {
+ Path oldIndexDir = createTempDir("dvupdates");
+ TestUtil.unzip(getDataInputStream(dvUpdatesIndex), oldIndexDir);
+ Directory dir = newFSDirectory(oldIndexDir);
+ verifyUsesDefaultCodec(dir, dvUpdatesIndex);
+
+ // update fields and verify index
+ IndexWriterConfig conf = new IndexWriterConfig(new MockAnalyzer(random()));
+ IndexWriter writer = new IndexWriter(dir, conf);
+ // introduce a new field that we later update
+ writer.addDocument(Arrays.asList(new StringField("id", "" + Integer.MAX_VALUE, Field.Store.NO),
+ new NumericDocValuesField("new_numeric", 1),
+ new BinaryDocValuesField("new_binary", toBytes(1))));
+ writer.updateNumericDocValue(new Term("id", "1"), "new_numeric", 1);
+ writer.updateBinaryDocValue(new Term("id", "1"), "new_binary", toBytes(1));
+
+ writer.commit();
+ Runnable assertDV = () -> {
+ boolean found = false;
+ try (DirectoryReader reader = DirectoryReader.open(dir)) {
+ for (LeafReaderContext ctx : reader.leaves()) {
+ LeafReader leafReader = ctx.reader();
+ TermsEnum id = leafReader.terms("id").iterator();
+ if (id.seekExact(new BytesRef("1"))) {
+ PostingsEnum postings = id.postings(null, PostingsEnum.NONE);
+ NumericDocValues numericDocValues = leafReader.getNumericDocValues("new_numeric");
+ BinaryDocValues binaryDocValues = leafReader.getBinaryDocValues("new_binary");
+ int doc;
+ while ((doc = postings.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ found = true;
+ assertTrue(binaryDocValues.advanceExact(doc));
+ assertTrue(numericDocValues.advanceExact(doc));
+ assertEquals(1, numericDocValues.longValue());
+ assertEquals(toBytes(1), binaryDocValues.binaryValue());
+ }
+ }
+ }
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
+ assertTrue(found);
+ };
+ assertDV.run();
+ // merge all segments
+ writer.forceMerge(1);
+ writer.commit();
+ assertDV.run();
+ writer.close();
+ dir.close();
+ }
// LUCENE-5907
public void testUpgradeWithNRTReader() throws Exception {
[15/37] lucene-solr:jira/http2: SOLR-13032: Add @AwaitsFix annotation
to test.
Posted by da...@apache.org.
SOLR-13032: Add @AwaitsFix annotation to test.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/e3cbdd05
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/e3cbdd05
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/e3cbdd05
Branch: refs/heads/jira/http2
Commit: e3cbdd05052a1bab7c1bb5ec2bd1025966b2ed87
Parents: 1408f52
Author: markrmiller <ma...@apache.org>
Authored: Mon Dec 3 11:07:40 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Mon Dec 3 11:07:40 2018 -0600
----------------------------------------------------------------------
.../src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java | 2 ++
1 file changed, 2 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e3cbdd05/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java b/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java
index 33fd7de..612e55b 100644
--- a/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java
+++ b/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java
@@ -72,6 +72,7 @@ public class MaxSizeAutoCommitTest extends SolrTestCaseJ4 {
}
@Test
+ @AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/SOLR-13032")
public void testAdds() throws Exception {
int maxFileSizeBound = 1000;
// Set max size bound
@@ -137,6 +138,7 @@ public class MaxSizeAutoCommitTest extends SolrTestCaseJ4 {
}
@Test
+ @AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/SOLR-13032")
public void testDeletes() throws Exception {
int maxFileSizeBound = 1000;
[20/37] lucene-solr:jira/http2: LUCENE-8509: WordDelimiterGraphFilter
no longer adjusts offsets by default
Posted by da...@apache.org.
LUCENE-8509: WordDelimiterGraphFilter no longer adjusts offsets by default
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/75a053dd
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/75a053dd
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/75a053dd
Branch: refs/heads/jira/http2
Commit: 75a053dd696d6e632755e613380450f22c78c91b
Parents: f5867a1
Author: Alan Woodward <ro...@apache.org>
Authored: Mon Dec 3 13:36:21 2018 +0000
Committer: Alan Woodward <ro...@apache.org>
Committed: Tue Dec 4 09:47:42 2018 +0000
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 ++
.../miscellaneous/WordDelimiterGraphFilter.java | 17 ++++----
.../WordDelimiterGraphFilterFactory.java | 5 ++-
.../TestWordDelimiterGraphFilter.java | 42 +++++++++++---------
4 files changed, 41 insertions(+), 27 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/75a053dd/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index fc609a5..0a41d70 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -142,6 +142,10 @@ Changes in Runtime Behavior
anymore. This doesn't affect ordering as this is a constant factor which is
the same for every document. (Luca Cavanna via Adrien Grand)
+* LUCENE-8509: WordDelimiterGraphFilter will no longer set the offsets of internal
+ tokens by default, preventing a number of bugs when the filter is chained with
+ tokenfilters that change the length of their tokens (Alan Woodward)
+
New Features
* LUCENE-8340: LongPoint#newDistanceQuery may be used to boost scores based on
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/75a053dd/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.java
----------------------------------------------------------------------
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.java
index a438213..00ace5b 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.java
@@ -191,6 +191,8 @@ public final class WordDelimiterGraphFilter extends TokenFilter {
// used for concatenating runs of similar typed subwords (word,number)
private final WordDelimiterConcatenation concat = new WordDelimiterConcatenation();
+ private final boolean adjustInternalOffsets;
+
// number of subwords last output by concat.
private int lastConcatCount;
@@ -206,10 +208,7 @@ public final class WordDelimiterGraphFilter extends TokenFilter {
private int savedEndOffset;
private AttributeSource.State savedState;
private int lastStartOffset;
-
- // if length by start + end offsets doesn't match the term text then assume
- // this is a synonym and don't adjust the offsets.
- private boolean hasIllegalOffsets;
+ private boolean adjustingOffsets;
private int wordPos;
@@ -217,11 +216,12 @@ public final class WordDelimiterGraphFilter extends TokenFilter {
* Creates a new WordDelimiterGraphFilter
*
* @param in TokenStream to be filtered
+ * @param adjustInternalOffsets if the offsets of partial terms should be adjusted
* @param charTypeTable table containing character types
* @param configurationFlags Flags configuring the filter
* @param protWords If not null is the set of tokens to protect from being delimited
*/
- public WordDelimiterGraphFilter(TokenStream in, byte[] charTypeTable, int configurationFlags, CharArraySet protWords) {
+ public WordDelimiterGraphFilter(TokenStream in, boolean adjustInternalOffsets, byte[] charTypeTable, int configurationFlags, CharArraySet protWords) {
super(in);
if ((configurationFlags &
~(GENERATE_WORD_PARTS |
@@ -240,6 +240,7 @@ public final class WordDelimiterGraphFilter extends TokenFilter {
this.protWords = protWords;
this.iterator = new WordDelimiterIterator(
charTypeTable, has(SPLIT_ON_CASE_CHANGE), has(SPLIT_ON_NUMERICS), has(STEM_ENGLISH_POSSESSIVE));
+ this.adjustInternalOffsets = adjustInternalOffsets;
}
/**
@@ -251,7 +252,7 @@ public final class WordDelimiterGraphFilter extends TokenFilter {
* @param protWords If not null is the set of tokens to protect from being delimited
*/
public WordDelimiterGraphFilter(TokenStream in, int configurationFlags, CharArraySet protWords) {
- this(in, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords);
+ this(in, false, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords);
}
/** Iterates all words parts and concatenations, buffering up the term parts we should return. */
@@ -261,7 +262,7 @@ public final class WordDelimiterGraphFilter extends TokenFilter {
// if length by start + end offsets doesn't match the term's text then set offsets for all our word parts/concats to the incoming
// offsets. this can happen if WDGF is applied to an injected synonym, or to a stem'd form, etc:
- hasIllegalOffsets = (savedEndOffset - savedStartOffset != savedTermLength);
+ adjustingOffsets = adjustInternalOffsets && savedEndOffset - savedStartOffset == savedTermLength;
bufferedLen = 0;
lastConcatCount = 0;
@@ -391,7 +392,7 @@ public final class WordDelimiterGraphFilter extends TokenFilter {
int startOffset;
int endOffset;
- if (hasIllegalOffsets) {
+ if (adjustingOffsets == false) {
startOffset = savedStartOffset;
endOffset = savedEndOffset;
} else {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/75a053dd/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilterFactory.java
----------------------------------------------------------------------
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilterFactory.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilterFactory.java
index 613aedc..4666c7d 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilterFactory.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilterFactory.java
@@ -53,12 +53,14 @@ import static org.apache.lucene.analysis.miscellaneous.WordDelimiterIterator.*;
public class WordDelimiterGraphFilterFactory extends TokenFilterFactory implements ResourceLoaderAware {
public static final String PROTECTED_TOKENS = "protected";
public static final String TYPES = "types";
+ public static final String OFFSETS = "adjustOffsets";
private final String wordFiles;
private final String types;
private final int flags;
byte[] typeTable = null;
private CharArraySet protectedWords = null;
+ private boolean adjustOffsets = false;
/** Creates a new WordDelimiterGraphFilterFactory */
public WordDelimiterGraphFilterFactory(Map<String, String> args) {
@@ -94,6 +96,7 @@ public class WordDelimiterGraphFilterFactory extends TokenFilterFactory implemen
wordFiles = get(args, PROTECTED_TOKENS);
types = get(args, TYPES);
this.flags = flags;
+ this.adjustOffsets = getBoolean(args, OFFSETS, true);
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
@@ -117,7 +120,7 @@ public class WordDelimiterGraphFilterFactory extends TokenFilterFactory implemen
@Override
public TokenFilter create(TokenStream input) {
- return new WordDelimiterGraphFilter(input, typeTable == null ? WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE : typeTable,
+ return new WordDelimiterGraphFilter(input, adjustOffsets, typeTable == null ? WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE : typeTable,
flags, protectedWords);
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/75a053dd/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterGraphFilter.java
----------------------------------------------------------------------
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterGraphFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterGraphFilter.java
index 65d3b02..e3f3f65 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterGraphFilter.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterGraphFilter.java
@@ -64,7 +64,8 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
// test that subwords and catenated subwords have
// the correct offsets.
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("foo-bar", 5, 12)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("foo-bar", 5, 12)),
+ true, DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "foobar", "foo", "bar" },
@@ -72,7 +73,7 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
new int[] { 12, 8, 12 });
// with illegal offsets:
- wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("foo-bar", 5, 6)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("foo-bar", 5, 6)), true, DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "foobar", "foo", "bar" },
new int[] { 5, 5, 5 },
@@ -81,7 +82,8 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
public void testOffsetChange() throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("übelkeit)", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("übelkeit)", 7, 16)),
+ true, DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "übelkeit" },
@@ -91,7 +93,8 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
public void testOffsetChange2() throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("(übelkeit", 7, 17)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("(übelkeit", 7, 17)),
+ true, DEFAULT_WORD_DELIM_TABLE, flags, null);
// illegal offsets:
assertTokenStreamContents(wdf,
new String[] { "übelkeit" },
@@ -101,7 +104,8 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
public void testOffsetChange3() throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("(übelkeit", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("(übelkeit", 7, 16)),
+ true, DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "übelkeit" },
new int[] { 8 },
@@ -110,7 +114,8 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
public void testOffsetChange4() throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("(foo,bar)", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("(foo,bar)", 7, 16)),
+ true, DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "foobar", "foo", "bar"},
@@ -120,7 +125,7 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
public void doSplit(final String input, String... output) throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(keywordMockTokenizer(input),
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(keywordMockTokenizer(input), false,
WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf, output);
@@ -182,7 +187,7 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
// the correct offsets.
Token token = new Token("foo-bar", 5, 12);
token.setType("mytype");
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(token), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(token), flags, null);
assertTokenStreamContents(wdf,
new String[] {"foobar", "foo", "bar"},
@@ -235,7 +240,7 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
public TokenStreamComponents createComponents(String field) {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new WordDelimiterGraphFilter(
- tokenizer,
+ tokenizer, true, DEFAULT_WORD_DELIM_TABLE,
flags, protWords));
}
};
@@ -272,7 +277,7 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
public TokenStreamComponents createComponents(String field) {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new WordDelimiterGraphFilter(
- new LargePosIncTokenFilter(tokenizer),
+ new LargePosIncTokenFilter(tokenizer), true, DEFAULT_WORD_DELIM_TABLE,
flags, protWords));
}
};
@@ -317,7 +322,7 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
public TokenStreamComponents createComponents(String field) {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
StopFilter filter = new StopFilter(tokenizer, EnglishAnalyzer.ENGLISH_STOP_WORDS_SET);
- return new TokenStreamComponents(tokenizer, new WordDelimiterGraphFilter(filter, flags, protWords));
+ return new TokenStreamComponents(tokenizer, new WordDelimiterGraphFilter(filter, true, DEFAULT_WORD_DELIM_TABLE, flags, protWords));
}
};
@@ -350,8 +355,8 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
assertAnalyzesTo(keywordTestAnalyzer(GENERATE_WORD_PARTS | IGNORE_KEYWORDS),
"abc-def klm-nop kpop",
new String[] {"abc", "def", "klm-nop", "kpop"},
- new int[]{0, 4, 8, 16},
- new int[]{3, 7, 15, 20},
+ new int[]{0, 0, 8, 16},
+ new int[]{7, 7, 15, 20},
null,
new int[]{1, 1, 1, 1},
null,
@@ -384,7 +389,7 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
@Override
public TokenStreamComponents createComponents(String field) {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
- return new TokenStreamComponents(tokenizer, new WordDelimiterGraphFilter(tokenizer, flags, null));
+ return new TokenStreamComponents(tokenizer, new WordDelimiterGraphFilter(tokenizer, true, DEFAULT_WORD_DELIM_TABLE, flags, null));
}
};
@@ -414,8 +419,8 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
assertAnalyzesTo(a, "abc-def-123-456",
new String[] { "abcdef123456", "abc-def-123-456", "abcdef", "abc", "def", "123456", "123", "456" },
- new int[] { 0, 0, 0, 0, 4, 8, 8, 12 },
- new int[] { 15, 15, 7, 3, 7, 15, 11, 15 },
+ new int[] { 0, 0, 0, 0, 0, 0, 0, 0 },
+ new int[] { 15, 15, 15, 15, 15, 15, 15, 15 },
null,
new int[] { 1, 0, 0, 0, 1, 1, 0, 1 },
null,
@@ -954,7 +959,8 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
}
public void testEmptyString() throws Exception {
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("", 0, 0)), DEFAULT_WORD_DELIM_TABLE, GENERATE_WORD_PARTS | CATENATE_ALL | PRESERVE_ORIGINAL, null);
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(new CannedTokenStream(new Token("", 0, 0)),
+ GENERATE_WORD_PARTS | CATENATE_ALL | PRESERVE_ORIGINAL, null);
wdf.reset();
assertTrue(wdf.incrementToken());
assertFalse(wdf.incrementToken());
@@ -967,7 +973,7 @@ public class TestWordDelimiterGraphFilter extends BaseTokenStreamTestCase {
new Token("foo-bar", 0, 7));
CharArraySet protectedWords = new CharArraySet(new HashSet<>(Arrays.asList("foo17-BAR")), true);
- WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(tokens, DEFAULT_WORD_DELIM_TABLE, GENERATE_WORD_PARTS | PRESERVE_ORIGINAL | CATENATE_ALL, protectedWords);
+ WordDelimiterGraphFilter wdf = new WordDelimiterGraphFilter(tokens, GENERATE_WORD_PARTS | PRESERVE_ORIGINAL | CATENATE_ALL, protectedWords);
assertGraphStrings(wdf,
"foo17-bar foo bar",
"foo17-bar foo-bar",
[16/37] lucene-solr:jira/http2: SOLR-12801: Wait for thread on close
and add AwaitsFix annotation - most of these sim tests can fail to elect
shard leaders.
Posted by da...@apache.org.
SOLR-12801: Wait for thread on close and add AwaitsFix annotation - most of these sim tests can fail to elect shard leaders.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/e14432ef
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/e14432ef
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/e14432ef
Branch: refs/heads/jira/http2
Commit: e14432efd8dda81c86cba557255652cfaa377a28
Parents: e3cbdd0
Author: markrmiller <ma...@apache.org>
Authored: Mon Dec 3 17:40:28 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Mon Dec 3 17:40:51 2018 -0600
----------------------------------------------------------------------
.../org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java | 5 +++++
.../solr/cloud/autoscaling/sim/TestSimExtremeIndexing.java | 3 +++
2 files changed, 8 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e14432ef/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java
index 9a6b73f..a6d76c8 100644
--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java
+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java
@@ -889,6 +889,11 @@ public class SimCloudManager implements SolrCloudManager {
IOUtils.closeQuietly(stateManager);
triggerThread.interrupt();
IOUtils.closeQuietly(triggerThread);
+ try {
+ triggerThread.join();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
IOUtils.closeQuietly(objectCache);
simCloudManagerPool.shutdownNow();
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e14432ef/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimExtremeIndexing.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimExtremeIndexing.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimExtremeIndexing.java
index a99b91c..6c5f9e6 100644
--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimExtremeIndexing.java
+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestSimExtremeIndexing.java
@@ -22,6 +22,8 @@ import java.util.Locale;
import java.util.concurrent.TimeUnit;
import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite;
+
+import org.apache.lucene.util.LuceneTestCase.AwaitsFix;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
@@ -50,6 +52,7 @@ import static org.apache.solr.cloud.autoscaling.AutoScalingHandlerTest.createAut
@TimeoutSuite(millis = 48 * 3600 * 1000)
@LogLevel("org.apache.solr.cloud.autoscaling=DEBUG;org.apache.solr.cloud.autoscaling.NodeLostTrigger=INFO;org.apache.client.solrj.cloud.autoscaling=DEBUG;org.apache.solr.cloud.autoscaling.ComputePlanAction=INFO;org.apache.solr.cloud.autoscaling.ExecutePlanAction=DEBUG;org.apache.solr.cloud.autoscaling.ScheduledTriggers=DEBUG")
//@LogLevel("org.apache.solr.cloud.autoscaling=DEBUG;org.apache.solr.cloud.autoscaling.NodeLostTrigger=INFO;org.apache.client.solrj.cloud.autoscaling=DEBUG;org.apache.solr.cloud.CloudTestUtils=TRACE")
+@AwaitsFix(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // this test can fail to elect a leader, seems to be common among sim tests
public class TestSimExtremeIndexing extends SimSolrCloudTestCase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
[07/37] lucene-solr:jira/http2: SOLR-12801 Revert breaking commit
a3ec5b5fdf and improve test to be more complete. Also,
add comments to make it easier for others to understand
TimeRoutedAliasUpdateProcessorTest
Posted by da...@apache.org.
SOLR-12801 Revert breaking commit a3ec5b5fdf and improve test
to be more complete. Also, add comments to make it easier for
others to understand TimeRoutedAliasUpdateProcessorTest
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/cf4d7494
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/cf4d7494
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/cf4d7494
Branch: refs/heads/jira/http2
Commit: cf4d7494101f48cc77a0b4fa182c789101854f6a
Parents: c951578
Author: Gus Heck <gu...@apache.org>
Authored: Sun Dec 2 16:34:40 2018 -0500
Committer: Gus Heck <gu...@apache.org>
Committed: Sun Dec 2 16:34:40 2018 -0500
----------------------------------------------------------------------
.../TimeRoutedAliasUpdateProcessor.java | 21 ++-----
.../TimeRoutedAliasUpdateProcessorTest.java | 64 +++++++++++++++++---
2 files changed, 63 insertions(+), 22 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/cf4d7494/solr/core/src/java/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessor.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessor.java
index 872404f..cc1ddb8 100644
--- a/solr/core/src/java/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessor.java
+++ b/solr/core/src/java/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessor.java
@@ -41,7 +41,6 @@ import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.UpdateParams;
-import org.apache.solr.common.util.ExecutorUtil;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.admin.CollectionsHandler;
@@ -97,9 +96,9 @@ public class TimeRoutedAliasUpdateProcessor extends UpdateRequestProcessor {
// never be updated by any async creation thread.
private List<Map.Entry<Instant, String>> parsedCollectionsDesc; // k=timestamp (start), v=collection. Sorted descending
private Aliases parsedCollectionsAliases; // a cached reference to the source of what we parse into parsedCollectionsDesc
- private volatile boolean executorRunning = false;
- private ExecutorService preemptiveCreationWaitExecutor = newMDCAwareSingleThreadExecutor(new DefaultSolrThreadFactory("TRA-preemptive-creation-wait"));
+ // This will be updated out in async creation threads see preemptiveAsync(Runnable r) for details
+ private volatile ExecutorService preemptiveCreationExecutor;
public static UpdateRequestProcessor wrap(SolrQueryRequest req, UpdateRequestProcessor next) {
//TODO get from "Collection property"
@@ -216,7 +215,7 @@ public class TimeRoutedAliasUpdateProcessor extends UpdateRequestProcessor {
// This next line blocks until all collections required by the current document have been created
return createAllRequiredCollections(docTimestamp, cmd.getPrintableId(), candidateCollectionDesc);
case ASYNC_PREEMPTIVE:
- if (!executorRunning) {
+ if (preemptiveCreationExecutor == null) {
// It's important not to add code between here and the prior call to findCandidateGivenTimestamp()
// in processAdd() that invokes updateParsedCollectionAliases(). Doing so would update parsedCollectionsDesc
// and create a race condition. We are relying on the fact that get(0) is returning the head of the parsed
@@ -248,17 +247,13 @@ public class TimeRoutedAliasUpdateProcessor extends UpdateRequestProcessor {
// would need to be shut down in a close hook to avoid test failures due to thread leaks in tests which is slightly
// more complicated from a code maintenance and readability stand point. An executor must used instead of a
// thread to ensure we pick up the proper MDC logging stuff from ExecutorUtil.
- executorRunning = true;
DefaultSolrThreadFactory threadFactory = new DefaultSolrThreadFactory("TRA-preemptive-creation");
- ExecutorService preemptiveCreationExecutor = newMDCAwareSingleThreadExecutor(threadFactory);
-
+ preemptiveCreationExecutor = newMDCAwareSingleThreadExecutor(threadFactory);
preemptiveCreationExecutor.execute(() -> {
r.run();
preemptiveCreationExecutor.shutdown();
- executorRunning = false;
+ preemptiveCreationExecutor = null;
});
-
- preemptiveCreationWaitExecutor.submit(() -> ExecutorUtil.awaitTermination(preemptiveCreationExecutor));
}
/**
@@ -418,11 +413,7 @@ public class TimeRoutedAliasUpdateProcessor extends UpdateRequestProcessor {
try {
cmdDistrib.close();
} finally {
- try {
- super.doClose();
- } finally {
- ExecutorUtil.shutdownAndAwaitTermination(preemptiveCreationWaitExecutor);
- }
+ super.doClose();
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/cf4d7494/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java b/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
index 4423030..b500a7e 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
@@ -366,6 +366,17 @@ public class TimeRoutedAliasUpdateProcessorTest extends SolrCloudTestCase {
// cause some collections to be created
ModifiableSolrParams params = params();
+
+ // TIME SENSITIVE SECTION BEGINS
+
+ // In this section we intentionally rely on timing of a race condition but the gap in collection creation time vs
+ // requesting the list of aliases and adding a single doc should be very large (1-2 seconds vs a few ms so we
+ // should always win the race) This is necessary because we are testing that we can guard against specific race
+ // conditions that happen while a collection is being created. To test this without timing sensitivity we would
+ // need a means to pass a semaphore to the server that it can use to delay collection creation
+ //
+ // This section must NOT gain any Thread.sleep() statements, nor should it gain any long running operations
+
assertUpdateResponse(add(alias, Arrays.asList(
sdoc("id", "2", "timestamp_dt", "2017-10-24T00:00:00Z"),
sdoc("id", "3", "timestamp_dt", "2017-10-25T00:00:00Z"),
@@ -375,19 +386,29 @@ public class TimeRoutedAliasUpdateProcessorTest extends SolrCloudTestCase {
assertUpdateResponse(solrClient.commit(alias));
cols = new CollectionAdminRequest.ListAliases().process(solrClient).getAliasesAsLists().get(alias);
- assertEquals(4, cols.size());
+ assertEquals(3, cols.size());
+ assertTrue("Preemptive creation appears to not be asynchronous anymore",!cols.contains("myalias_2017-10-26"));
assertNumDocs("2017-10-23", 1);
assertNumDocs("2017-10-24", 1);
assertNumDocs("2017-10-25", 3);
+ // Here we quickly add another doc in a separate request, before the collection creation has completed.
+ // This has the potential to incorrectly cause preemptive collection creation to run twice and create a
+ // second collection. TimeRoutedAliasUpdateProcessor is meant to guard against this race condition.
assertUpdateResponse(add(alias, Collections.singletonList(
sdoc("id", "6", "timestamp_dt", "2017-10-25T23:01:00Z")), // might cause duplicate preemptive creation
params));
assertUpdateResponse(solrClient.commit(alias));
+ // TIME SENSITIVE SECTION ENDS
+
waitCol("2017-10-26", numShards);
+
cols = new CollectionAdminRequest.ListAliases().process(solrClient).getAliasesAsLists().get(alias);
- assertEquals(5, cols.size());
+ assertTrue("Preemptive creation happened twice and created a collection " +
+ "further in the future than the configured time slice!",!cols.contains("myalias_2017-10-27"));
+
+ assertEquals(4, cols.size());
assertNumDocs("2017-10-23", 1);
assertNumDocs("2017-10-24", 1);
assertNumDocs("2017-10-25", 4);
@@ -398,13 +419,13 @@ public class TimeRoutedAliasUpdateProcessorTest extends SolrCloudTestCase {
.addProperty(TimeRoutedAlias.ROUTER_PREEMPTIVE_CREATE_MATH, "3DAY").process(solrClient);
assertUpdateResponse(add(alias, Collections.singletonList(
- sdoc("id", "7", "timestamp_dt", "2017-10-25T23:01:00Z")), // should cause preemptive creation now
+ sdoc("id", "7", "timestamp_dt", "2017-10-25T23:01:00Z")), // should cause preemptive creation of 10-27 now
params));
assertUpdateResponse(solrClient.commit(alias));
waitCol("2017-10-27", numShards);
cols = new CollectionAdminRequest.ListAliases().process(solrClient).getAliasesAsLists().get(alias);
- assertEquals(6,cols.size()); // only one created in async case
+ assertEquals(5,cols.size()); // only one created in async case
assertNumDocs("2017-10-23", 1);
assertNumDocs("2017-10-24", 1);
assertNumDocs("2017-10-25", 5);
@@ -412,14 +433,14 @@ public class TimeRoutedAliasUpdateProcessorTest extends SolrCloudTestCase {
assertNumDocs("2017-10-27", 0);
assertUpdateResponse(add(alias, Collections.singletonList(
- sdoc("id", "8", "timestamp_dt", "2017-10-25T23:01:00Z")), // should cause preemptive creation now
+ sdoc("id", "8", "timestamp_dt", "2017-10-25T23:01:00Z")), // should cause preemptive creation of 10-28 now
params));
assertUpdateResponse(solrClient.commit(alias));
waitCol("2017-10-27", numShards);
waitCol("2017-10-28", numShards);
cols = new CollectionAdminRequest.ListAliases().process(solrClient).getAliasesAsLists().get(alias);
- assertEquals(7,cols.size()); // Subsequent documents continue to create up to limit
+ assertEquals(6,cols.size()); // Subsequent documents continue to create up to limit
assertNumDocs("2017-10-23", 1);
assertNumDocs("2017-10-24", 1);
assertNumDocs("2017-10-25", 6);
@@ -451,7 +472,7 @@ public class TimeRoutedAliasUpdateProcessorTest extends SolrCloudTestCase {
waitCol("2017-10-29", numShards);
cols = new CollectionAdminRequest.ListAliases().process(solrClient).getAliasesAsLists().get(alias);
- assertEquals(8,cols.size());
+ assertEquals(7,cols.size());
assertNumDocs("2017-10-23", 1);
assertNumDocs("2017-10-24", 1);
assertNumDocs("2017-10-25", 6);
@@ -490,6 +511,35 @@ public class TimeRoutedAliasUpdateProcessorTest extends SolrCloudTestCase {
"rows", "0"));
assertEquals(13, resp.getResults().getNumFound());
+ assertUpdateResponse(add(alias, Collections.singletonList(
+ sdoc("id", "14", "timestamp_dt", "2017-10-31T23:01:00Z")), // should cause preemptive creation 11-01
+ params));
+ waitCol("2017-11-01", numShards);
+
+ assertUpdateResponse(add(alias, Collections.singletonList(
+ sdoc("id", "15", "timestamp_dt", "2017-10-31T23:01:00Z")), // should cause preemptive creation 11-02
+ params));
+ waitCol("2017-11-02", numShards);
+
+ assertUpdateResponse(add(alias, Collections.singletonList(
+ sdoc("id", "16", "timestamp_dt", "2017-10-31T23:01:00Z")), // should cause preemptive creation 11-03
+ params));
+ waitCol("2017-11-03", numShards);
+
+ assertUpdateResponse(add(alias, Collections.singletonList(
+ sdoc("id", "17", "timestamp_dt", "2017-10-31T23:01:00Z")), // should NOT cause preemptive creation 11-04
+ params));
+
+ cols = new CollectionAdminRequest.ListAliases().process(solrClient).getAliasesAsLists().get(alias);
+ assertTrue("Preemptive creation beyond ROUTER_PREEMPTIVE_CREATE_MATH setting of 3DAY!",!cols.contains("myalias_2017-11-04"));
+
+ assertUpdateResponse(add(alias, Collections.singletonList(
+ sdoc("id", "18", "timestamp_dt", "2017-11-01T23:01:00Z")), // should NOT cause preemptive creation 11-04
+ params));
+ waitCol("2017-11-04",numShards);
+
+ Thread.sleep(2000); // allow the executor used in preemptive creation time to shut down.
+
}
private void assertNumDocs(final String datePart, int expected) throws SolrServerException, IOException {
[03/37] lucene-solr:jira/http2: SOLR-12801: Don't possibly block
forever in this test in remaining spots.
Posted by da...@apache.org.
SOLR-12801: Don't possibly block forever in this test in remaining spots.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/e5281ef3
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/e5281ef3
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/e5281ef3
Branch: refs/heads/jira/http2
Commit: e5281ef3d5e36f5ad8a871818dd511fb9fbee74f
Parents: b294d84
Author: markrmiller <ma...@apache.org>
Authored: Sat Dec 1 13:02:51 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Sat Dec 1 13:02:58 2018 -0600
----------------------------------------------------------------------
.../solr/cloud/autoscaling/sim/TestSimDistributedQueue.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e5281ef3/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 a997571..00926f3 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
@@ -65,7 +65,7 @@ public class TestSimDistributedQueue extends SolrTestCaseJ4 {
assertNull(dq.poll());
dq.offer(data);
- dq.peek(true); // wait until data is definitely there before calling remove
+ dq.peek(15000); // wait until data is definitely there before calling remove
assertArrayEquals(dq.remove(), data);
assertNull(dq.poll());
@@ -90,7 +90,7 @@ public class TestSimDistributedQueue extends SolrTestCaseJ4 {
DistributedQueue dq = makeDistributedQueue(dqZNode);
assertNull(dq.peek());
- Future<String> future = executor.submit(() -> new String(dq.peek(true), UTF8));
+ Future<String> future = executor.submit(() -> new String(dq.peek(15000), UTF8));
try {
future.get(1000, TimeUnit.MILLISECONDS);
fail("TimeoutException expected");
[36/37] lucene-solr:jira/http2: LUCENE-8595: Fix interleaved DV
update and reset
Posted by da...@apache.org.
LUCENE-8595: Fix interleaved DV update and reset
This change fixes a bug where interleaved update and reset value
to the same doc in the same updates package looses an update
if the reset comes before the update as well as loosing the reset
if the update comes frist.
Co-authored-by: Adrien Grand <jp...@gmail.com>
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/f0db05b3
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/f0db05b3
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/f0db05b3
Branch: refs/heads/jira/http2
Commit: f0db05b37ec5bda5edd35fcb0fb94c4b4a0d9089
Parents: aaa64d7
Author: Simon Willnauer <si...@apache.org>
Authored: Thu Dec 6 21:27:13 2018 +0100
Committer: Simon Willnauer <si...@apache.org>
Committed: Fri Dec 7 08:24:52 2018 +0100
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 ++
.../lucene/index/DocValuesFieldUpdates.java | 10 +++-
.../lucene/index/TestDocValuesFieldUpdates.java | 63 ++++++++++++++++++++
3 files changed, 74 insertions(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f0db05b3/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 51b831d..14b4961 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -312,6 +312,10 @@ Bug fixes
* LUCENE-8586: Intervals.or() could get stuck in an infinite loop on certain indexes
(Alan Woodward)
+* LUCENE-8595: Fix interleaved DV update and reset. Interleaved update and reset value
+ to the same doc in the same updates package looses an update if the reset comes before
+ the update as well as loosing the reset if the update comes frist. (Simon Willnauer, Adrien Grant)
+
New Features
* LUCENE-8496: Selective indexing - modify BKDReader/BKDWriter to allow users
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f0db05b3/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java b/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java
index 9bf9179..7c2c5b1 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java
@@ -298,7 +298,7 @@ abstract class DocValuesFieldUpdates implements Accountable {
// increasing docID order:
// NOTE: we can have ties here, when the same docID was updated in the same segment, in which case we rely on sort being
// stable and preserving original order so the last update to that docID wins
- return Long.compare(docs.get(i), docs.get(j));
+ return Long.compare(docs.get(i)>>>1, docs.get(j)>>>1);
}
}.sort(0, size);
}
@@ -392,9 +392,13 @@ abstract class DocValuesFieldUpdates implements Accountable {
}
long longDoc = docs.get(idx);
++idx;
- while (idx < size && docs.get(idx) == longDoc) {
+ for (; idx < size; idx++) {
// scan forward to last update to this doc
- ++idx;
+ final long nextLongDoc = docs.get(idx);
+ if ((longDoc >>> 1) != (nextLongDoc >>> 1)) {
+ break;
+ }
+ longDoc = nextLongDoc;
}
hasValue = (longDoc & HAS_VALUE_MASK) > 0;
if (hasValue) {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f0db05b3/lucene/core/src/test/org/apache/lucene/index/TestDocValuesFieldUpdates.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocValuesFieldUpdates.java b/lucene/core/src/test/org/apache/lucene/index/TestDocValuesFieldUpdates.java
index 2066dcd..6c60df3 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDocValuesFieldUpdates.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocValuesFieldUpdates.java
@@ -69,4 +69,67 @@ public class TestDocValuesFieldUpdates extends LuceneTestCase {
assertEquals(24, iterator.longValue());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, iterator.nextDoc());
}
+
+ public void testUpdateAndResetSameDoc() {
+ NumericDocValuesFieldUpdates updates = new NumericDocValuesFieldUpdates(0, "test", 2);
+ updates.add(0, 1);
+ updates.reset(0);
+ updates.finish();
+ NumericDocValuesFieldUpdates.Iterator iterator = updates.iterator();
+ assertEquals(0, iterator.nextDoc());
+ assertFalse(iterator.hasValue());
+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, iterator.nextDoc());
+ }
+
+ public void testUpdateAndResetUpdateSameDoc() {
+ NumericDocValuesFieldUpdates updates = new NumericDocValuesFieldUpdates(0, "test", 3);
+ updates.add(0, 1);
+ updates.add(0);
+ updates.add(0, 2);
+ updates.finish();
+ NumericDocValuesFieldUpdates.Iterator iterator = updates.iterator();
+ assertEquals(0, iterator.nextDoc());
+ assertTrue(iterator.hasValue());
+ assertEquals(2, iterator.longValue());
+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, iterator.nextDoc());
+ }
+
+ public void testUpdatesAndResetRandom() {
+ NumericDocValuesFieldUpdates updates = new NumericDocValuesFieldUpdates(0, "test", 10);
+ int numUpdates = 10 + random().nextInt(100);
+ Integer[] values = new Integer[5];
+ for (int i = 0; i < 5; i++) {
+ values[i] = random().nextBoolean() ? null : random().nextInt(100);
+ if (values[i] == null) {
+ updates.reset(i);
+ } else {
+ updates.add(i, values[i]);
+ }
+ }
+ for (int i = 0; i < numUpdates; i++) {
+ int docId = random().nextInt(5);
+ values[docId] = random().nextBoolean() ? null : random().nextInt(100);
+ if (values[docId] == null) {
+ updates.reset(docId);
+ } else {
+ updates.add(docId, values[docId]);
+ }
+ }
+
+ updates.finish();
+ NumericDocValuesFieldUpdates.Iterator iterator = updates.iterator();
+ int idx = 0;
+ while (iterator.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
+ assertEquals(idx, iterator.docID());
+ if (values[idx] == null) {
+ assertFalse(iterator.hasValue());
+ } else {
+ assertTrue(iterator.hasValue());
+ assertEquals(values[idx].longValue(), iterator.longValue());
+ }
+ idx++;
+ }
+
+
+ }
}
[18/37] lucene-solr:jira/http2: Pre-commit fixes for LUCENE-8374
(JavaDoc + arguments)
Posted by da...@apache.org.
Pre-commit fixes for LUCENE-8374 (JavaDoc + arguments)
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/6c111611
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/6c111611
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/6c111611
Branch: refs/heads/jira/http2
Commit: 6c111611118ceda0837f25a27e5b4549f2693457
Parents: 59919b4
Author: Toke Eskildsen <to...@apache.org>
Authored: Tue Dec 4 10:05:09 2018 +0100
Committer: Toke Eskildsen <to...@apache.org>
Committed: Tue Dec 4 10:05:09 2018 +0100
----------------------------------------------------------------------
.../lucene/codecs/lucene70/IndexedDISICache.java | 10 +++++++++-
.../codecs/lucene70/IndexedDISICacheFactory.java | 19 ++++++++++++++++++-
.../lucene/codecs/lucene70/LongCompressor.java | 7 ++++++-
3 files changed, 33 insertions(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6c111611/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
index fdf93cf..80867a3 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
@@ -118,7 +118,9 @@ public class IndexedDISICache implements Accountable {
this.name = "";
}
- // Used to represent no caching.
+ /**
+ * Shared between all structures that are too small to meaningfully use jump-tables.
+ */
public static final IndexedDISICache EMPTY = new IndexedDISICache();
/**
@@ -156,6 +158,10 @@ public class IndexedDISICache implements Accountable {
return target >> RANK_BLOCK_BITS << RANK_BLOCK_BITS;
}
+ /**
+ * Offsets stated the block starts.
+ * @return true if the cache has offsets.
+ */
public boolean hasOffsets() {
return blockCache != null;
}
@@ -299,6 +305,7 @@ public class IndexedDISICache implements Accountable {
}
/**
+ * Creation stats intended for human inspection.
* @return Human readable details from the creation of the cache instance.
*/
public String getCreationStats() {
@@ -306,6 +313,7 @@ public class IndexedDISICache implements Accountable {
}
/**
+ * Cache name, as stated in the constructor.
* @return Human-readable name for the cache instance.
*/
public String getName() {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6c111611/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
index 610529a..f177210 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
@@ -48,6 +48,12 @@ public class IndexedDISICacheFactory implements Accountable {
private final Map<String, VaryingBPVJumpTable> vBPVPool = new HashMap<>();
/**
+ * Creates a {@link IndexedDISICache} and {@link VaryingBPVJumpTable} holding factory,
+ * intended for shared use within a single segment.
+ */
+ public IndexedDISICacheFactory() { }
+
+ /**
* Create a cached {@link IndexedDISI} instance.
* @param data persistent data containing the DISI-structure.
* @param cost cost as defined for IndexedDISI.
@@ -146,13 +152,24 @@ public class IndexedDISICacheFactory implements Accountable {
return cache;
}
- // Statistics
+ /**
+ * Cache statistics intended for external inspection.
+ * @return the number of total blocks where jumps are accelerated by jump-tables.
+ */
public long getDISIBlocksWithOffsetsCount() {
return disiPool.values().stream().filter(IndexedDISICache::hasOffsets).count();
}
+ /**
+ * Cache statistics intended for external inspection.
+ * @return the total number of DENSE blocks where index-counts are accelerated by rank.
+ */
public long getDISIBlocksWithRankCount() {
return disiPool.values().stream().filter(IndexedDISICache::hasRank).count();
}
+ /**
+ * Cache statistics intended for external inspection.
+ * @return the number of numeric blocks where jumps are accelerated by jump-tables
+ */
public long getVaryingBPVCount() {
return vBPVPool.size();
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6c111611/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java
index 1c030a7..7b12cc6 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java
@@ -48,6 +48,11 @@ public class LongCompressor {
private static final double DEFAULT_MIN_ZERO_VALUES_FRACTION_FOR_SPARSE = 0.2; // 20% (just guessing of a value here)
/**
+ * LongCompressor exclusively uses static methods and is never instantiated.
+ */
+ private LongCompressor() { }
+
+ /**
* Create a compact version of the given values.
* @param values PackedInts with no special constraints.
* @return a compact version of the given values or the given values if compression did not improve on heap overhead.
@@ -63,7 +68,7 @@ public class LongCompressor {
* @return a compact version of the given values or the given values if compression did not improve on heap overhead.
*/
public static PackedInts.Reader compress(PackedInts.Reader values, int length) {
- return compress(values, values.size(), true);
+ return compress(values, length, true);
}
/**
[26/37] lucene-solr:jira/http2: Add 'prelim_sort' helper to SolrJ's
TermsFacetMap
Posted by da...@apache.org.
Add 'prelim_sort' helper to SolrJ's TermsFacetMap
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/a5fb6f8a
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/a5fb6f8a
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/a5fb6f8a
Branch: refs/heads/jira/http2
Commit: a5fb6f8adc6a0d65b11c4738c5bbf751fc01cffe
Parents: 868e005
Author: Jason Gerlowski <ge...@apache.org>
Authored: Tue Dec 4 12:49:02 2018 -0500
Committer: Jason Gerlowski <ge...@apache.org>
Committed: Tue Dec 4 14:29:29 2018 -0500
----------------------------------------------------------------------
.../solrj/request/json/TermsFacetMap.java | 26 ++++++++++++++++++++
...JsonQueryRequestFacetingIntegrationTest.java | 23 +++++++++++++++++
2 files changed, 49 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a5fb6f8a/solr/solrj/src/java/org/apache/solr/client/solrj/request/json/TermsFacetMap.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/json/TermsFacetMap.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/json/TermsFacetMap.java
index e28f8a8..ea7c2fd 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/json/TermsFacetMap.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/json/TermsFacetMap.java
@@ -67,6 +67,12 @@ public class TermsFacetMap extends JsonFacetMap<TermsFacetMap> {
*
* Values can be based on 'count' (the number of results in each bucket), 'index' (the natural order of bucket values),
* or on any stat facet that occurs in the bucket. Defaults to "count desc" if not specified.
+ *
+ * By default, {@code sort} is calculated for all buckets generated by all shards. If {@code sort} is expensive a
+ * cheaper approximation can be provided using {@link #setPreliminarySort(String)} that will be run instead during
+ * bucket collection.
+ *
+ * @see TermsFacetMap#setPreliminarySort(String)
*/
public TermsFacetMap setSort(String sortString) {
if (sortString == null) {
@@ -77,6 +83,26 @@ public class TermsFacetMap extends JsonFacetMap<TermsFacetMap> {
}
/**
+ * Indicates an approximate sort calculation to be performed during initial bucket generation and collection.
+ *
+ * Values can be based on 'count' (the number of results in each bucket), 'index' (the natural order of bucket values),
+ * or on any stat facet that occurs in the bucket. Defaults to "count desc" if not specified.
+ *
+ * When no {@code prelim_sort} is provided, {@code sort} is calculated on all buckets generated by all shards. If
+ * {@code sort} is expensive, {@code prelim_sort} can be used to provide a cheaper approximation calculation that is
+ * run instead on initial bucket collection. {@code sort} is still used when assembling the final list of buckets.
+ *
+ * @see TermsFacetMap#setSort(String)
+ */
+ public TermsFacetMap setPreliminarySort(String preliminarySort) {
+ if (preliminarySort == null) {
+ throw new IllegalArgumentException("Parameter 'preliminarySort' must be non-null");
+ }
+ put("prelim_sort", preliminarySort);
+ return this;
+ }
+
+ /**
* Indicates the number of additional buckets to request internally beyond those required by {@link #setLimit(int)}.
*
* Defaults to -1 if not specified, which triggers some heuristic guessing based on other settings.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/a5fb6f8a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.java
index 344fdd2..4852c76 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.java
@@ -93,6 +93,29 @@ public class JsonQueryRequestFacetingIntegrationTest extends SolrCloudTestCase {
}
@Test
+ public void testTermsFacetWithPrelimSort() throws Exception {
+ final TermsFacetMap categoriesFacetMap = new TermsFacetMap("cat")
+ .setPreliminarySort("count desc")
+ .setSort("index desc")
+ .setLimit(3);
+ final JsonQueryRequest request = new JsonQueryRequest()
+ .setQuery("*:*")
+ .withFacet("top_cats", categoriesFacetMap);
+
+ QueryResponse response = request.process(cluster.getSolrClient(), COLLECTION_NAME);
+
+ assertExpectedDocumentsFoundAndReturned(response, NUM_TECHPRODUCTS_DOCS, 10);
+ final NestableJsonFacet topLevelFacetData = response.getJsonFacetingResponse();
+ assertEquals(NUM_TECHPRODUCTS_DOCS, topLevelFacetData.getCount());
+ //The prelim_sort/sort combination should give us the 3 most popular categories in reverse-alpha order
+ assertHasFacetWithBucketValues(topLevelFacetData, "top_cats",
+ new FacetBucket("memory", NUM_MEMORY),
+ new FacetBucket("electronics", NUM_ELECTRONICS),
+ new FacetBucket("currency", NUM_CURRENCY));
+
+ }
+
+ @Test
public void testTermsFacetWithNumBucketsRequested() throws Exception {
final TermsFacetMap categoriesFacetMap = new TermsFacetMap("cat")
.includeTotalNumBuckets(true)
[33/37] lucene-solr:jira/http2: SOLR-13028: @AwaitsFix
AutoAddReplicasPlanActionTest#testSimple.
Posted by da...@apache.org.
SOLR-13028: @AwaitsFix AutoAddReplicasPlanActionTest#testSimple.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/46d79940
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/46d79940
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/46d79940
Branch: refs/heads/jira/http2
Commit: 46d79940459f7b884b3caa749eee639dcff8c6ad
Parents: b9a966e
Author: markrmiller <ma...@apache.org>
Authored: Thu Dec 6 08:56:03 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Thu Dec 6 08:56:03 2018 -0600
----------------------------------------------------------------------
.../solr/cloud/autoscaling/AutoAddReplicasPlanActionTest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/46d79940/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoAddReplicasPlanActionTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoAddReplicasPlanActionTest.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoAddReplicasPlanActionTest.java
index 1c6d4a8..593225f 100644
--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoAddReplicasPlanActionTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoAddReplicasPlanActionTest.java
@@ -77,7 +77,7 @@ public class AutoAddReplicasPlanActionTest extends SolrCloudTestCase{
}
@Test
- @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
+ @AwaitsFix(bugUrl="https://issues.apache.org/jira/browse/SOLR-13028")
public void testSimple() throws Exception {
JettySolrRunner jetty1 = cluster.getJettySolrRunner(0);
JettySolrRunner jetty2 = cluster.getJettySolrRunner(1);
[06/37] lucene-solr:jira/http2: SOLR-6117: Unify ReplicationHandler
error handling
Posted by da...@apache.org.
SOLR-6117: Unify ReplicationHandler error handling
Prior to this commit, ReplicationHandler had a few inconsistencies
in how it reported errors:
- Sometimes the 'status' field was used as an enum (e.g. 'success'
v. 'failure'. Elsewhere it is used to hold error messages.
- Sometimes an explicit 'message' field was used, but often not.
- Sometimes a stack trace was provided in place of an error message.
This commit tweaks the various error cases in ReplicationHandler to
report errors consistently. 'status' is always an enum-type value. A
'message' field is provided for all errors, with an optional 'exception'
field.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/c951578f
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/c951578f
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/c951578f
Branch: refs/heads/jira/http2
Commit: c951578fcabfd5520f425156b0fa35f35811554d
Parents: 16241f4
Author: Jason Gerlowski <ge...@apache.org>
Authored: Sun Dec 2 16:08:41 2018 -0500
Committer: Jason Gerlowski <ge...@apache.org>
Committed: Sun Dec 2 16:23:04 2018 -0500
----------------------------------------------------------------------
solr/CHANGES.txt | 4 +
.../apache/solr/handler/ReplicationHandler.java | 188 +++++++++++--------
.../test/org/apache/solr/MinimalSchemaTest.java | 3 +-
.../solr/handler/TestReplicationHandler.java | 91 ++++++---
4 files changed, 183 insertions(+), 103 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c951578f/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 22b6721..d5240be 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -80,6 +80,10 @@ Improvements
If you don't use nested documents then _root_ can be removed from the schema. (Dr Oleg Savrasov, Moshe Bla,
David Smiley, Mikhail Khludnev)
+* SOLR-6117: The response format has changed slightly for ReplicationHandler error-cases. All errors now have a non-200
+ 'status' field, a 'message' field giving more details on the error, and an optional 'exception' field. (Shalin Mangar,
+ Jason Gerlowski)
+
Optimizations
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c951578f/solr/core/src/java/org/apache/solr/handler/ReplicationHandler.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/ReplicationHandler.java b/solr/core/src/java/org/apache/solr/handler/ReplicationHandler.java
index 241b6cd..3dc53bf 100644
--- a/solr/core/src/java/org/apache/solr/handler/ReplicationHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/ReplicationHandler.java
@@ -240,12 +240,8 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
rsp.setHttpCaching(false);
final SolrParams solrParams = req.getParams();
- String command = solrParams.get(COMMAND);
- if (command == null) {
- rsp.add(STATUS, OK_STATUS);
- rsp.add("message", "No command");
- return;
- }
+ String command = solrParams.required().get(COMMAND);
+
// This command does not give the current index version of the master
// It gives the current 'replicateable' index version
if (command.equals(CMD_INDEX_VERSION)) {
@@ -267,11 +263,13 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
core.getDeletionPolicy().setReserveDuration(commitPoint.getGeneration(), reserveCommitDuration);
rsp.add(CMD_INDEX_VERSION, IndexDeletionPolicyWrapper.getCommitTimestamp(commitPoint));
rsp.add(GENERATION, commitPoint.getGeneration());
+ rsp.add(STATUS, OK_STATUS);
} else {
// This happens when replication is not configured to happen after startup and no commit/optimize
// has happened yet.
rsp.add(CMD_INDEX_VERSION, 0L);
rsp.add(GENERATION, 0L);
+ rsp.add(STATUS, OK_STATUS);
}
} else if (command.equals(CMD_GET_FILE)) {
getFileStream(solrParams, rsp);
@@ -279,57 +277,28 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
getFileList(solrParams, rsp);
} else if (command.equalsIgnoreCase(CMD_BACKUP)) {
doSnapShoot(new ModifiableSolrParams(solrParams), rsp, req);
- rsp.add(STATUS, OK_STATUS);
} else if (command.equalsIgnoreCase(CMD_RESTORE)) {
restore(new ModifiableSolrParams(solrParams), rsp, req);
- rsp.add(STATUS, OK_STATUS);
} else if (command.equalsIgnoreCase(CMD_RESTORE_STATUS)) {
- rsp.add(CMD_RESTORE_STATUS, getRestoreStatus());
+ populateRestoreStatus(rsp);
} else if (command.equalsIgnoreCase(CMD_DELETE_BACKUP)) {
- deleteSnapshot(new ModifiableSolrParams(solrParams));
- rsp.add(STATUS, OK_STATUS);
+ deleteSnapshot(new ModifiableSolrParams(solrParams), rsp);
} else if (command.equalsIgnoreCase(CMD_FETCH_INDEX)) {
- String masterUrl = solrParams.get(MASTER_URL);
- if (!isSlave && masterUrl == null) {
- rsp.add(STATUS,ERR_STATUS);
- rsp.add("message","No slave configured or no 'masterUrl' Specified");
- return;
- }
- final SolrParams paramsCopy = new ModifiableSolrParams(solrParams);
- Thread fetchThread = new Thread(() -> doFetch(paramsCopy, false), "explicit-fetchindex-cmd") ;
- fetchThread.setDaemon(false);
- fetchThread.start();
- if (solrParams.getBool(WAIT, false)) {
- fetchThread.join();
- }
- rsp.add(STATUS, OK_STATUS);
+ fetchIndex(solrParams, rsp);
} else if (command.equalsIgnoreCase(CMD_DISABLE_POLL)) {
- if (pollingIndexFetcher != null){
- disablePoll();
- rsp.add(STATUS, OK_STATUS);
- } else {
- rsp.add(STATUS, ERR_STATUS);
- rsp.add("message","No slave configured");
- }
+ disablePoll(rsp);
} else if (command.equalsIgnoreCase(CMD_ENABLE_POLL)) {
- if (pollingIndexFetcher != null){
- enablePoll();
- rsp.add(STATUS, OK_STATUS);
- }else {
- rsp.add(STATUS,ERR_STATUS);
- rsp.add("message","No slave configured");
- }
+ enablePoll(rsp);
} else if (command.equalsIgnoreCase(CMD_ABORT_FETCH)) {
- if (abortFetch()){
+ if (abortFetch()) {
rsp.add(STATUS, OK_STATUS);
} else {
- rsp.add(STATUS,ERR_STATUS);
- rsp.add("message","No slave configured");
+ reportErrorOnResponse(rsp, "No slave configured", null);
}
} else if (command.equals(CMD_SHOW_COMMITS)) {
- rsp.add(CMD_SHOW_COMMITS, getCommits());
+ populateCommitInfo(rsp);
} else if (command.equals(CMD_DETAILS)) {
- rsp.add(CMD_DETAILS, getReplicationDetails(solrParams.getBool("slave", true)));
+ getReplicationDetails(rsp, solrParams.getBool("slave", true));
} else if (CMD_ENABLE_REPL.equalsIgnoreCase(command)) {
replicationEnabled.set(true);
rsp.add(STATUS, OK_STATUS);
@@ -339,6 +308,14 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
}
}
+ private void reportErrorOnResponse(SolrQueryResponse response, String message, Exception e) {
+ response.add(STATUS, ERR_STATUS);
+ response.add(MESSAGE, message);
+ if (e != null) {
+ response.add(EXCEPTION, e);
+ }
+ }
+
public boolean abortFetch() {
IndexFetcher fetcher = currentIndexFetcher;
if (fetcher != null){
@@ -349,15 +326,41 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
}
}
- private void deleteSnapshot(ModifiableSolrParams params) {
- String name = params.get(NAME);
- if(name == null) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Missing mandatory param: name");
- }
+ private void deleteSnapshot(ModifiableSolrParams params, SolrQueryResponse rsp) {
+ String name = params.required().get(NAME);
SnapShooter snapShooter = new SnapShooter(core, params.get(CoreAdminParams.BACKUP_LOCATION), params.get(NAME));
snapShooter.validateDeleteSnapshot();
snapShooter.deleteSnapAsync(this);
+ rsp.add(STATUS, OK_STATUS);
+ }
+
+ private void fetchIndex(SolrParams solrParams, SolrQueryResponse rsp) throws InterruptedException {
+ String masterUrl = solrParams.get(MASTER_URL);
+ if (!isSlave && masterUrl == null) {
+ reportErrorOnResponse(rsp, "No slave configured or no 'masterUrl' specified", null);
+ return;
+ }
+ final SolrParams paramsCopy = new ModifiableSolrParams(solrParams);
+ final IndexFetchResult[] results = new IndexFetchResult[1];
+ Thread fetchThread = new Thread(() -> {
+ IndexFetchResult result = doFetch(paramsCopy, false);
+ results[0] = result;
+ }, "explicit-fetchindex-cmd") ;
+ fetchThread.setDaemon(false);
+ fetchThread.start();
+ if (solrParams.getBool(WAIT, false)) {
+ fetchThread.join();
+ if (results[0] == null) {
+ reportErrorOnResponse(rsp, "Unable to determine result of synchronous index fetch", null);
+ } else if (results[0].getSuccessful()) {
+ rsp.add(STATUS, OK_STATUS);
+ } else {
+ reportErrorOnResponse(rsp, results[0].getMessage(), null);
+ }
+ } else {
+ rsp.add(STATUS, OK_STATUS);
+ }
}
private List<NamedList<Object>> getCommits() {
@@ -496,6 +499,7 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
MDC.put("RestoreCore.backupName", name);
restoreFuture = restoreExecutor.submit(restoreCore);
currentRestoreName = name;
+ rsp.add(STATUS, OK_STATUS);
} finally {
MDC.remove("RestoreCore.core");
MDC.remove("RestoreCore.backupLocation");
@@ -503,31 +507,42 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
}
}
- private NamedList<Object> getRestoreStatus() {
- NamedList<Object> status = new SimpleOrderedMap<>();
-
+ private void populateRestoreStatus(SolrQueryResponse rsp) {
+ NamedList<Object> restoreStatus = new SimpleOrderedMap<>();
if (restoreFuture == null) {
- status.add(STATUS, "No restore actions in progress");
- return status;
+ restoreStatus.add(STATUS, "No restore actions in progress");
+ rsp.add(CMD_RESTORE_STATUS, restoreStatus);
+ rsp.add(STATUS, OK_STATUS);
+ return;
}
- status.add("snapshotName", currentRestoreName);
+ restoreStatus.add("snapshotName", currentRestoreName);
if (restoreFuture.isDone()) {
try {
boolean success = restoreFuture.get();
if (success) {
- status.add(STATUS, SUCCESS);
+ restoreStatus.add(STATUS, SUCCESS);
} else {
- status.add(STATUS, FAILED);
+ restoreStatus.add(STATUS, FAILED);
}
} catch (Exception e) {
- status.add(STATUS, FAILED);
- status.add(EXCEPTION, e.getMessage());
+ restoreStatus.add(STATUS, FAILED);
+ restoreStatus.add(EXCEPTION, e.getMessage());
+ rsp.add(CMD_RESTORE_STATUS, restoreStatus);
+ reportErrorOnResponse(rsp, "Unable to read restorestatus", e);
+ return;
}
} else {
- status.add(STATUS, "In Progress");
+ restoreStatus.add(STATUS, "In Progress");
}
- return status;
+
+ rsp.add(CMD_RESTORE_STATUS, restoreStatus);
+ rsp.add(STATUS, OK_STATUS);
+ }
+
+ private void populateCommitInfo(SolrQueryResponse rsp) {
+ rsp.add(CMD_SHOW_COMMITS, getCommits());
+ rsp.add(STATUS, OK_STATUS);
}
private void doSnapShoot(SolrParams params, SolrQueryResponse rsp, SolrQueryRequest req) {
@@ -567,9 +582,12 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
SnapShooter snapShooter = new SnapShooter(repo, core, locationUri, params.get(NAME), commitName);
snapShooter.validateCreateSnapshot();
snapShooter.createSnapAsync(numberToKeep, (nl) -> snapShootDetails = nl);
+ rsp.add(STATUS, OK_STATUS);
+ } catch (SolrException e) {
+ throw e;
} catch (Exception e) {
- log.error("Exception during creating a snapshot", e);
- rsp.add("exception", e);
+ log.error("Exception while creating a snapshot", e);
+ reportErrorOnResponse(rsp, "Error encountered while creating a snapshot: " + e.getMessage(), e);
}
}
@@ -593,21 +611,17 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
} else {
rsp.add(FILE_STREAM, new DirectoryFileStream(solrParams));
}
+ rsp.add(STATUS, OK_STATUS);
}
@SuppressWarnings("unchecked")
private void getFileList(SolrParams solrParams, SolrQueryResponse rsp) {
- String v = solrParams.get(GENERATION);
- if (v == null) {
- rsp.add("status", "no index generation specified");
- return;
- }
+ String v = solrParams.required().get(GENERATION);
long gen = Long.parseLong(v);
IndexCommit commit = core.getDeletionPolicy().getCommitPoint(gen);
- //System.out.println("ask for files for gen:" + commit.getGeneration() + core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName());
if (commit == null) {
- rsp.add("status", "invalid index generation");
+ reportErrorOnResponse(rsp, "invalid index generation", null);
return;
}
@@ -629,6 +643,7 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
long checksum = CodecUtil.retrieveChecksum(in);
fileMeta.put(CHECKSUM, checksum);
} catch (Exception e) {
+ //TODO Should this trigger a larger error?
log.warn("Could not read checksum from index file: " + file, e);
}
}
@@ -647,15 +662,16 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
try {
fileMeta.put(CHECKSUM, CodecUtil.retrieveChecksum(in));
} catch (Exception e) {
+ //TODO Should this trigger a larger error?
log.warn("Could not read checksum from index file: " + infos.getSegmentsFileName(), e);
}
}
}
result.add(fileMeta);
} catch (IOException e) {
- rsp.add("status", "unable to get file names for given index generation");
- rsp.add(EXCEPTION, e);
log.error("Unable to get file names for indexCommit generation: " + gen, e);
+ reportErrorOnResponse(rsp, "unable to get file names for given index generation", e);
+ return;
} finally {
if (dir != null) {
try {
@@ -674,9 +690,9 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
rsp.add(TLOG_FILES, tlogfiles);
}
catch (IOException e) {
- rsp.add("status", "unable to get tlog file names for given index generation");
- rsp.add(EXCEPTION, e);
log.error("Unable to get tlog file names for indexCommit generation: " + gen, e);
+ reportErrorOnResponse(rsp, "unable to get tlog file names for given index generation", e);
+ return;
}
}
@@ -685,6 +701,7 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
log.debug("Adding config files to list: " + includeConfFiles);
//if configuration files need to be included get their details
rsp.add(CONF_FILES, getConfFileInfoFromCache(confFileNameAlias, confFileInfoCache));
+ rsp.add(STATUS, OK_STATUS);
}
/**
@@ -773,17 +790,23 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
}
}
- void disablePoll() {
- if (isSlave) {
+ private void disablePoll(SolrQueryResponse rsp) {
+ if (pollingIndexFetcher != null){
pollDisabled.set(true);
log.info("inside disable poll, value of pollDisabled = " + pollDisabled);
+ rsp.add(STATUS, OK_STATUS);
+ } else {
+ reportErrorOnResponse(rsp, "No slave configured", null);
}
}
- void enablePoll() {
- if (isSlave) {
+ private void enablePoll(SolrQueryResponse rsp) {
+ if (pollingIndexFetcher != null){
pollDisabled.set(false);
log.info("inside enable poll, value of pollDisabled = " + pollDisabled);
+ rsp.add(STATUS, OK_STATUS);
+ } else {
+ reportErrorOnResponse(rsp, "No slave configured", null);
}
}
@@ -886,10 +909,11 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
tag, true, "replicationEnabled", getCategory().toString(), scope);
}
+ //TODO Should a failure retrieving any piece of info mark the overall request as a failure? Is there a core set of values that are required to make a response here useful?
/**
* Used for showing statistics and progress information.
*/
- private NamedList<Object> getReplicationDetails(boolean showSlaveDetails) {
+ private NamedList<Object> getReplicationDetails(SolrQueryResponse rsp, boolean showSlaveDetails) {
NamedList<Object> details = new SimpleOrderedMap<>();
NamedList<Object> master = new SimpleOrderedMap<>();
NamedList<Object> slave = new SimpleOrderedMap<>();
@@ -1047,6 +1071,10 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
if (snapshotStats != null)
details.add(CMD_BACKUP, snapshotStats);
+ if (rsp.getValues().get(STATUS) == null) {
+ rsp.add(STATUS, OK_STATUS);
+ }
+ rsp.add(CMD_DETAILS, details);
return details;
}
@@ -1727,6 +1755,8 @@ public class ReplicationHandler extends RequestHandlerBase implements SolrCoreAw
public static final String STATUS = "status";
+ public static final String MESSAGE = "message";
+
public static final String COMMAND = "command";
public static final String CMD_DETAILS = "details";
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c951578f/solr/core/src/test/org/apache/solr/MinimalSchemaTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/MinimalSchemaTest.java b/solr/core/src/test/org/apache/solr/MinimalSchemaTest.java
index 4c06438..a5fc545 100644
--- a/solr/core/src/test/org/apache/solr/MinimalSchemaTest.java
+++ b/solr/core/src/test/org/apache/solr/MinimalSchemaTest.java
@@ -116,7 +116,8 @@ public class MinimalSchemaTest extends SolrTestCaseJ4 {
handler.startsWith("/stream") ||
handler.startsWith("/terms") ||
handler.startsWith("/analysis/")||
- handler.startsWith("/debug/")
+ handler.startsWith("/debug/") ||
+ handler.startsWith("/replication")
) {
continue;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c951578f/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 0cd2c04..e3a9377 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
@@ -49,6 +49,7 @@ import org.apache.solr.BaseDistributedSearchTestCase;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
import org.apache.solr.client.solrj.SolrClient;
+import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettyConfig;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
@@ -79,6 +80,8 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.junit.matchers.JUnitMatchers.containsString;
+
/**
* Test for ReplicationHandler
*
@@ -223,8 +226,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
QueryRequest req = new QueryRequest(params);
NamedList<Object> res = s.request(req);
-
- assertNotNull("null response from server", res);
+ assertReplicationResponseSucceeded(res);
@SuppressWarnings("unchecked") NamedList<Object> details
= (NamedList<Object>) res.get("details");
@@ -234,23 +236,6 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
return details;
}
-// private NamedList<Object> getCommits(SolrClient s) throws Exception {
-//
-//
-// ModifiableSolrParams params = new ModifiableSolrParams();
-// params.set("command","commits");
-// params.set("_trace","getCommits");
-// params.set("qt",ReplicationHandler.PATH);
-// QueryRequest req = new QueryRequest(params);
-//
-// NamedList<Object> res = s.request(req);
-//
-// assertNotNull("null response from server", res);
-//
-//
-// return res;
-// }
-
private NamedList<Object> getIndexVersion(SolrClient s) throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams();
@@ -260,9 +245,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
QueryRequest req = new QueryRequest(params);
NamedList<Object> res = s.request(req);
-
- assertNotNull("null response from server", res);
-
+ assertReplicationResponseSucceeded(res);
return res;
}
@@ -1083,12 +1066,13 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
params.set("command", "indexversion");
QueryRequest req = new QueryRequest(params);
NamedList<Object> resp = client1.request(req);
-
+ assertReplicationResponseSucceeded(resp);
Long version = (Long) resp.get("indexversion");
assertEquals(maxVersionClient1, version);
// check vs /replication?command=indexversion call
resp = client2.request(req);
+ assertReplicationResponseSucceeded(resp);
version = (Long) resp.get("indexversion");
assertEquals(maxVersionClient2, version);
}
@@ -1481,6 +1465,61 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
}
}
}
+
+ @Test
+ public void testFileListShouldReportErrorsWhenTheyOccur() throws Exception {
+ SolrQuery q = new SolrQuery();
+ q.add("qt", "/replication")
+ .add("wt", "json")
+ .add("command", "filelist")
+ .add("generation", "-1"); // A 'generation' value not matching any commit point should cause error.
+ QueryResponse response = slaveClient.query(q);
+ NamedList<Object> resp = response.getResponse();
+ assertNotNull(resp);
+ assertEquals("ERROR", resp.get("status"));
+ assertEquals("invalid index generation", resp.get("message"));
+ }
+
+ @Test
+ public void testFetchIndexShouldReportErrorsWhenTheyOccur() throws Exception {
+ int masterPort = masterJetty.getLocalPort();
+ masterJetty.stop();
+ SolrQuery q = new SolrQuery();
+ q.add("qt", "/replication")
+ .add("wt", "json")
+ .add("wait", "true")
+ .add("command", "fetchindex")
+ .add("masterUrl", buildUrl(masterPort));
+ QueryResponse response = slaveClient.query(q);
+ NamedList<Object> resp = response.getResponse();
+ assertNotNull(resp);
+ assertEquals("Fetch index with wait=true should have returned an error response", "ERROR", resp.get("status"));
+ }
+
+ @Test
+ public void testShouldReportErrorWhenRequiredCommandArgMissing() throws Exception {
+ SolrQuery q = new SolrQuery();
+ q.add("qt", "/replication")
+ .add("wt", "json");
+ SolrException thrown = expectThrows(SolrException.class, () -> {
+ slaveClient.query(q);
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, thrown.code());
+ assertThat(thrown.getMessage(), containsString("Missing required parameter: command"));
+ }
+
+ @Test
+ public void testShouldReportErrorWhenDeletingBackupButNameMissing() {
+ SolrQuery q = new SolrQuery();
+ q.add("qt", "/replication")
+ .add("wt", "json")
+ .add("command", "deletebackup");
+ SolrException thrown = expectThrows(SolrException.class, () -> {
+ slaveClient.query(q);
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, thrown.code());
+ assertThat(thrown.getMessage(), containsString("Missing required parameter: name"));
+ }
private class AddExtraDocs implements Runnable {
@@ -1583,6 +1622,12 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
return min; // compilation neccessity
}
}
+
+ private void assertReplicationResponseSucceeded(NamedList response) {
+ assertNotNull("null response from server", response);
+ assertNotNull("Expected replication response to have 'status' field", response.get("status"));
+ assertEquals("OK", response.get("status"));
+ }
private static String buildUrl(int port) {
return buildUrl(port, context);
[27/37] lucene-solr:jira/http2: SOLR-12422: Add section on
performance issues with Solr Cell; Overhaul and re-organize entire page
Posted by da...@apache.org.
SOLR-12422: Add section on performance issues with Solr Cell; Overhaul and re-organize entire page
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/c81822e1
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/c81822e1
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/c81822e1
Branch: refs/heads/jira/http2
Commit: c81822e15774c691a5772d4dfccae603b2247714
Parents: ad373ff
Author: Cassandra Targett <ct...@apache.org>
Authored: Tue Dec 4 15:06:08 2018 -0600
Committer: Cassandra Targett <ct...@apache.org>
Committed: Tue Dec 4 15:08:22 2018 -0600
----------------------------------------------------------------------
.../src/images/solr-cell/sample-pdf-query.png | Bin 0 -> 226063 bytes
...g-data-with-solr-cell-using-apache-tika.adoc | 310 +++++++++++++------
2 files changed, 223 insertions(+), 87 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c81822e1/solr/solr-ref-guide/src/images/solr-cell/sample-pdf-query.png
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/images/solr-cell/sample-pdf-query.png b/solr/solr-ref-guide/src/images/solr-cell/sample-pdf-query.png
new file mode 100644
index 0000000..f94b30e
Binary files /dev/null and b/solr/solr-ref-guide/src/images/solr-cell/sample-pdf-query.png differ
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c81822e1/solr/solr-ref-guide/src/uploading-data-with-solr-cell-using-apache-tika.adoc
----------------------------------------------------------------------
diff --git a/solr/solr-ref-guide/src/uploading-data-with-solr-cell-using-apache-tika.adoc b/solr/solr-ref-guide/src/uploading-data-with-solr-cell-using-apache-tika.adoc
index d78ab6e..9b3da6c 100644
--- a/solr/solr-ref-guide/src/uploading-data-with-solr-cell-using-apache-tika.adoc
+++ b/solr/solr-ref-guide/src/uploading-data-with-solr-cell-using-apache-tika.adoc
@@ -1,4 +1,5 @@
= Uploading Data with Solr Cell using Apache Tika
+:page-tocclass: right
// 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
@@ -16,11 +17,15 @@
// specific language governing permissions and limitations
// under the License.
-Solr uses code from the http://lucene.apache.org/tika/[Apache Tika] project to provide a framework for incorporating many different file-format parsers such as http://incubator.apache.org/pdfbox/[Apache PDFBox] and http://poi.apache.org/index.html[Apache POI] into Solr itself. Working with this framework, Solr's `ExtractingRequestHandler` can use Tika to support uploading binary files, including files in popular formats such as Word and PDF, for data extraction and indexing.
+If the documents you need to index are in a binary format, such as Word, Excel, PDFs, etc., Solr includes a request handler which uses http://lucene.apache.org/tika/[Apache Tika] to extract text for indexing to Solr.
-When this framework was under development, it was called the Solr Content Extraction Library or CEL; from that abbreviation came this framework's name: Solr Cell.
+Solr uses code from the Tika project to provide a framework for incorporating many different file-format parsers such as http://incubator.apache.org/pdfbox/[Apache PDFBox] and http://poi.apache.org/index.html[Apache POI] into Solr itself.
-If you want to supply your own `ContentHandler` for Solr to use, you can extend the `ExtractingRequestHandler` and override the `createFactory()` method. This factory is responsible for constructing the `SolrContentHandler` that interacts with Tika, and allows literals to override Tika-parsed values. Set the parameter `literalsOverride`, which normally defaults to `true`, to `false` to append Tika-parsed values to literal values.
+Working with this framework, Solr's `ExtractingRequestHandler` uses Tika internally to support uploading binary files
+for data extraction and indexing. Downloading Tika is not required to use Solr Cell.
+
+When this framework was under development, it was called the Solr _Content Extraction Library_, or _CEL_; from that abbreviation came this framework's name: Solr Cell. The names Solr Cell and `ExtractingRequestHandler` are used
+interchangeably for this feature.
== Key Solr Cell Concepts
@@ -33,7 +38,7 @@ See http://tika.apache.org/{ivy-tika-version}/formats.html for the file types su
Solr responds to Tika's SAX events to create one or more text fields from the content.
Tika exposes document metadata as well (apart from the XHTML).
* Tika produces metadata such as Title, Subject, and Author according to specifications such as the DublinCore.
-The metadata available is highly dependent on the file types and what they in turn contain.
+The metadata available is highly dependent on the file types and what they in turn contain. Some of the general metadata created is described in the section <<Metadata Created by Tika>> below.
Solr Cell supplies some metadata of its own too.
* Solr Cell concatenates text from the internal XHTML into a `content` field.
You can configure which elements should be included/ignored, and which should map to another field.
@@ -42,55 +47,84 @@ By default it maps to the same name but several parameters control how this is d
* When Solr Cell finishes creating the internal `SolrInputDocument`, the rest of the Lucene/Solr indexing stack takes over.
The next step after any update handler is the <<update-request-processors.adoc#update-request-processors,Update Request Processor>> chain.
-[NOTE]
-====
-While Apache Tika is quite powerful, it is not perfect and fails on some files. PDF files are particularly problematic, mostly due to the PDF format itself. In case of a failure processing any file, the `ExtractingRequestHandler` does not have a secondary mechanism to try to extract some text from the file; it will throw an exception and fail.
-====
+Solr Cell is a contrib, which means it's not automatically included with Solr but must be configured.
+The example configsets have Solr Cell configured, but if you are not using those,
+you will want to pay attention to the section <<Configuring the ExtractingRequestHandler in solrconfig.xml>> below.
+
+=== Solr Cell Performance Implications
+
+Rich document formats are frequently not well documented, and even in cases where there is documentation for the
+format, not everyone who creates documents will follow the specifications faithfully.
+
+This creates a situation where Tika may encounter something that it is simply not able to handle gracefully,
+despite taking great pains to support as many formats as possible.
+PDF files are particularly problematic, mostly due to the PDF format itself.
-== Trying out Tika
+In case of a failure processing any file, the `ExtractingRequestHandler` does not have a secondary mechanism to try to extract some text from the file; it will throw an exception and fail.
+
+If any exceptions cause the `ExtractingRequestHandler` and/or Tika to crash, Solr as a whole will also crash because
+the request handler is running in the same JVM that Solr uses for other operations.
+
+Indexing can also consume all available Solr resources, particularly with large PDFs, presentations, or other files
+that have a lot of rich media embedded in them.
+
+For these reasons, Solr Cell is not recommended for use in a production system.
+
+It is a best practice to use Solr Cell as a proof-of-concept tool during development and then run Tika as an external
+process that sends the extracted documents to Solr (via <<using-solrj.adoc#using-solrj,SolrJ>>) for indexing.
+This way, any extraction failures that occur are isolated from Solr itself and can be handled gracefully.
+
+For a few examples of how this could be done, see this blog post by Erick Erickson, https://lucidworks.com/2012/02/14/indexing-with-solrj/[Indexing with SolrJ].
+
+== Trying out Solr Cell
You can try out the Tika framework using the `schemaless` example included in Solr.
-This will simply create a core/collection "gettingstarted" with the default configSet.
-Start the example:
+This command will simply start Solr and create a core/collection named "gettingstarted" with the `_default` configset.
[source,bash]
----
bin/solr -e schemaless
----
-You can now use curl to send a sample PDF file via HTTP POST:
+Once Solr is started, you can use curl to send a sample PDF included with Solr via HTTP POST:
[source,bash]
----
curl 'http://localhost:8983/solr/gettingstarted/update/extract?literal.id=doc1&uprefix=ignored_&commit=true' -F "myfile=@example/exampledocs/solr-word.pdf"
----
-The URL above calls the Extracting Request Handler, uploads the file `solr-word.pdf` and assigns it the unique ID `doc1`. Here's a closer look at the components of this command:
+The URL above calls the `ExtractingRequestHandler`, uploads the file `solr-word.pdf`, and assigns it the unique ID `doc1`. Here's a closer look at the components of this command:
* The `literal.id=doc1` parameter provides a unique ID for the document being indexed.
-There are alternatives to this like mapping a metadata field to the ID, generating a new UUID, and generating an ID from a signature (hash) of the content.
+Without this, the ID would be set to the absolute path to the file.
++
+There are alternatives to this, such as mapping a metadata field to the ID, generating a new UUID, or generating an ID from a signature (hash) of the content.
* The `commit=true parameter` causes Solr to perform a commit after indexing the document, making it immediately searchable. For optimum performance when loading many documents, don't call the commit command until you are done.
-* The `-F` flag instructs curl to POST data using the Content-Type `multipart/form-data` and supports the uploading of binary files. The @ symbol instructs curl to upload the attached file.
+* The `-F` flag instructs curl to POST data using the Content-Type `multipart/form-data` and supports the uploading of binary files. The `@` symbol instructs curl to upload the attached file.
-* The argument `myfile=@tutorial.html` needs a valid path, which can be absolute or relative.
+* The argument `myfile=@example/exampledocs/solr-word.pdf` uploads the sample file.Note this includes the path, so if you upload a different file, always be sure to include either the relative or absolute path to the file.
-You can also use `bin/post` to send a PDF file into Solr (without the params, the post tool would set `literal.id` to the absolute path to the file):
+You can also use `bin/post` to do the same thing:
[source,bash]
----
bin/post -c gettingstarted example/exampledocs/solr-word.pdf -params "literal.id=doc1"
----
-Now you should be able to execute a query and find that document. You can make a request like `\http://localhost:8983/solr/gettingstarted/select?q=pdf`.
+Now you can execute a query and find that document with a request like `\http://localhost:8983/solr/gettingstarted/select?q=pdf`. The document will look something like this:
+
+image:images/solr-cell/sample-pdf-query.png[float="right",width=50%,pdfwidth=60%]
You may notice there are many metadata fields associated with this document.
Solr's configuration is by default in "schemaless" (data driven) mode, and thus all metadata fields extracted get their own field.
+
You might instead want to ignore them generally except for a few you specify.
To do that, use the `uprefix` parameter to map unknown (to the schema) metadata field names to a schema field name that is effectively ignored.
The dynamic field `ignored_*` is good for this purpose.
+
For the fields you do want to map, explicitly set them using `fmap.IN=OUT` and/or ensure the field is defined in the schema.
Here's an example:
@@ -101,83 +135,149 @@ bin/post -c gettingstarted example/exampledocs/solr-word.pdf -params "literal.id
[NOTE]
====
-This won't have the intended effect if you run it at this point in the sequence of this tutorial.
-Previously we added the document without these parameters; schemaless mode automatically added all fields at that time.
-"uprefix" only applies to fields that are _undefined_ (hence the 'u' in "uprefix"), so these won't be prefixed now.
-However you will see the new "last_modified_dt" field.
-The easiest way to try this properly is to start over by deleting `example/schemaless/` (while Solr is stopped).
+The above example won't work as expected if you run it after you've already indexed the document one or more times.
+
+Previously we added the document without these parameters so all fields were added to the index at that time.
+The `uprefix` parameter only applies to fields that are _undefined_, so these won't be prefixed if the document is reindexed later.
+However, you would see the new `last_modified_dt` field.
+
+The easiest way to try this parameter is to start over with a fresh collection.
====
-== Solr Cell Input Parameters
+== ExtractingRequestHandler Parameters and Configuration
+
+=== Solr Cell Parameters
-The table below describes the parameters accepted by the Extracting Request Handler.
+The following parameters are accepted by the `ExtractingRequestHandler`.
+
+These parameters can be set for each indexing request (as request parameters), or they can be set for all requests to
+the request handler generally by defining them in `solrconfig.xml`, as described in <<Configuring the ExtractingRequestHandler in solrconfig.xml>>.
`capture`::
-Captures XHTML elements with the specified name for a supplementary addition to the Solr document. This parameter can be useful for copying chunks of the XHTML into a separate field. For instance, it could be used to grab paragraphs (`<p>`) and index them into a separate field. Note that content is still also captured into the overall "content" field.
+Captures XHTML elements with the specified name for a supplementary addition to the Solr document. This parameter can be useful for copying chunks of the XHTML into a separate field. For instance, it could be used to grab paragraphs (`<p>`) and index them into a separate field. Note that content is still also captured into the `content` field.
++
+Example: `capture=p` (in a request) or `<str name="capture">p</str>` (in `solrconfig.xml`)
++
+Output: `"p": {"This is a paragraph from my document."}`
++
+This parameter can also be used with the `fmap._source_field_` parameter to map content from attributes to a new field.
`captureAttr`::
-Indexes attributes of the Tika XHTML elements into separate fields, named after the element. If set to true, for example, when extracting from HTML, Tika can return the href attributes in <a> tags as fields named "a". See the examples below.
+Indexes attributes of the Tika XHTML elements into separate fields, named after the element. If set to `true`, when extracting from HTML, Tika can return the href attributes in `<a>` tags as fields named "`a`".
++
+Example: `captureAttr=true`
++
+Output: `"div": {"classname1", "classname2"}`
`commitWithin`::
Add the document within the specified number of milliseconds.
++
+Example: `commitWithin=10000` (10 seconds)
`defaultField`::
-If the `uprefix` parameter (see below) is not specified and a field cannot be determined, the default field will be used.
+A default field to use if the `uprefix` parameter is not specified and a field cannot otherwise be determined.
++
+Example: `defaultField=\_text_`
`extractOnly`::
-Default is `false`. If `true`, returns the extracted content from Tika without indexing the document. This literally includes the extracted XHTML as a string in the response. When viewing manually, it may be useful to use a response format other than XML to aid in viewing the embedded XHTML tags. For an example, see http://wiki.apache.org/solr/TikaExtractOnlyExampleOutput.
+Default is `false`. If `true`, returns the extracted content from Tika without indexing the document. This returns the extracted XHTML as a string in the response. When viewing on a screen, it may be useful to set the `extractFormat` parameter for a response format other than XML to aid in viewing the embedded XHTML tags.
++
+Example: `extractOnly=true`
`extractFormat`::
-The default is `xml`, but the other option is `text`. Controls the serialization format of the extract content. The `xml` format is actually XHTML, the same format that results from passing the `-x` command to the Tika command line application, while the text format is like that produced by Tika's `-t` command. This parameter is valid only if `extractOnly` is set to true.
+The default is `xml`, but the other option is `text`. Controls the serialization format of the extract content. The `xml` format is actually XHTML, the same format that results from passing the `-x` command to the Tika command line application, while the text format is like that produced by Tika's `-t` command.
++
+This parameter is valid only if `extractOnly` is set to true.
++
+Example: `extractFormat=text`
++
+Output: For an example output (in XML), see http://wiki.apache.org/solr/TikaExtractOnlyExampleOutput
`fmap._source_field_`::
-Maps (moves) one field name to another. The `source_field` must be a field in incoming documents, and the value is the Solr field to map to. Example: `fmap.content=text` causes the data in the `content` field generated by Tika to be moved to the Solr's `text` field.
+Maps (moves) one field name to another. The `source_field` must be a field in incoming documents, and the value is the Solr field to map to.
++
+Example: `fmap.content=text` causes the data in the `content` field generated by Tika to be moved to the Solr's `text` field.
`ignoreTikaException`::
If `true`, exceptions found during processing will be skipped. Any metadata available, however, will be indexed.
++
+Example: `ignoreTikaException=true`
`literal._fieldname_`::
Populates a field with the name supplied with the specified value for each document. The data can be multivalued if the field is multivalued.
++
+Example: `literal.doc_status=published`
++
+Output: `"doc_status": "published"`
`literalsOverride`::
-If `true` (the default), literal field values will override other values with the same field name. If `false`, literal values defined with `literal._fieldname_` will be appended to data already in the fields extracted from Tika. If setting `literalsOverride` to `false`, the field must be multivalued.
+If `true` (the default), literal field values will override other values with the same field name.
++
+If `false`, literal values defined with `literal._fieldname_` will be appended to data already in the fields extracted
+from Tika. When setting `literalsOverride` to `false`, the field must be multivalued.
++
+Example: `literalsOverride=false`
`lowernames`::
-Values are `true` or `false`. If `true`, all field names will be mapped to lowercase with underscores, if needed. For example, "Content-Type" would be mapped to "content_type."
+If `true`, all field names will be mapped to lowercase with underscores, if needed.
++
+Example: `lowernames=true`
++
+Output: Assuming input of "Content-Type", the result in documents would be a field `content_type`
`multipartUploadLimitInKB`::
-Useful if uploading very large documents, this defines the KB size of documents to allow.
+Defines the size in kilobytes of documents to allow. The default is `2048` (2Mb).
+If you have very large documents, you should increase this or they will be rejected.
++
+Example: `multipartUploadLimitInKB=2048000`
+
+`parseContext.config`::
+If a Tika parser being used allows parameters, you can pass them to Tika by creating a parser configuration file and
+pointing Solr to it. See the section <<Parser-Specific Properties>> for more information about how to use this parameter.
++
+Example: `parseContext.config=pdf-config.xml`
`passwordsFile`::
-Defines a file path and name for a file of file name to password mappings.
+Defines a file path and name for a file of file name to password mappings. See the section
+<<Indexing Encrypted Documents>> for more information about using a password file.
++
+Example: `passwordsFile=/path/to/passwords.txt`
`resource.name`::
-Specifies the optional name of the file. Tika can use it as a hint for detecting a file's MIME type.
+Specifies the name of the file to index. This is optional, but Tika can use it as a hint for detecting a file's MIME type.
++
+Example: `resource.name=mydoc.doc`
`resource.password`::
-Defines a password to use for a password-protected PDF or OOXML file.
+Defines a password to use for a password-protected PDF or OOXML file. See the section <<Indexing Encrypted Documents>>
+for more information about using this parameter.
++
+Example: `resource.password=secret`
`tika.config`::
-Defines a file path and name to a customized Tika configuration file. This is only required if you have customized your Tika implementation.
+Defines a file path and name to a custom Tika configuration file. This is only required if you have customized your Tika implementation.
++
+Example: `tika.config=/path/to/tika.config`
`uprefix`::
-Prefixes all fields _that are undefined in the schema_ with the given prefix. This is very useful when combined with dynamic field definitions. Example: `uprefix=ignored_` would effectively ignore all unknown fields generated by Tika given the default schema contains `<dynamicField name="ignored_*" type="ignored"/>`
+Prefixes all fields _that are undefined in the schema_ with the given prefix. This is very useful when combined with dynamic field definitions.
++
+Example: `uprefix=ignored_` would add `ignored_` as a prefix to all unknown fields. In this case, you could additionally define a rule in the Schema to not index these fields:
++
+`<dynamicField name="ignored_*" type="ignored" />`
`xpath`::
-When extracting, only return Tika XHTML content that satisfies the given XPath expression. See http://tika.apache.org/{ivy-tika-version}/ for details on the format of Tika XHTML. See also http://wiki.apache.org/solr/TikaExtractOnlyExampleOutput.
-
-== Order of Operations
-
-Here is the order in which the Solr Cell framework, using the Extracting Request Handler and Tika, processes its input.
+When extracting, only return Tika XHTML content that satisfies the given XPath expression.
+See http://tika.apache.org/{ivy-tika-version}/ for details on the format of Tika XHTML, it varies with the format being parsed.
+Also see the section <<Defining XPath Expressions>> for an example.
-. Tika generates fields or passes them in as literals specified by `literal.<fieldname>=<value>`. If `literalsOverride=false`, literals will be appended as multi-value to the Tika-generated field.
-. If `lowernames=true`, Tika maps fields to lowercase.
-. Tika applies the mapping rules specified by `fmap.__source__=__target__` parameters.
-. If `uprefix` is specified, any unknown field names are prefixed with that value, else if `defaultField` is specified, any unknown fields are copied to the default field.
+=== Configuring the ExtractingRequestHandler in solrconfig.xml
-== Configuring the Solr ExtractingRequestHandler
+If you have started Solr with one of the supplied <<config-sets.adoc#config-sets,example configsets>>, you already have
+the `ExtractingRequestHandler` configured by default and you only need to customize it for your content.
-If you are not working with the supplied <<config-sets.adoc#config-sets,config sets>>, you must configure your own `solrconfig.xml` to know about the Jar's containing the `ExtractingRequestHandler` and its dependencies:
+If you are not working with an example configset, the jars required to use Solr Cell will not be loaded automatically.
+You will need to configure your `solrconfig.xml` to find the `ExtractingRequestHandler` and its dependencies:
[source,xml]
----
@@ -185,39 +285,55 @@ If you are not working with the supplied <<config-sets.adoc#config-sets,config s
<lib dir="${solr.install.dir:../../..}/dist/" regex="solr-cell-\d.*\.jar" />
----
-You can then configure the `ExtractingRequestHandler` in `solrconfig.xml`.
+You can then configure the `ExtractingRequestHandler` in `solrconfig.xml`. The following is the default
+configuration found in Solr's `_default` configset, which you can modify as needed:
[source,xml]
----
-<requestHandler name="/update/extract" class="org.apache.solr.handler.extraction.ExtractingRequestHandler">
+<requestHandler name="/update/extract"
+ startup="lazy"
+ class="solr.extraction.ExtractingRequestHandler" >
<lst name="defaults">
- <str name="fmap.Last-Modified">last_modified</str>
- <str name="uprefix">ignored_</str>
+ <str name="lowernames">true</str>
+ <str name="fmap.content">_text_</str>
</lst>
- <!--Optional. Specify a path to a tika configuration file. See the Tika docs for details.-->
- <str name="tika.config">/my/path/to/tika.config</str>
- <!-- Optional. Specify an external file containing parser-specific properties.
- This file is located in the same directory as solrconfig.xml by default.-->
- <str name="parseContext.config">parseContext.xml</str>
</requestHandler>
----
-In the defaults section, we are mapping Tika's Last-Modified Metadata attribute to a field named `last_modified`. We are also telling it to ignore undeclared fields. These are all overridden parameters.
-
-The `tika.config` entry points to a file containing a Tika configuration.
+In this setup, all field names are lower-cased (with the `lowernames` parameter), and Tika's `content` field is mapped to Solr's `__text__` field.
[TIP]
====
-You likely need to have <<update-request-processors.adoc#update-request-processors,Update Request Processors>> (URPs) that parse numbers and dates and do other manipulations on the metadata fields generated by Solr Cell.
-In Solr's default configuration, "schemaless" (data driven) mode is enabled, which does a variety of such processing already.
-_If you don't use this mode_, you can still selectively specify the desired URPs.
-An easy way to specify this is to configure the parameter `processor` (under `defaults`) to `uuid,remove-blank,field-name-mutating,parse-boolean,parse-long,parse-double,parse-date`.
-That suggested list was taken right from the `add-unknown-fields-to-the-schema` URP chain, excluding `add-schema-fields`.
+You may need to configure <<update-request-processors.adoc#update-request-processors,Update Request Processors>> (URPs)
+that parse numbers and dates and do other manipulations on the metadata fields generated by Solr Cell.
+
+In Solr's default configsets, <<schemaless-mode.adoc#schemaless-mode,"schemaless">> (aka data driven, or field guessing) mode is enabled, which does a variety of such processing already.
+
+If you instead explicitly define the fields for your schema, you can selectively specify the desired URPs.
+An easy way to specify this is to configure the parameter `processor` (under `defaults`) to `uuid,remove-blank,field-name-mutating,parse-boolean,parse-long,parse-double,parse-date`. For example:
+
+[source,xml]
+----
+<requestHandler name="/update/extract"
+ startup="lazy"
+ class="solr.extraction.ExtractingRequestHandler" >
+ <lst name="defaults">
+ <str name="lowernames">true</str>
+ <str name="fmap.content">_text_</str>
+ <str name="processor">uuid,remove-blank,field-name-mutating,parse-boolean,parse-long,parse-double,parse-date</processor>
+ </lst>
+</requestHandler>
+----
+
+The above suggested list was taken from the list of URPs that run as a part of schemaless mode and provide much of its functionality. However, one major part of the schemaless functionality is missing from the suggested list, `add-unknown-fields-to-the-schema`, which is the part that adds fields to the schema. So you can use the other URPs without worrying about unexpected field additions.
====
=== Parser-Specific Properties
-Parsers used by Tika may have specific properties to govern how data is extracted. For instance, when using the Tika library from a Java program, the PDFParserConfig class has a method `setSortByPosition(boolean)` that can extract vertically oriented text. To access that method via configuration with the ExtractingRequestHandler, one can add the `parseContext.config` property to the `solrconfig.xml` file (see above) and then set properties in Tika's PDFParserConfig as below. Consult the Tika Java API documentation for configuration parameters that can be set for any particular parsers that require this level of control.
+Parsers used by Tika may have specific properties to govern how data is extracted.
+These can be passed through Solr for special parsing situations.
+
+For instance, when using the Tika library from a Java program, the `PDFParserConfig` class has a method `setSortByPosition(boolean)` that can extract vertically oriented text. To access that method via configuration with the `ExtractingRequestHandler`, one can add the `parseContext.config` property to `solrconfig.xml` and then set properties in Tika's `PDFParserConfig` as in the example below.
[source,xml]
----
@@ -230,13 +346,9 @@ Parsers used by Tika may have specific properties to govern how data is extracte
</entries>
----
-=== Multi-Core Configuration
-
-For a multi-core configuration, you can specify `sharedLib='lib'` in the `<solr/>` section of `solr.xml` and place the necessary jar files there.
-
-For more information about Solr cores, see <<the-well-configured-solr-instance.adoc#the-well-configured-solr-instance,The Well-Configured Solr Instance>>.
+Consult the Tika Java API documentation for configuration parameters that can be set for any particular parsers that require this level of control.
-== Indexing Encrypted Documents with the ExtractingUpdateRequestHandler
+=== Indexing Encrypted Documents
The ExtractingRequestHandler will decrypt encrypted files and index their content if you supply a password in either `resource.password` on the request, or in a `passwordsFile` file.
@@ -250,19 +362,31 @@ myFileName = myPassword
.*\.pdf$ = myPdfPassword
----
-== Solr Cell Examples
+=== Multi-Core Configuration
+
+For a multi-core configuration, you can specify `sharedLib='lib'` in the `<solr/>` section of `solr.xml` and place the necessary jar files there.
+
+For more information about Solr cores, see <<the-well-configured-solr-instance.adoc#the-well-configured-solr-instance,The Well-Configured Solr Instance>>.
+
+=== Extending the ExtractingRequestHandler
+
+If you want to supply your own `ContentHandler` for Solr to use, you can extend the `ExtractingRequestHandler` and override the `createFactory()` method. This factory is responsible for constructing the `SolrContentHandler` that interacts with Tika, and allows literals to override Tika-parsed values. Set the parameter `literalsOverride`, which normally defaults to `true`, to `false` to append Tika-parsed values to literal values.
+
+== Solr Cell Internals
=== Metadata Created by Tika
As mentioned before, Tika produces metadata about the document. Metadata describes different aspects of a document, such as the author's name, the number of pages, the file size, and so on. The metadata produced depends on the type of document submitted. For instance, PDFs have different metadata than Word documents do.
-In addition to Tika's metadata, Solr adds the following metadata (defined in `ExtractingMetadataConstants`):
+=== Metadata Added by Solr
+
+In addition to the metadata added by Tika's parsers, Solr adds the following metadata:
`stream_name`::
The name of the Content Stream as uploaded to Solr. Depending on how the file is uploaded, this may or may not be set.
`stream_source_info`::
-Any source info about the stream. (See the section on Content Streams later in this section.)
+Any source info about the stream.
`stream_size`::
The size of the stream in bytes.
@@ -270,21 +394,30 @@ The size of the stream in bytes.
`stream_content_type`::
The content type of the stream, if available.
+IMPORTANT: It's recommended to use the `extractOnly` option before indexing to discover the values Solr will
+set for these metadata elements on your content.
-IMPORTANT: We recommend that you try using the `extractOnly` option to discover which values Solr is setting for these metadata elements.
+=== Order of Input Processing
-=== Examples of Uploads Using the Extracting Request Handler
+Here is the order in which the Solr Cell framework processes its input:
-==== Capture and Mapping
+. Tika generates fields or passes them in as literals specified by `literal.<fieldname>=<value>`. If `literalsOverride=false`, literals will be appended as multi-value to the Tika-generated field.
+. If `lowernames=true`, Tika maps fields to lowercase.
+. Tika applies the mapping rules specified by `fmap.__source__=__target__` parameters.
+. If `uprefix` is specified, any unknown field names are prefixed with that value, else if `defaultField` is specified, any unknown fields are copied to the default field.
-The command below captures `<div>` tags separately, and then maps all the instances of that field to a dynamic field named `foo_t`.
+== Solr Cell Examples
+
+=== Using capture and Mapping Fields
+
+The command below captures `<div>` tags separately (`capture=div`), and then maps all the instances of that field to a dynamic field named `foo_t` (`fmap.div=foo_t`).
[source,bash]
----
bin/post -c gettingstarted example/exampledocs/sample.html -params "literal.id=doc2&captureAttr=true&defaultField=_text_&fmap.div=foo_t&capture=div"
----
-==== Using Literals to Define Your Own Metadata
+=== Using Literals to Define Custom Metadata
To add in your own metadata, pass in the literal parameter along with the file:
@@ -293,7 +426,10 @@ To add in your own metadata, pass in the literal parameter along with the file:
bin/post -c gettingstarted -params "literal.id=doc4&captureAttr=true&defaultField=text&capture=div&fmap.div=foo_t&literal.blah_s=Bah" example/exampledocs/sample.html
----
-==== XPath Expressions
+The parameter `literal.blah_s=Bah` will insert a field `blah_s` into every document.
+Every instance of the text will be "Bah".
+
+=== Defining XPath Expressions
The example below passes in an XPath expression to restrict the XHTML returned by Tika:
@@ -302,7 +438,7 @@ The example below passes in an XPath expression to restrict the XHTML returned b
bin/post -c gettingstarted -params "literal.id=doc5&captureAttr=true&defaultField=text&capture=div&fmap.div=foo_t&xpath=/xhtml:html/xhtml:body/xhtml:div//node()" example/exampledocs/sample.html
----
-=== Extracting Data without Indexing It
+=== Extracting Data without Indexing
Solr allows you to extract data without indexing. You might want to do this if you're using Solr solely as an extraction server or if you're interested in testing Solr extraction.
@@ -320,7 +456,7 @@ The output includes XML generated by Tika (and further escaped by Solr's XML) us
bin/post -c gettingstarted -params "extractOnly=true&wt=ruby&indent=true" -out yes example/exampledocs/sample.html
----
-== Sending Documents to Solr with a POST
+=== Using Solr Cell with a POST Request
The example below streams the file as the body of the POST, which does not, then, provide information to Solr about the name of the file.
@@ -329,9 +465,9 @@ The example below streams the file as the body of the POST, which does not, then
curl "http://localhost:8983/solr/gettingstarted/update/extract?literal.id=doc6&defaultField=text&commit=true" --data-binary @example/exampledocs/sample.html -H 'Content-type:text/html'
----
-== Sending Documents to Solr with SolrJ
+== Using Solr Cell with SolrJ
-SolrJ is a Java client that you can use to add documents to the index, update the index, or query the index. You'll find more information on SolrJ in <<client-apis.adoc#client-apis,Client APIs>>.
+SolrJ is a Java client that you can use to add documents to the index, update the index, or query the index. You'll find more information on SolrJ in <<using-solrj.adoc#using-solrj,Using SolrJ>>.
Here's an example of using Solr Cell and SolrJ to add documents to a Solr index.
[34/37] lucene-solr:jira/http2: LUCENE-8539: fix some typos and
improve style in TestStopFilter
Posted by da...@apache.org.
LUCENE-8539: fix some typos and improve style in TestStopFilter
Split the test in two tests, use random
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/2e586a7e
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/2e586a7e
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/2e586a7e
Branch: refs/heads/jira/http2
Commit: 2e586a7e7c8019ee81e7646f95250b172b1c1628
Parents: 46d7994
Author: Diego Ceccarelli <dc...@bloomberg.net>
Authored: Tue Oct 23 00:08:51 2018 +0100
Committer: Mike McCandless <mi...@apache.org>
Committed: Thu Dec 6 10:48:50 2018 -0500
----------------------------------------------------------------------
.../apache/lucene/analysis/TestStopFilter.java | 165 +++++++++++++------
1 file changed, 115 insertions(+), 50 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/2e586a7e/lucene/core/src/test/org/apache/lucene/analysis/TestStopFilter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/analysis/TestStopFilter.java b/lucene/core/src/test/org/apache/lucene/analysis/TestStopFilter.java
index f17cd51..5d2e2d8 100644
--- a/lucene/core/src/test/org/apache/lucene/analysis/TestStopFilter.java
+++ b/lucene/core/src/test/org/apache/lucene/analysis/TestStopFilter.java
@@ -17,14 +17,24 @@
package org.apache.lucene.analysis;
import java.io.IOException;
+import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Random;
+import java.util.Set;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.util.English;
public class TestStopFilter extends BaseTokenStreamTestCase {
+
+ private final static int MAX_NUMBER_OF_TOKENS = 50;
// other StopFilter functionality is already tested by TestStopAnalyzer
@@ -37,7 +47,7 @@ public class TestStopFilter extends BaseTokenStreamTestCase {
assertTokenStreamContents(stream, new String[] { "Now", "The" });
}
- public void testStopFilt() throws IOException {
+ public void testStopFilter() throws IOException {
StringReader reader = new StringReader("Now is The Time");
String[] stopWords = new String[] { "is", "the", "Time" };
CharArraySet stopSet = StopFilter.makeStopSet(stopWords);
@@ -47,49 +57,99 @@ public class TestStopFilter extends BaseTokenStreamTestCase {
assertTokenStreamContents(stream, new String[] { "Now", "The" });
}
+
+ private static void logStopwords(String name, Collection<String> stopwords){
+ log(String.format(Locale.ROOT, "stopword list [%s]: %s", name, stopwords.isEmpty() ? "Empty" : stopwords.toString()));
+ }
+
/**
- * Test Position increments applied by StopFilter with and without enabling this option.
+ * Randomly generate a document and a list of stopwords to apply
+ * @param numberOfTokens max number of tokens in the document
+ * @param sb will contain the text at the end of the method
+ * @param stopwords will contain the list of the stopwords at the end of the method
+ * @param stopwordPositions will contain the position of the stopwords at the end of the method
*/
- public void testStopPositons() throws IOException {
- StringBuilder sb = new StringBuilder();
- ArrayList<String> a = new ArrayList<>();
- for (int i=0; i<20; i++) {
- String w = English.intToEnglish(i).trim();
- sb.append(w).append(" ");
- if (i%3 != 0) a.add(w);
+ private static void generateTestSetWithStopwordsAndStopwordPositions(int numberOfTokens, StringBuilder sb, List<String> stopwords, List<Integer> stopwordPositions){
+ Random rand = random();
+ for (int i = 0; i < numberOfTokens; i++) {
+ String token = English.intToEnglish(i).trim();
+ sb.append(token).append(' ');
+ if (i == 0 || rand.nextBoolean()) {
+ // with probability 0.5 will tell if this is a stopword or
+ // no - adding always the first token to make sure that the
+ // list of stopwords is not empty;
+ stopwords.add(token);
+ stopwordPositions.add(i);
+ }
}
- log(sb.toString());
- String stopWords[] = a.toArray(new String[0]);
- for (int i=0; i<a.size(); i++) log("Stop: "+stopWords[i]);
- CharArraySet stopSet = StopFilter.makeStopSet(stopWords);
+ log("Number of tokens : "+numberOfTokens);
+ log("Document : "+sb.toString());
+ logStopwords("Stopwords", stopwords);
+ }
+
+ /**
+ * Check that the positions of the terms in a document keep into account the fact
+ * that some of the words were filtered by the StopwordFilter
+ */
+ public void testTokenPositionWithStopwordFilter() throws IOException {
+ // at least 1 token
+ final int numberOfTokens = random().nextInt(MAX_NUMBER_OF_TOKENS-1)+1;
+ StringBuilder sb = new StringBuilder();
+ List<String> stopwords = new ArrayList<>(numberOfTokens);
+ List<Integer> stopwordPositions = new ArrayList<>(numberOfTokens);
+ generateTestSetWithStopwordsAndStopwordPositions(numberOfTokens, sb, stopwords, stopwordPositions);
+
+ CharArraySet stopSet = StopFilter.makeStopSet(stopwords);
+ logStopwords("All stopwords", stopwords);
// with increments
StringReader reader = new StringReader(sb.toString());
final MockTokenizer in = new MockTokenizer(MockTokenizer.WHITESPACE, false);
in.setReader(reader);
- StopFilter stpf = new StopFilter(in, stopSet);
- doTestStopPositons(stpf);
- // with increments, concatenating two stop filters
- ArrayList<String> a0 = new ArrayList<>();
- ArrayList<String> a1 = new ArrayList<>();
- for (int i=0; i<a.size(); i++) {
- if (i%2==0) {
- a0.add(a.get(i));
- } else {
- a1.add(a.get(i));
- }
- }
- String stopWords0[] = a0.toArray(new String[0]);
- for (int i=0; i<a0.size(); i++) log("Stop0: "+stopWords0[i]);
- String stopWords1[] = a1.toArray(new String[0]);
- for (int i=0; i<a1.size(); i++) log("Stop1: "+stopWords1[i]);
- CharArraySet stopSet0 = StopFilter.makeStopSet(stopWords0);
- CharArraySet stopSet1 = StopFilter.makeStopSet(stopWords1);
- reader = new StringReader(sb.toString());
+ StopFilter stopfilter = new StopFilter(in, stopSet);
+ doTestStopwordsPositions(stopfilter, stopwordPositions, numberOfTokens);
+ }
+
+ /**
+ * Check that the positions of the terms in a document keep into account the fact
+ * that some of the words were filtered by two StopwordFilters concatenated together.
+ */
+ public void testTokenPositionsWithConcatenatedStopwordFilters() throws IOException {
+ // at least 1 token
+ final int numberOfTokens = random().nextInt(MAX_NUMBER_OF_TOKENS-1)+1;
+ StringBuilder sb = new StringBuilder();
+ List<String> stopwords = new ArrayList<>(numberOfTokens);
+ List<Integer> stopwordPositions = new ArrayList<>();
+ generateTestSetWithStopwordsAndStopwordPositions(numberOfTokens, sb, stopwords, stopwordPositions);
+
+ // we want to make sure that concatenating two list of stopwords
+ // produce the same results of using one unique list of stopwords.
+ // So we first generate a list of stopwords:
+ // e.g.: [a, b, c, d, e]
+ // and then we split the list in two disjoint partitions
+ // e.g. [a, c, e] [b, d]
+ int partition = random().nextInt(stopwords.size());
+ Collections.shuffle(stopwords, random());
+ final List<String> stopwordsRandomPartition = stopwords.subList(0, partition);
+ final Set<String> stopwordsRemaining = new HashSet<>(stopwords);
+ stopwordsRemaining.removeAll(stopwordsRandomPartition); // remove the first partition from all the stopwords
+
+ CharArraySet firstStopSet = StopFilter.makeStopSet(stopwordsRandomPartition);
+ logStopwords("Stopwords-first", stopwordsRandomPartition);
+ CharArraySet secondStopSet = StopFilter.makeStopSet(new ArrayList<>(stopwordsRemaining), false);
+ logStopwords("Stopwords-second", stopwordsRemaining);
+
+ Reader reader = new StringReader(sb.toString());
final MockTokenizer in1 = new MockTokenizer(MockTokenizer.WHITESPACE, false);
in1.setReader(reader);
- StopFilter stpf0 = new StopFilter(in1, stopSet0); // first part of the set
- StopFilter stpf01 = new StopFilter(stpf0, stopSet1); // two stop filters concatenated!
- doTestStopPositons(stpf01);
+
+ // Here we create a stopFilter with the stopwords in the first partition and then we
+ // concatenate it with the stopFilter created with the stopwords in the second partition
+ StopFilter stopFilter = new StopFilter(in1, firstStopSet); // first part of the set
+ StopFilter concatenatedStopFilter = new StopFilter(stopFilter, secondStopSet); // two stop filters concatenated!
+
+ // ... and finally we check that the positions of the filtered tokens matched using the concatenated
+ // stopFilters match the positions of the filtered tokens using the unique original list of stopwords
+ doTestStopwordsPositions(concatenatedStopFilter, stopwordPositions, numberOfTokens);
}
// LUCENE-3849: make sure after .end() we see the "ending" posInc
@@ -97,8 +157,8 @@ public class TestStopFilter extends BaseTokenStreamTestCase {
CharArraySet stopSet = StopFilter.makeStopSet("of");
final MockTokenizer in = new MockTokenizer(MockTokenizer.WHITESPACE, false);
in.setReader(new StringReader("test of"));
- StopFilter stpf = new StopFilter(in, stopSet);
- assertTokenStreamContents(stpf, new String[] { "test" },
+ StopFilter stopfilter = new StopFilter(in, stopSet);
+ assertTokenStreamContents(stopfilter, new String[] { "test" },
new int[] {0},
new int[] {4},
null,
@@ -111,20 +171,25 @@ public class TestStopFilter extends BaseTokenStreamTestCase {
null);
}
- private void doTestStopPositons(StopFilter stpf) throws IOException {
- CharTermAttribute termAtt = stpf.getAttribute(CharTermAttribute.class);
- PositionIncrementAttribute posIncrAtt = stpf.getAttribute(PositionIncrementAttribute.class);
- stpf.reset();
- for (int i=0; i<20; i+=3) {
- assertTrue(stpf.incrementToken());
- log("Token "+i+": "+stpf);
- String w = English.intToEnglish(i).trim();
- assertEquals("expecting token "+i+" to be "+w,w,termAtt.toString());
- assertEquals("all but first token must have position increment of 3",i==0?1:3,posIncrAtt.getPositionIncrement());
+ private void doTestStopwordsPositions(StopFilter stopfilter, List<Integer> stopwordPositions, final int numberOfTokens) throws IOException {
+ CharTermAttribute termAtt = stopfilter.getAttribute(CharTermAttribute.class);
+ PositionIncrementAttribute posIncrAtt = stopfilter.getAttribute(PositionIncrementAttribute.class);
+ stopfilter.reset();
+ log("Test stopwords positions:");
+ for (int i=0; i<numberOfTokens; i++) {
+ if (stopwordPositions.contains(i)){
+ // if i is in stopwordPosition it is a stopword and we skip this position
+ continue;
+ }
+ assertTrue(stopfilter.incrementToken());
+ log(String.format(Locale.ROOT, "token %d: %s", i, termAtt.toString()));
+ String token = English.intToEnglish(i).trim();
+ assertEquals(String.format(Locale.ROOT, "expecting token %d to be %s", i, token), token, termAtt.toString());
}
- assertFalse(stpf.incrementToken());
- stpf.end();
- stpf.close();
+ assertFalse(stopfilter.incrementToken());
+ stopfilter.end();
+ stopfilter.close();
+ log("----------");
}
// print debug info depending on VERBOSE
[10/37] lucene-solr:jira/http2: LUCENE-8374 part 1/4: Reduce reads
for sparse DocValues
Posted by da...@apache.org.
LUCENE-8374 part 1/4: Reduce reads for sparse DocValues
Offset and index jump-table for IndexedDISI blocks.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/58a7a8ad
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/58a7a8ad
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/58a7a8ad
Branch: refs/heads/jira/http2
Commit: 58a7a8ada5cebeb261060c56cd6d0a9446478bf6
Parents: 643ffc6
Author: Toke Eskildsen <to...@apache.org>
Authored: Mon Dec 3 14:23:11 2018 +0100
Committer: Toke Eskildsen <to...@apache.org>
Committed: Mon Dec 3 14:23:11 2018 +0100
----------------------------------------------------------------------
lucene/CHANGES.txt | 3 +
.../lucene/codecs/lucene70/IndexedDISI.java | 65 +++++-
.../codecs/lucene70/IndexedDISICache.java | 234 +++++++++++++++++++
.../lucene70/IndexedDISICacheFactory.java | 150 ++++++++++++
.../lucene70/Lucene70DocValuesProducer.java | 85 +++++--
.../lucene/codecs/lucene70/TestIndexedDISI.java | 91 ++++++--
.../org/apache/lucene/index/TestDocValues.java | 105 +++++++++
7 files changed, 684 insertions(+), 49 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/58a7a8ad/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 6b001b9..349d64d 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -208,6 +208,9 @@ Optimizations
to early terminate the iterator if the minimum score is greater than the constant
score. (Christophe Bismuth via Jim Ferenczi)
+* LUCENE-8374: Reduce reads for sparse DocValues and whole number numeric DocValues.
+ (Toke Eskildsen)
+
======================= Lucene 7.7.0 =======================
Build
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/58a7a8ad/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java
index 6138896..114710e 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java
@@ -50,6 +50,9 @@ import org.apache.lucene.util.RoaringDocIdSet;
final class IndexedDISI extends DocIdSetIterator {
static final int MAX_ARRAY_LENGTH = (1 << 12) - 1;
+ static final String NO_NAME = "n/a";
+
+ public final String name;
private static void flush(int block, FixedBitSet buffer, int cardinality, IndexOutput out) throws IOException {
assert block >= 0 && block < 65536;
@@ -98,19 +101,49 @@ final class IndexedDISI extends DocIdSetIterator {
/** The slice that stores the {@link DocIdSetIterator}. */
private final IndexInput slice;
private final long cost;
+ private final IndexedDISICache cache;
IndexedDISI(IndexInput in, long offset, long length, long cost) throws IOException {
- this(in.slice("docs", offset, length), cost);
+ this(in, offset, length, cost, NO_NAME);
+ }
+
+ IndexedDISI(IndexInput in, long offset, long length, long cost, String name) throws IOException {
+ this(in, offset, length, cost, null, name);
+ }
+
+ IndexedDISI(IndexInput in, long offset, long length, long cost, IndexedDISICache cache) throws IOException {
+ this(in, offset, length, cost, cache, NO_NAME);
+ }
+
+ IndexedDISI(IndexInput in, long offset, long length, long cost, IndexedDISICache cache, String name) throws IOException {
+ this(in.slice("docs", offset, length), cost, cache, name);
}
+ IndexedDISI(IndexInput slice, long cost) throws IOException {
+ this(slice, cost, NO_NAME);
+ }
// This constructor allows to pass the slice directly in case it helps reuse
// see eg. Lucene70 norms producer's merge instance
- IndexedDISI(IndexInput slice, long cost) throws IOException {
+ IndexedDISI(IndexInput slice, long cost, String name) throws IOException {
+ this(slice, cost, null, name);
+// IndexedDISICacheFactory.debug(
+// "Non-cached direct slice IndexedDISI with length " + slice.length() + ": " + slice.toString());
+ }
+
+ IndexedDISI(IndexInput slice, long cost, IndexedDISICache cache) throws IOException {
+ this(slice, cost, cache, NO_NAME);
+ }
+ // This constructor allows to pass the slice directly in case it helps reuse
+ // see eg. Lucene70 norms producer's merge instance
+ IndexedDISI(IndexInput slice, long cost, IndexedDISICache cache, String name) {
+ this.name = name;
this.slice = slice;
this.cost = cost;
+ this.cache = cache == null ? IndexedDISICache.EMPTY : cache;
}
private int block = -1;
+ private long blockStart; // Used with the DENSE cache
private long blockEnd;
private int nextBlockIndex = -1;
Method method;
@@ -126,6 +159,8 @@ final class IndexedDISI extends DocIdSetIterator {
private int wordIndex = -1;
// number of one bits encountered so far, including those of `word`
private int numberOfOnes;
+ // Used with rank for jumps inside of DENSE
+ private int denseOrigoIndex;
// ALL variables
private int gap;
@@ -138,6 +173,7 @@ final class IndexedDISI extends DocIdSetIterator {
@Override
public int advance(int target) throws IOException {
final int targetBlock = target & 0xFFFF0000;
+ // Note: The cache makes it easy to add support for random access. This has not been done as the API forbids it
if (block < targetBlock) {
advanceBlock(targetBlock);
}
@@ -163,6 +199,20 @@ final class IndexedDISI extends DocIdSetIterator {
}
private void advanceBlock(int targetBlock) throws IOException {
+ if (targetBlock >= block+2) { // 1 block skip is (slightly) faster to do without block jump table
+ long offset = cache.getFilePointerForBlock(targetBlock >> IndexedDISICache.BLOCK_BITS);
+ if (offset != -1 && offset > slice.getFilePointer()) {
+ int origo = cache.getIndexForBlock(targetBlock >> IndexedDISICache.BLOCK_BITS);
+ if (origo != -1) {
+ this.nextBlockIndex = origo - 1; // -1 to compensate for the always-added 1 in readBlockHeader
+ slice.seek(offset);
+ readBlockHeader();
+ return;
+ }
+ }
+ }
+
+ // Fallback to non-cached
do {
slice.seek(blockEnd);
readBlockHeader();
@@ -170,6 +220,7 @@ final class IndexedDISI extends DocIdSetIterator {
}
private void readBlockHeader() throws IOException {
+ blockStart = slice.getFilePointer();
block = Short.toUnsignedInt(slice.readShort()) << 16;
assert block >= 0;
final int numValues = 1 + Short.toUnsignedInt(slice.readShort());
@@ -187,6 +238,7 @@ final class IndexedDISI extends DocIdSetIterator {
blockEnd = slice.getFilePointer() + (1 << 13);
wordIndex = -1;
numberOfOnes = index + 1;
+ denseOrigoIndex = numberOfOnes;
}
}
@@ -250,6 +302,7 @@ final class IndexedDISI extends DocIdSetIterator {
boolean advanceWithinBlock(IndexedDISI disi, int target) throws IOException {
final int targetInBlock = target & 0xFFFF;
final int targetWordIndex = targetInBlock >>> 6;
+
for (int i = disi.wordIndex + 1; i <= targetWordIndex; ++i) {
disi.word = disi.slice.readLong();
disi.numberOfOnes += Long.bitCount(disi.word);
@@ -263,7 +316,10 @@ final class IndexedDISI extends DocIdSetIterator {
return true;
}
+ // There were no set bits at the wanted position. Move forward until one is reached
while (++disi.wordIndex < 1024) {
+ // This could use the rank cache to skip empty spaces >= 512 bits, but it seems unrealistic
+ // that such blocks would be DENSE
disi.word = disi.slice.readLong();
if (disi.word != 0) {
disi.index = disi.numberOfOnes;
@@ -272,12 +328,15 @@ final class IndexedDISI extends DocIdSetIterator {
return true;
}
}
+ // No set bits in the block at or after the wanted position.
return false;
}
+
@Override
boolean advanceExactWithinBlock(IndexedDISI disi, int target) throws IOException {
final int targetInBlock = target & 0xFFFF;
final int targetWordIndex = targetInBlock >>> 6;
+
for (int i = disi.wordIndex + 1; i <= targetWordIndex; ++i) {
disi.word = disi.slice.readLong();
disi.numberOfOnes += Long.bitCount(disi.word);
@@ -288,6 +347,8 @@ final class IndexedDISI extends DocIdSetIterator {
disi.index = disi.numberOfOnes - Long.bitCount(leftBits);
return (leftBits & 1L) != 0;
}
+
+
},
ALL {
@Override
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/58a7a8ad/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
new file mode 100644
index 0000000..9a80689
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
@@ -0,0 +1,234 @@
+/*
+ * 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.lucene.codecs.lucene70;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.Accountable;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.packed.PackedInts;
+
+import static org.apache.lucene.codecs.lucene70.IndexedDISI.MAX_ARRAY_LENGTH;
+
+/**
+ * Caching of IndexedDISI with two strategies:
+ *
+ * A lookup table for block blockCache and index.
+ *
+ * The lookup table is an array of {@code long}s with an entry for each block. It allows for
+ * direct jumping to the block, as opposed to iteration from the current position and forward
+ * one block at a time.
+ *
+ * Each long entry consists of 2 logical parts:
+ *
+ * The first 31 bits holds the index (number of set bits in the blocks) up to just before the
+ * wanted block. The next 33 bits holds the offset into the underlying slice.
+ * As there is a maximum of 2^16 blocks, it follows that the maximum size of any block must
+ * not exceed 2^17 bits to avoid overflow. This is currently the case, with the largest
+ * block being DENSE and using 2^16 + 32 bits, and is likely to continue to hold as using
+ * more than double the amount of bits is unlikely to be an efficient representation.
+ * The cache overhead is numDocs/1024 bytes.
+ *
+ * Note: There are 4 types of blocks: ALL, DENSE, SPARSE and non-existing (0 set bits).
+ * In the case of non-existing blocks, the entry in the lookup table has index equal to the
+ * previous entry and offset equal to the next non-empty block.
+ *
+ * The performance overhead for creating a cache instance is equivalent to visiting every 65536th
+ * doc value for the given field, i.e. it scales lineary to field size.
+ */
+public class IndexedDISICache implements Accountable {
+ private static final int BLOCK = 65536; // The number of docIDs that a single block represents
+ static final int BLOCK_BITS = 16;
+ private static final long BLOCK_INDEX_SHIFT = 33; // Number of bits to shift a lookup entry to get the index
+ private static final long BLOCK_INDEX_MASK = ~0L << BLOCK_INDEX_SHIFT; // The index bits in a lookup entry
+ private static final long BLOCK_LOOKUP_MASK = ~BLOCK_INDEX_MASK; // The offset bits in a lookup entry
+
+ private long[] blockCache = null; // One every 65536 docs, contains index & slice position
+ private String creationStats = "";
+ private final String name; // Identifier for debug, log & inspection
+
+ // Flags for not-yet-defined-values used during building
+ private static final long BLOCK_EMPTY_INDEX = ~0L << BLOCK_INDEX_SHIFT;
+ private static final long BLOCK_EMPTY_LOOKUP = BLOCK_LOOKUP_MASK;
+ private static final long BLOCK_EMPTY = BLOCK_EMPTY_INDEX | BLOCK_EMPTY_LOOKUP;
+
+ /**
+ * Builds the stated caches for the given IndexInput.
+ *
+ * @param in positioned at the start of the logical underlying bitmap.
+ */
+ IndexedDISICache(IndexInput in, String name) throws IOException {
+ blockCache = new long[16]; // Will be extended when needed
+ Arrays.fill(blockCache, BLOCK_EMPTY);
+ this.name = name;
+ updateCaches(in);
+ }
+
+ private IndexedDISICache() {
+ this.blockCache = null;
+ this.name = "";
+ }
+
+ // Used to represent no caching.
+ public static final IndexedDISICache EMPTY = new IndexedDISICache();
+
+ /**
+ * If available, returns a position within the underlying {@link IndexInput} for the start of the block
+ * containing the wanted bit (the target) or the next non-EMPTY block, if the block representing the bit is empty.
+ * @param targetBlock the index for the block to resolve (docID / 65536).
+ * @return the offset for the block for target or -1 if it cannot be resolved.
+ */
+ long getFilePointerForBlock(int targetBlock) {
+ long offset = blockCache == null || blockCache.length <= targetBlock ?
+ -1 : blockCache[targetBlock] & BLOCK_LOOKUP_MASK;
+ return offset == BLOCK_EMPTY_LOOKUP ? -1 : offset;
+ }
+
+ /**
+ * If available, returns the index; number of set bits before the wanted block.
+ * @param targetBlock the block to resolve (docID / 65536).
+ * @return the index for the block or -1 if it cannot be resolved.
+ */
+ int getIndexForBlock(int targetBlock) {
+ if (blockCache == null || blockCache.length <= targetBlock) {
+ return -1;
+ }
+ return (blockCache[targetBlock] & BLOCK_INDEX_MASK) == BLOCK_EMPTY_INDEX ?
+ -1 : (int)(blockCache[targetBlock] >>> BLOCK_INDEX_SHIFT);
+ }
+
+ public boolean hasOffsets() {
+ return blockCache != null;
+ }
+
+ private void updateCaches(IndexInput slice) throws IOException {
+ final long startOffset = slice.getFilePointer();
+
+ final long startTime = System.nanoTime();
+ AtomicInteger statBlockALL = new AtomicInteger(0);
+ AtomicInteger statBlockDENSE = new AtomicInteger(0);
+ AtomicInteger statBlockSPARSE = new AtomicInteger(0);
+
+ // Fill phase
+ int largestBlock = fillCache(slice, statBlockALL, statBlockDENSE, statBlockSPARSE);
+ freezeCaches(largestBlock);
+
+ slice.seek(startOffset); // Leave it as we found it
+ creationStats = String.format(Locale.ENGLISH,
+ "name=%s, blocks=%d (ALL=%d, DENSE=%d, SPARSE=%d, EMPTY=%d), time=%dms, block=%d bytes",
+ name,
+ largestBlock+1, statBlockALL.get(), statBlockDENSE.get(), statBlockSPARSE.get(),
+ (largestBlock+1-statBlockALL.get()-statBlockDENSE.get()-statBlockSPARSE.get()),
+ (System.nanoTime()-startTime)/1000000,
+ blockCache == null ? 0 : blockCache.length*Long.BYTES);
+ }
+
+ private int fillCache(
+ IndexInput slice, AtomicInteger statBlockALL, AtomicInteger statBlockDENSE, AtomicInteger statBlockSPARSE)
+ throws IOException {
+ int largestBlock = -1;
+ long index = 0;
+ int rankIndex = -1;
+ while (slice.getFilePointer() < slice.length()) {
+ final long startFilePointer = slice.getFilePointer();
+
+ final int blockIndex = Short.toUnsignedInt(slice.readShort());
+ final int numValues = 1 + Short.toUnsignedInt(slice.readShort());
+
+ assert blockIndex > largestBlock;
+ if (blockIndex == DocIdSetIterator.NO_MORE_DOCS >>> 16) { // End reached
+ assert Short.toUnsignedInt(slice.readShort()) == (DocIdSetIterator.NO_MORE_DOCS & 0xFFFF);
+ break;
+ }
+ largestBlock = blockIndex;
+
+ blockCache = ArrayUtil.grow(blockCache, blockIndex+1); // No-op if large enough
+ blockCache[blockIndex] = (index << BLOCK_INDEX_SHIFT) | startFilePointer;
+ index += numValues;
+
+ if (numValues <= MAX_ARRAY_LENGTH) { // SPARSE
+ statBlockSPARSE.incrementAndGet();
+ slice.seek(slice.getFilePointer() + (numValues << 1));
+ continue;
+ }
+ if (numValues == 65536) { // ALL
+ statBlockALL.incrementAndGet();
+ // Already at next block offset
+ continue;
+ }
+
+ // The block is DENSE
+ statBlockDENSE.incrementAndGet();
+ long nextBlockOffset = slice.getFilePointer() + (1 << 13);
+ slice.seek(nextBlockOffset);
+ }
+
+ return largestBlock;
+ }
+
+ private void freezeCaches(int largestBlock) {
+ if (largestBlock == -1) { // No set bit: Disable the caches
+ blockCache = null;
+ return;
+ }
+
+ // Reduce size to minimum
+ if (blockCache.length-1 > largestBlock) {
+ long[] newBC = new long[Math.max(largestBlock - 1, 1)];
+ System.arraycopy(blockCache, 0, newBC, 0, newBC.length);
+ blockCache = newBC;
+ }
+
+ // Set non-defined blockCache entries (caused by blocks with 0 set bits) to the subsequently defined one
+ long latest = BLOCK_EMPTY;
+ for (int i = blockCache.length-1; i >= 0 ; i--) {
+ long current = blockCache[i];
+ if (current == BLOCK_EMPTY) {
+ blockCache[i] = latest;
+ } else {
+ latest = current;
+ }
+ }
+ }
+
+ /**
+ * @return Human readable details from the creation of the cache instance.
+ */
+ public String getCreationStats() {
+ return creationStats;
+ }
+
+ /**
+ * @return Human-readable name for the cache instance.
+ */
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return (blockCache == null ? 0 : RamUsageEstimator.sizeOf(blockCache)) +
+ RamUsageEstimator.NUM_BYTES_OBJECT_REF*3 +
+ RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + creationStats.length()*2;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/58a7a8ad/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
new file mode 100644
index 0000000..6cf8af1
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
@@ -0,0 +1,150 @@
+/*
+ * 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.lucene.codecs.lucene70;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.RandomAccessInput;
+import org.apache.lucene.util.Accountable;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.RamUsageEstimator;
+
+/**
+ * Creates and stores caches for {@link IndexedDISI} and {@link Lucene70DocValuesProducer}.
+ * The caches are stored in maps, where the key is made up from offset and length of a slice
+ * in an underlying segment. Each segment uses their own IndexedDISICacheFactory.
+ *
+ * See {@link IndexedDISICache} for details on the caching.
+ */
+public class IndexedDISICacheFactory implements Accountable {
+
+ /**
+ * If the slice with the DISI-data is less than this number of bytes, don't create a cache.
+ * This is a very low number as the DISI-structure very efficiently represents EMPTY and ALL blocks.
+ */
+ private static int MIN_LENGTH_FOR_CACHING = 50; // Set this very low: Could be 9 EMPTY followed by a SPARSE
+
+ // jump-table and rank for DISI blocks
+ private final Map<Long, IndexedDISICache> disiPool = new HashMap<>();
+
+ /**
+ * Create a cached {@link IndexedDISI} instance.
+ * @param data persistent data containing the DISI-structure.
+ * @param cost cost as defined for IndexedDISI.
+ * @param name identifier for the DISI-structure for debug purposes.
+ * @return a cached IndexedDISI or a plain IndexedDISI, if caching is not applicable.
+ * @throws IOException if the DISI-structure could not be accessed.
+ */
+ IndexedDISI createCachedIndexedDISI(IndexInput data, long key, int cost, String name) throws IOException {
+ IndexedDISICache cache = getCache(data, key, name);
+ return new IndexedDISI(data, cost, cache, name);
+ }
+
+ /**
+ * Create a cached {@link IndexedDISI} instance.
+ * @param data persistent data containing the DISI-structure.
+ * @param offset same as the offset that will also be used for creating an {@link IndexedDISI}.
+ * @param length same af the length that will also be used for creating an {@link IndexedDISI}.
+ * @param cost cost as defined for IndexedDISI.
+ * @param name identifier for the DISI-structure for debug purposes.
+ * @return a cached IndexedDISI or a plain IndexedDISI, if caching is not applicable.
+ * @throws IOException if the DISI-structure could not be accessed.
+ */
+ IndexedDISI createCachedIndexedDISI(IndexInput data, long offset, long length, long cost, String name)
+ throws IOException {
+ IndexedDISICache cache = getCache(data, offset, length, name);
+ return new IndexedDISI(data, offset, length, cost, cache, name);
+ }
+
+ /**
+ * Creates a cache (jump table) for {@link IndexedDISI}.
+ * If the cache has previously been created, the old cache is returned.
+ * @param data the slice to create a cache for.
+ * @param offset same as the offset that will also be used for creating an {@link IndexedDISI}.
+ * @param length same af the length that will also be used for creating an {@link IndexedDISI}.
+ * @param name human readable designation, typically a field name. Used for debug, log and inspection.
+ * @return a cache for the given slice+offset+length or null if not suitable for caching.
+ */
+ public IndexedDISICache getCache(IndexInput data, long offset, long length, String name) throws IOException {
+ if (length < MIN_LENGTH_FOR_CACHING) {
+ return null;
+ }
+
+ long key = offset + length;
+ IndexedDISICache cache = disiPool.get(key);
+ if (cache == null) {
+ // TODO: Avoid overlapping builds of the same cache for performance reason
+ cache = new IndexedDISICache(data.slice("docs", offset, length), name);
+ disiPool.put(key, cache);
+ }
+ return cache;
+ }
+
+ /**
+ * Creates a cache (jump table) for {@link IndexedDISI}.
+ * If the cache has previously been created, the old cache is returned.
+ * @param slice the input slice.
+ * @param key identifier for the cache, unique within the segment that originated the slice.
+ * Recommendation is offset+length for the slice, relative to the data mapping the segment.
+ * Warning: Do not use slice.getFilePointer and slice.length as they are not guaranteed
+ * to be unique within the segment (slice.getFilePointer is 0 when a sub-slice is created).
+ * @param name human readable designation, typically a field name. Used for debug, log and inspection.
+ * @return a cache for the given slice+offset+length or null if not suitable for caching.
+ */
+ public IndexedDISICache getCache(IndexInput slice, long key, String name) throws IOException {
+ final long length = slice.length();
+ if (length < MIN_LENGTH_FOR_CACHING) {
+ return null;
+ }
+
+ IndexedDISICache cache = disiPool.get(key);
+ if (cache == null) {
+ // TODO: Avoid overlapping builds of the same cache
+ cache = new IndexedDISICache(slice, name);
+ disiPool.put(key, cache);
+ }
+ return cache;
+ }
+
+ // Statistics
+ public long getDISIBlocksWithOffsetsCount() {
+ return disiPool.values().stream().filter(IndexedDISICache::hasOffsets).count();
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ long mem = RamUsageEstimator.shallowSizeOf(this) +
+ RamUsageEstimator.shallowSizeOf(disiPool);
+ for (Map.Entry<Long, IndexedDISICache> cacheEntry: disiPool.entrySet()) {
+ mem += RamUsageEstimator.shallowSizeOf(cacheEntry);
+ mem += RamUsageEstimator.sizeOf(cacheEntry.getKey());
+ mem += cacheEntry.getValue().ramBytesUsed();
+ }
+ return mem;
+ }
+
+ /**
+ * Releases all caches.
+ */
+ void releaseAll() {
+ disiPool.clear();
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/58a7a8ad/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java
index b0f6e84..812caba 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java
@@ -57,6 +57,7 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
private final Map<String,SortedNumericEntry> sortedNumerics = new HashMap<>();
private long ramBytesUsed;
private final IndexInput data;
+ private final IndexedDISICacheFactory disiCacheFactory = new IndexedDISICacheFactory();
private final int maxDoc;
/** expert: instantiates a new reader */
@@ -119,23 +120,23 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
byte type = meta.readByte();
if (type == Lucene70DocValuesFormat.NUMERIC) {
- numerics.put(info.name, readNumeric(meta));
+ numerics.put(info.name, readNumeric(meta, info.name));
} else if (type == Lucene70DocValuesFormat.BINARY) {
- binaries.put(info.name, readBinary(meta));
+ binaries.put(info.name, readBinary(meta, info.name));
} else if (type == Lucene70DocValuesFormat.SORTED) {
- sorted.put(info.name, readSorted(meta));
+ sorted.put(info.name, readSorted(meta, info.name));
} else if (type == Lucene70DocValuesFormat.SORTED_SET) {
- sortedSets.put(info.name, readSortedSet(meta));
+ sortedSets.put(info.name, readSortedSet(meta, info.name));
} else if (type == Lucene70DocValuesFormat.SORTED_NUMERIC) {
- sortedNumerics.put(info.name, readSortedNumeric(meta));
+ sortedNumerics.put(info.name, readSortedNumeric(meta, info.name));
} else {
throw new CorruptIndexException("invalid type: " + type, meta);
}
}
}
- private NumericEntry readNumeric(ChecksumIndexInput meta) throws IOException {
- NumericEntry entry = new NumericEntry();
+ private NumericEntry readNumeric(ChecksumIndexInput meta, String name) throws IOException {
+ NumericEntry entry = new NumericEntry(name);
readNumeric(meta, entry);
return entry;
}
@@ -167,8 +168,8 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
entry.valuesLength = meta.readLong();
}
- private BinaryEntry readBinary(ChecksumIndexInput meta) throws IOException {
- BinaryEntry entry = new BinaryEntry();
+ private BinaryEntry readBinary(ChecksumIndexInput meta, String name) throws IOException {
+ BinaryEntry entry = new BinaryEntry(name);
entry.dataOffset = meta.readLong();
entry.dataLength = meta.readLong();
entry.docsWithFieldOffset = meta.readLong();
@@ -186,8 +187,8 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
return entry;
}
- private SortedEntry readSorted(ChecksumIndexInput meta) throws IOException {
- SortedEntry entry = new SortedEntry();
+ private SortedEntry readSorted(ChecksumIndexInput meta, String name) throws IOException {
+ SortedEntry entry = new SortedEntry(name);
entry.docsWithFieldOffset = meta.readLong();
entry.docsWithFieldLength = meta.readLong();
entry.numDocsWithField = meta.readInt();
@@ -198,12 +199,12 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
return entry;
}
- private SortedSetEntry readSortedSet(ChecksumIndexInput meta) throws IOException {
- SortedSetEntry entry = new SortedSetEntry();
+ private SortedSetEntry readSortedSet(ChecksumIndexInput meta, String name) throws IOException {
+ SortedSetEntry entry = new SortedSetEntry(name);
byte multiValued = meta.readByte();
switch (multiValued) {
case 0: // singlevalued
- entry.singleValueEntry = readSorted(meta);
+ entry.singleValueEntry = readSorted(meta, name);
return entry;
case 1: // multivalued
break;
@@ -245,8 +246,8 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
entry.termsIndexAddressesLength = meta.readLong();
}
- private SortedNumericEntry readSortedNumeric(ChecksumIndexInput meta) throws IOException {
- SortedNumericEntry entry = new SortedNumericEntry();
+ private SortedNumericEntry readSortedNumeric(ChecksumIndexInput meta, String name) throws IOException {
+ SortedNumericEntry entry = new SortedNumericEntry(name);
readNumeric(meta, entry);
entry.numDocsWithField = meta.readInt();
if (entry.numDocsWithField != entry.numValues) {
@@ -262,9 +263,23 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
@Override
public void close() throws IOException {
data.close();
+ disiCacheFactory.releaseAll();
}
- private static class NumericEntry {
+ // Highly debatable if this is a sane construct as the name is only used for debug/logging/inspection purposes
+ // This was introduced in LUCENE-8374
+ private static class EntryImpl {
+ final String name;
+
+ public EntryImpl(String name) {
+ this.name = name;
+ }
+ }
+
+ private static class NumericEntry extends EntryImpl {
+ public NumericEntry(String name) {
+ super(name);
+ }
long[] table;
int blockShift;
byte bitsPerValue;
@@ -277,7 +292,10 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
long valuesLength;
}
- private static class BinaryEntry {
+ private static class BinaryEntry extends EntryImpl {
+ public BinaryEntry(String name) {
+ super(name);
+ }
long dataOffset;
long dataLength;
long docsWithFieldOffset;
@@ -290,7 +308,10 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
DirectMonotonicReader.Meta addressesMeta;
}
- private static class TermsDictEntry {
+ private static class TermsDictEntry extends EntryImpl {
+ public TermsDictEntry(String name) {
+ super(name);
+ }
long termsDictSize;
int termsDictBlockShift;
DirectMonotonicReader.Meta termsAddressesMeta;
@@ -308,6 +329,9 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
private static class SortedEntry extends TermsDictEntry {
+ public SortedEntry(String name) {
+ super(name);
+ }
long docsWithFieldOffset;
long docsWithFieldLength;
int numDocsWithField;
@@ -317,6 +341,9 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
private static class SortedSetEntry extends TermsDictEntry {
+ public SortedSetEntry(String name) {
+ super(name);
+ }
SortedEntry singleValueEntry;
long docsWithFieldOffset;
long docsWithFieldLength;
@@ -330,6 +357,9 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
private static class SortedNumericEntry extends NumericEntry {
+ public SortedNumericEntry(String name) {
+ super(name);
+ }
int numDocsWithField;
DirectMonotonicReader.Meta addressesMeta;
long addressesOffset;
@@ -338,7 +368,7 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
@Override
public long ramBytesUsed() {
- return ramBytesUsed;
+ return ramBytesUsed + disiCacheFactory.ramBytesUsed();
}
@Override
@@ -496,7 +526,8 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
} else {
// sparse
- final IndexedDISI disi = new IndexedDISI(data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numValues);
+ final IndexedDISI disi = disiCacheFactory.createCachedIndexedDISI(
+ data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numValues, entry.name);
if (entry.bitsPerValue == 0) {
return new SparseNumericDocValues(disi) {
@Override
@@ -767,7 +798,8 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
} else {
// sparse
- final IndexedDISI disi = new IndexedDISI(data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numDocsWithField);
+ final IndexedDISI disi = disiCacheFactory.createCachedIndexedDISI(
+ data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numDocsWithField, entry.name);
if (entry.minLength == entry.maxLength) {
// fixed length
final int length = entry.maxLength;
@@ -868,7 +900,8 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
};
} else {
// sparse
- final IndexedDISI disi = new IndexedDISI(data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numDocsWithField);
+ final IndexedDISI disi = disiCacheFactory.createCachedIndexedDISI(
+ data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numDocsWithField, entry.name);
return new BaseSortedDocValues(entry, data) {
@Override
@@ -1236,7 +1269,8 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
};
} else {
// sparse
- final IndexedDISI disi = new IndexedDISI(data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numDocsWithField);
+ final IndexedDISI disi = disiCacheFactory.createCachedIndexedDISI(
+ data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numDocsWithField, entry.name);
return new SortedNumericDocValues() {
boolean set;
@@ -1362,7 +1396,8 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
};
} else {
// sparse
- final IndexedDISI disi = new IndexedDISI(data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numDocsWithField);
+ final IndexedDISI disi = disiCacheFactory.createCachedIndexedDISI(
+ data, entry.docsWithFieldOffset, entry.docsWithFieldLength, entry.numDocsWithField, entry.name);
return new BaseSortedSetDocValues(entry, data) {
boolean set;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/58a7a8ad/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java
index 64bfbd5..aae3a7f 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java
@@ -150,6 +150,39 @@ public class TestIndexedDISI extends LuceneTestCase {
}
}
}
+ public void testDenseMultiBlock() throws IOException {
+ try (Directory dir = newDirectory()) {
+ int maxDoc = 10 * 65536; // 10 blocks
+ FixedBitSet set = new FixedBitSet(maxDoc);
+ for (int i = 0; i < maxDoc; i += 2) { // Set every other to ensure dense
+ set.set(i);
+ }
+ doTest(set, dir);
+ }
+ }
+
+ public void testOneDocMissingFixed() throws IOException {
+ int maxDoc = 9699;
+ FixedBitSet set = new FixedBitSet(maxDoc);
+ set.set(0, maxDoc);
+ set.clear(1345);
+ try (Directory dir = newDirectory()) {
+
+ final int cardinality = set.cardinality();
+ long length;
+ try (IndexOutput out = dir.createOutput("foo", IOContext.DEFAULT)) {
+ IndexedDISI.writeBitSet(new BitSetIterator(set, cardinality), out);
+ length = out.getFilePointer();
+ }
+
+ int step = 16000;
+ try (IndexInput in = dir.openInput("foo", IOContext.DEFAULT)) {
+ IndexedDISI disi = new IndexedDISI(in, 0L, length, cardinality);
+ BitSetIterator disi2 = new BitSetIterator(set, cardinality);
+ assertAdvanceEquality(disi, disi2, step);
+ }
+ }
+ }
public void testRandom() throws IOException {
try (Directory dir = newDirectory()) {
@@ -188,32 +221,14 @@ public class TestIndexedDISI extends LuceneTestCase {
try (IndexInput in = dir.openInput("foo", IOContext.DEFAULT)) {
IndexedDISI disi = new IndexedDISI(in, 0L, length, cardinality);
BitSetIterator disi2 = new BitSetIterator(set, cardinality);
- int i = 0;
- for (int doc = disi2.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = disi2.nextDoc()) {
- assertEquals(doc, disi.nextDoc());
- assertEquals(i++, disi.index());
- }
- assertEquals(DocIdSetIterator.NO_MORE_DOCS, disi.nextDoc());
+ assertSingleStepEquality(disi, disi2);
}
for (int step : new int[] {1, 10, 100, 1000, 10000, 100000}) {
try (IndexInput in = dir.openInput("foo", IOContext.DEFAULT)) {
IndexedDISI disi = new IndexedDISI(in, 0L, length, cardinality);
BitSetIterator disi2 = new BitSetIterator(set, cardinality);
- int index = -1;
- while (true) {
- int target = disi2.docID() + step;
- int doc;
- do {
- doc = disi2.nextDoc();
- index++;
- } while (doc < target);
- assertEquals(doc, disi.advance(target));
- if (doc == DocIdSetIterator.NO_MORE_DOCS) {
- break;
- }
- assertEquals(index, disi.index());
- }
+ assertAdvanceEquality(disi, disi2, step);
}
}
@@ -221,8 +236,18 @@ public class TestIndexedDISI extends LuceneTestCase {
try (IndexInput in = dir.openInput("foo", IOContext.DEFAULT)) {
IndexedDISI disi = new IndexedDISI(in, 0L, length, cardinality);
BitSetIterator disi2 = new BitSetIterator(set, cardinality);
+ int disi2length = set.length();
+ assertAdvanceExactRandomized(disi, disi2, disi2length, step);
+ }
+ }
+
+ dir.deleteFile("foo");
+ }
+
+ private void assertAdvanceExactRandomized(IndexedDISI disi, BitSetIterator disi2, int disi2length, int step)
+ throws IOException {
int index = -1;
- for (int target = 0; target < set.length(); ) {
+ for (int target = 0; target < disi2length; ) {
target += TestUtil.nextInt(random(), 0, step);
int doc = disi2.docID();
while (doc < target) {
@@ -241,9 +266,31 @@ public class TestIndexedDISI extends LuceneTestCase {
}
}
}
+
+ private void assertSingleStepEquality(IndexedDISI disi, BitSetIterator disi2) throws IOException {
+ int i = 0;
+ for (int doc = disi2.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = disi2.nextDoc()) {
+ assertEquals(doc, disi.nextDoc());
+ assertEquals(i++, disi.index());
+ }
+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, disi.nextDoc());
}
- dir.deleteFile("foo");
+ private void assertAdvanceEquality(IndexedDISI disi, BitSetIterator disi2, int step) throws IOException {
+ int index = -1;
+ while (true) {
+ int target = disi2.docID() + step;
+ int doc;
+ do {
+ doc = disi2.nextDoc();
+ index++;
+ } while (doc < target);
+ assertEquals(doc, disi.advance(target));
+ if (doc == DocIdSetIterator.NO_MORE_DOCS) {
+ break;
+ }
+ assertEquals("Expected equality using step " + step + " at docID " + doc, index, disi.index());
+ }
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/58a7a8ad/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java b/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
index 0214e54..daebad9 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
@@ -18,7 +18,13 @@ package org.apache.lucene.index;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.BinaryDocValuesField;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
@@ -27,7 +33,9 @@ import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StringField;
+import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.MMapDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.LuceneTestCase;
@@ -123,6 +131,103 @@ public class TestDocValues extends LuceneTestCase {
iw.close();
dir.close();
}
+
+ /**
+ * Triggers varying bits per value codec representation for numeric.
+ */
+ public void testNumericFieldVaryingBPV() throws Exception {
+ Directory dir = newDirectory();
+ IndexWriter iw = new IndexWriter(dir, newIndexWriterConfig(null));
+ long generatedSum = 0;
+ for (int bpv = 2 ; bpv < 24 ; bpv+=3) {
+ for (int i = 0 ; i < 66000 ; i++) {
+ Document doc = new Document();
+ int max = 1 << (bpv - 1);
+ int value = random().nextInt(max) | max;
+ generatedSum += value;
+ //System.out.println("--- " + value);
+ doc.add(new NumericDocValuesField("foo", value));
+ iw.addDocument(doc);
+ }
+ }
+ iw.flush();
+ iw.forceMerge(1, true);
+ iw.commit();
+ DirectoryReader dr = DirectoryReader.open(iw);
+ LeafReader r = getOnlyLeafReader(dr);
+
+ // ok
+ NumericDocValues numDV = DocValues.getNumeric(r, "foo");
+
+ assertNotNull(numDV);
+ long sum = 0;
+ while (numDV.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
+ sum += numDV.longValue();
+ }
+ assertEquals("The sum of retrieved values should match the input", generatedSum, sum);
+
+// assertNotNull(DocValues.getSortedNumeric(r, "foo"));
+
+ dr.close();
+ iw.close();
+ dir.close();
+ }
+
+ // LUCENE-8374 had a bug where a vBPV-block with BPV==0 as the very end of the numeric DocValues made it fail
+ public void testNumericEntryZeroesLastBlock() throws IOException {
+ List<Long> docValues = new ArrayList<>(2*16384);
+ for (int id = 0 ; id < 2*16384 ; id++) { // 2 vBPV-blocks for the dv-field
+ if (id < 16384) { // First vBPV-block just has semi-ramdom values
+ docValues.add((long) (id % 1000));
+ } else { // Second block is all zeroes, resulting in an extreme "1-byte for the while block"-representation
+ docValues.add(0L);
+ }
+ }
+ assertRandomAccessDV("Last block BPV=0", docValues);
+ }
+
+ private void assertRandomAccessDV(String designation, List<Long> docValues) throws IOException {
+ // Create corpus
+ Path zeroPath = Paths.get(System.getProperty("java.io.tmpdir"),"plain_" + random().nextInt());
+ Directory zeroDir = new MMapDirectory(zeroPath);
+ IndexWriterConfig iwc = new IndexWriterConfig(new StandardAnalyzer());
+ //iwc.setCodec(Codec.forName("Lucene70"));
+ IndexWriter iw = new IndexWriter(zeroDir, iwc);
+
+ for (int id = 0 ; id < docValues.size() ; id++) {
+ Document doc = new Document();
+ doc.add(new StringField("id", Integer.toString(id), Field.Store.YES));
+ doc.add(new NumericDocValuesField("dv", docValues.get(id)));
+ iw.addDocument(doc);
+ }
+ iw.flush();
+ iw.commit();
+ iw.forceMerge(1, true);
+ iw.close();
+
+ DirectoryReader dr = DirectoryReader.open(zeroDir);
+
+ for (int id = 0 ; id < docValues.size() ; id++) {
+ int readerIndex = dr.readerIndex(id);
+ // We create a new reader each time as we want to test vBPV-skipping and not sequential iteration
+ NumericDocValues numDV = dr.leaves().get(readerIndex).reader().getNumericDocValues("dv");
+ assertTrue(designation + ": There should be a value for docID " + id, numDV.advanceExact(id));
+ assertEquals(designation + ": The value for docID " + id + " should be as expected",
+ docValues.get(id), Long.valueOf(numDV.longValue()));
+ }
+
+ // Clean up
+ deleteAndClose(zeroDir);
+ Files.delete(zeroPath);
+ }
+
+ private void deleteAndClose(Directory dir) throws IOException {
+ String[] files = dir.listAll();
+ for (String file: files) {
+ dir.deleteFile(file);
+ }
+ dir.close();
+ }
/**
* field with binary docvalues
[13/37] lucene-solr:jira/http2: LUCENE-8374 part 4/4: Reduce reads
for sparse DocValues
Posted by da...@apache.org.
LUCENE-8374 part 4/4: Reduce reads for sparse DocValues
Offset and index jump-table for norm blocks.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/e356d793
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/e356d793
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/e356d793
Branch: refs/heads/jira/http2
Commit: e356d793caf2a899f23261baba922d4a08b362ed
Parents: 7949b98
Author: Toke Eskildsen <to...@apache.org>
Authored: Mon Dec 3 14:30:30 2018 +0100
Committer: Toke Eskildsen <to...@apache.org>
Committed: Mon Dec 3 14:30:30 2018 +0100
----------------------------------------------------------------------
.../apache/lucene/codecs/lucene70/Lucene70NormsProducer.java | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e356d793/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70NormsProducer.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70NormsProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70NormsProducer.java
index c7310e8..321fcff 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70NormsProducer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70NormsProducer.java
@@ -45,6 +45,7 @@ final class Lucene70NormsProducer extends NormsProducer implements Cloneable {
private final Map<Integer,NormsEntry> norms = new HashMap<>();
private final int maxDoc;
private IndexInput data;
+ private final IndexedDISICacheFactory disiCacheFactory = new IndexedDISICacheFactory();
private boolean merging;
private Map<Integer, IndexInput> disiInputs;
private Map<Integer, RandomAccessInput> dataInputs;
@@ -293,7 +294,9 @@ final class Lucene70NormsProducer extends NormsProducer implements Cloneable {
} else {
// sparse
final IndexInput disiInput = getDisiInput(field, entry);
- final IndexedDISI disi = new IndexedDISI(disiInput, entry.numDocsWithField);
+ final IndexedDISI disi = disiCacheFactory.createCachedIndexedDISI(
+ disiInput, entry.docsWithFieldOffset + entry.docsWithFieldLength, entry.numDocsWithField, field.name);
+
if (entry.bytesPerNorm == 0) {
return new SparseNormsIterator(disi) {
@Override
@@ -342,11 +345,12 @@ final class Lucene70NormsProducer extends NormsProducer implements Cloneable {
@Override
public void close() throws IOException {
data.close();
+ disiCacheFactory.releaseAll();
}
@Override
public long ramBytesUsed() {
- return 64L * norms.size(); // good enough
+ return 64L * norms.size() + disiCacheFactory.ramBytesUsed(); // good enough
}
@Override
[31/37] lucene-solr:jira/http2: LUCENE-8593: Specialize single value
numeric DV updates
Posted by da...@apache.org.
LUCENE-8593: Specialize single value numeric DV updates
The case when all values are the the same on a numeric field update
is common for soft_deletes. With the new infrastucture for buffering
DV updates we can gain an easy win by specializing the applied updates
if all values are the same.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/b4e1fe43
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/b4e1fe43
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/b4e1fe43
Branch: refs/heads/jira/http2
Commit: b4e1fe4393b5b23a0de3658c15fbcaf29255b082
Parents: 38cfd0e
Author: Simon Willnauer <si...@apache.org>
Authored: Wed Dec 5 21:58:30 2018 +0100
Committer: Simon Willnauer <si...@apache.org>
Committed: Thu Dec 6 09:40:59 2018 +0100
----------------------------------------------------------------------
.../lucene/index/DocValuesFieldUpdates.java | 48 ++++++++++++++++++++
.../apache/lucene/index/FieldUpdatesBuffer.java | 12 +++++
.../lucene/index/FrozenBufferedUpdates.java | 16 +++++--
.../index/NumericDocValuesFieldUpdates.java | 20 ++++++++
.../lucene/index/TestFieldUpdatesBuffer.java | 7 +++
5 files changed, 98 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b4e1fe43/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java b/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java
index 093a428..9bf9179 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocValuesFieldUpdates.java
@@ -425,4 +425,52 @@ abstract class DocValuesFieldUpdates implements Accountable {
return hasValue;
}
}
+
+ static abstract class SingleValueDocValuesFieldUpdates extends DocValuesFieldUpdates {
+
+ protected SingleValueDocValuesFieldUpdates(int maxDoc, long delGen, String field, DocValuesType type) {
+ super(maxDoc, delGen, field, type);
+ }
+
+ @Override
+ void add(int doc, long value) {
+ assert longValue() == value;
+ super.add(doc);
+ }
+
+ @Override
+ void add(int doc, BytesRef value) {
+ assert binaryValue().equals(value);
+ super.add(doc);
+ }
+
+ @Override
+ void add(int docId, Iterator iterator) {
+ throw new UnsupportedOperationException();
+ }
+
+ protected abstract BytesRef binaryValue();
+
+ protected abstract long longValue();
+
+ @Override
+ Iterator iterator() {
+ return new DocValuesFieldUpdates.AbstractIterator(size, docs, delGen) {
+ @Override
+ protected void set(long idx) {
+ // nothing to do;
+ }
+
+ @Override
+ long longValue() {
+ return SingleValueDocValuesFieldUpdates.this.longValue();
+ }
+
+ @Override
+ BytesRef binaryValue() {
+ return SingleValueDocValuesFieldUpdates.this.binaryValue();
+ }
+ };
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b4e1fe43/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java b/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java
index acfa88e..31a91bb 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java
@@ -183,6 +183,18 @@ final class FieldUpdatesBuffer {
return isNumeric;
}
+ boolean hasSingleValue() {
+ // we only do this optimization for numerics so far.
+ return isNumeric && numericValues.length == 1;
+ }
+
+ long getNumericValue(int idx) {
+ if (hasValues != null && hasValues.get(idx) == false) {
+ return 0;
+ }
+ return numericValues[getArrayIndex(numericValues.length, idx)];
+ }
+
/**
* Struct like class that is used to iterate over all updates in this buffer
*/
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b4e1fe43/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 266db31..94138c7 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
@@ -484,9 +484,10 @@ final class FrozenBufferedUpdates {
long updateCount = 0;
// We first write all our updates private, and only in the end publish to the ReadersAndUpdates */
- Map<String, DocValuesFieldUpdates> holder = new HashMap<>();
+ final List<DocValuesFieldUpdates> resolvedUpdates = new ArrayList<>();
for (Map.Entry<String, FieldUpdatesBuffer> fieldUpdate : updates.entrySet()) {
String updateField = fieldUpdate.getKey();
+ DocValuesFieldUpdates dvUpdates = null;
FieldUpdatesBuffer value = fieldUpdate.getValue();
boolean isNumeric = value.isNumeric();
FieldUpdatesBuffer.BufferedUpdateIterator iterator = value.iterator();
@@ -534,14 +535,19 @@ final class FrozenBufferedUpdates {
if (termsEnum.seekExact(bufferedUpdate.termValue)) {
// we don't need term frequencies for this
postingsEnum = termsEnum.postings(postingsEnum, PostingsEnum.NONE);
- DocValuesFieldUpdates dvUpdates = holder.get(updateField);
if (dvUpdates == null) {
if (isNumeric) {
- dvUpdates = new NumericDocValuesFieldUpdates(delGen, updateField, segState.reader.maxDoc());
+ if (value.hasSingleValue()) {
+ dvUpdates = new NumericDocValuesFieldUpdates
+ .SingleValueNumericDocValuesFieldUpdates(delGen, updateField, segState.reader.maxDoc(),
+ value.getNumericValue(0));
+ } else {
+ dvUpdates = new NumericDocValuesFieldUpdates(delGen, updateField, segState.reader.maxDoc());
+ }
} else {
dvUpdates = new BinaryDocValuesFieldUpdates(delGen, updateField, segState.reader.maxDoc());
}
- holder.put(updateField, dvUpdates);
+ resolvedUpdates.add(dvUpdates);
}
final IntConsumer docIdConsumer;
final DocValuesFieldUpdates update = dvUpdates;
@@ -582,7 +588,7 @@ final class FrozenBufferedUpdates {
}
// now freeze & publish:
- for (DocValuesFieldUpdates update : holder.values()) {
+ for (DocValuesFieldUpdates update : resolvedUpdates) {
if (update.any()) {
update.finish();
segState.rld.addDVUpdate(update);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b4e1fe43/lucene/core/src/java/org/apache/lucene/index/NumericDocValuesFieldUpdates.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/NumericDocValuesFieldUpdates.java b/lucene/core/src/java/org/apache/lucene/index/NumericDocValuesFieldUpdates.java
index 626a61e..ebc196b 100644
--- a/lucene/core/src/java/org/apache/lucene/index/NumericDocValuesFieldUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/NumericDocValuesFieldUpdates.java
@@ -111,4 +111,24 @@ final class NumericDocValuesFieldUpdates extends DocValuesFieldUpdates {
+ Long.BYTES
+ RamUsageEstimator.NUM_BYTES_OBJECT_REF;
}
+
+ static class SingleValueNumericDocValuesFieldUpdates extends SingleValueDocValuesFieldUpdates {
+
+ private final long value;
+
+ SingleValueNumericDocValuesFieldUpdates(long delGen, String field, int maxDoc, long value) {
+ super(maxDoc, delGen, field, DocValuesType.NUMERIC);
+ this.value = value;
+ }
+
+ @Override
+ protected BytesRef binaryValue() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected long longValue() {
+ return value;
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b4e1fe43/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java b/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java
index ae4442f..832c7cc 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java
@@ -36,9 +36,13 @@ public class TestFieldUpdatesBuffer extends LuceneTestCase {
new DocValuesUpdate.NumericDocValuesUpdate(new Term("id", "1"), "age", 6);
FieldUpdatesBuffer buffer = new FieldUpdatesBuffer(counter, update, 15);
buffer.addUpdate(new Term("id", "10"), 6, 15);
+ assertTrue(buffer.hasSingleValue());
buffer.addUpdate(new Term("id", "8"), 12, 15);
+ assertFalse(buffer.hasSingleValue());
buffer.addUpdate(new Term("some_other_field", "8"), 13, 17);
+ assertFalse(buffer.hasSingleValue());
buffer.addUpdate(new Term("id", "8"), 12, 16);
+ assertFalse(buffer.hasSingleValue());
assertTrue(buffer.isNumeric());
FieldUpdatesBuffer.BufferedUpdateIterator iterator = buffer.iterator();
FieldUpdatesBuffer.BufferedUpdate value = iterator.next();
@@ -214,14 +218,17 @@ public class TestFieldUpdatesBuffer extends LuceneTestCase {
int count = 0;
while ((value = iterator.next()) != null) {
+ long v = buffer.getNumericValue(count);
randomUpdate = updates.get(count++);
assertEquals(randomUpdate.term.bytes.utf8ToString(), value.termValue.utf8ToString());
assertEquals(randomUpdate.term.field, value.termField);
assertEquals(randomUpdate.hasValue, value.hasValue);
if (randomUpdate.hasValue) {
assertEquals(randomUpdate.getValue(), value.numericValue);
+ assertEquals(v, value.numericValue);
} else {
assertEquals(0, value.numericValue);
+ assertEquals(0, v);
}
assertEquals(randomUpdate.docIDUpto, value.docUpTo);
}
[02/37] lucene-solr:jira/http2: SOLR-12801: Don't possibly block
forever in this test in another spot.
Posted by da...@apache.org.
SOLR-12801: Don't possibly block forever in this test in another spot.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/b294d846
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/b294d846
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/b294d846
Branch: refs/heads/jira/http2
Commit: b294d8460f85d53bfe5ed57a7aa44911ab851aa2
Parents: b5a9cca
Author: markrmiller <ma...@apache.org>
Authored: Sat Dec 1 12:54:56 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Sat Dec 1 12:55:05 2018 -0600
----------------------------------------------------------------------
.../apache/solr/cloud/autoscaling/sim/TestSimDistributedQueue.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b294d846/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 c607e48..a997571 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
@@ -105,7 +105,7 @@ public class TestSimDistributedQueue extends SolrTestCaseJ4 {
assertNull(dq.peek(100));
// Rerun the earlier test make sure updates are still seen, post reconnection.
- future = executor.submit(() -> new String(dq.peek(true), UTF8));
+ future = executor.submit(() -> new String(dq.peek(15000), UTF8));
try {
future.get(1000, TimeUnit.MILLISECONDS);
fail("TimeoutException expected");
[32/37] lucene-solr:jira/http2: SOLR-12833: Add configurable timeout
to VersionBucket lock.
Posted by da...@apache.org.
SOLR-12833: Add configurable timeout to VersionBucket lock.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/b9a966e5
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/b9a966e5
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/b9a966e5
Branch: refs/heads/jira/http2
Commit: b9a966e5f75b77944f61e88a30c002dbc22c504e
Parents: b4e1fe4
Author: markrmiller <ma...@apache.org>
Authored: Tue Dec 4 10:01:24 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Thu Dec 6 08:36:56 2018 -0600
----------------------------------------------------------------------
solr/CHANGES.txt | 2 +
.../org/apache/solr/update/VersionBucket.java | 44 +++++++
.../org/apache/solr/update/VersionInfo.java | 13 +-
.../processor/DistributedUpdateProcessor.java | 132 +++++++++++--------
4 files changed, 131 insertions(+), 60 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b9a966e5/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index dcc6267..7936e57 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -163,6 +163,8 @@ Improvements
* SOLR-12804: Remove static modifier from Overseer queue access. (Mark Miller)
+* SOLR-12833: Add configurable timeout to VersionBucket lock. (Jeffery Yuan, Mark Miller)
+
Other Changes
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b9a966e5/solr/core/src/java/org/apache/solr/update/VersionBucket.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/update/VersionBucket.java b/solr/core/src/java/org/apache/solr/update/VersionBucket.java
index c0c2826..066936a 100644
--- a/solr/core/src/java/org/apache/solr/update/VersionBucket.java
+++ b/solr/core/src/java/org/apache/solr/update/VersionBucket.java
@@ -16,12 +16,26 @@
*/
package org.apache.solr.update;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
// TODO: make inner?
// TODO: store the highest possible in the index on a commit (but how to not block adds?)
// TODO: could also store highest possible in the transaction log after a commit.
// Or on a new index, just scan "version" for the max?
/** @lucene.internal */
public class VersionBucket {
+ private int lockTimeoutMs;
+
+ public VersionBucket(int lockTimeoutMs) {
+ this.lockTimeoutMs = lockTimeoutMs;
+ }
+
+ private final Lock lock = new ReentrantLock(true);
+ private final Condition condition = lock.newCondition();
+
public long highest;
public void updateHighest(long val) {
@@ -29,4 +43,34 @@ public class VersionBucket {
highest = Math.max(highest, Math.abs(val));
}
}
+
+ public int getLockTimeoutMs() {
+ return lockTimeoutMs;
+ }
+
+ public boolean tryLock() {
+ try {
+ return lock.tryLock(lockTimeoutMs, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void unlock() {
+ lock.unlock();
+ }
+
+ public void signalAll() {
+ condition.signalAll();
+ }
+
+ public void awaitNanos(long nanosTimeout) {
+ try {
+ condition.awaitNanos(nanosTimeout);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b9a966e5/solr/core/src/java/org/apache/solr/update/VersionInfo.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/update/VersionInfo.java b/solr/core/src/java/org/apache/solr/update/VersionInfo.java
index 7697be4..dd39043 100644
--- a/solr/core/src/java/org/apache/solr/update/VersionInfo.java
+++ b/solr/core/src/java/org/apache/solr/update/VersionInfo.java
@@ -45,8 +45,13 @@ import org.slf4j.LoggerFactory;
import static org.apache.solr.common.params.CommonParams.VERSION_FIELD;
public class VersionInfo {
-
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final String SYS_PROP_BUCKET_VERSION_LOCK_TIMEOUT_MS = "bucketVersionLockTimeoutMs";
+
+ /**
+ * same as default client read timeout: 10 mins
+ */
+ private static final int DEFAULT_VERSION_BUCKET_LOCK_TIMEOUT_MS = 600000;
private final UpdateLog ulog;
private final VersionBucket[] buckets;
@@ -54,6 +59,8 @@ public class VersionInfo {
private SchemaField idField;
final ReadWriteLock lock = new ReentrantReadWriteLock(true);
+ private int versionBucketLockTimeoutMs;
+
/**
* Gets and returns the {@link org.apache.solr.common.params.CommonParams#VERSION_FIELD} from the specified
* schema, after verifying that it is indexed, stored, and single-valued.
@@ -94,9 +101,11 @@ public class VersionInfo {
IndexSchema schema = ulog.uhandler.core.getLatestSchema();
versionField = getAndCheckVersionField(schema);
idField = schema.getUniqueKeyField();
+ versionBucketLockTimeoutMs = ulog.uhandler.core.getSolrConfig().getInt("updateHandler/versionBucketLockTimeoutMs",
+ Integer.parseInt(System.getProperty(SYS_PROP_BUCKET_VERSION_LOCK_TIMEOUT_MS, "" + DEFAULT_VERSION_BUCKET_LOCK_TIMEOUT_MS)));
buckets = new VersionBucket[ BitUtil.nextHighestPowerOfTwo(nBuckets) ];
for (int i=0; i<buckets.length; i++) {
- buckets[i] = new VersionBucket();
+ buckets[i] = new VersionBucket(versionBucketLockTimeoutMs);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b9a966e5/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 74bd86e..6f85646 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
@@ -1010,16 +1010,16 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
if (vinfo == null) {
if (AtomicUpdateDocumentMerger.isAtomicUpdate(cmd)) {
- throw new SolrException
- (SolrException.ErrorCode.BAD_REQUEST,
- "Atomic document updates are not supported unless <updateLog/> is configured");
+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
+ "Atomic document updates are not supported unless <updateLog/> is configured");
} else {
super.processAdd(cmd);
return false;
}
}
- // This is only the hash for the bucket, and must be based only on the uniqueKey (i.e. do not use a pluggable hash here)
+ // This is only the hash for the bucket, and must be based only on the uniqueKey (i.e. do not use a pluggable hash
+ // here)
int bucketHash = bucketHash(idBytes);
// at this point, there is an update we need to try and apply.
@@ -1059,9 +1059,10 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
}
vinfo.lockForUpdate();
- try {
- synchronized (bucket) {
- bucket.notifyAll(); //just in case anyone is waiting let them know that we have a new update
+ if (bucket.tryLock()) {
+ try {
+ bucket.signalAll();
+ // just in case anyone is waiting let them know that we have a new update
// we obtain the version when synchronized and then do the add so we can ensure that
// if version1 < version2 then version1 is actually added before version2.
@@ -1100,15 +1101,16 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
if (versionOnUpdate != 0) {
Long lastVersion = vinfo.lookupVersion(cmd.getIndexedId());
long foundVersion = lastVersion == null ? -1 : lastVersion;
- if ( versionOnUpdate == foundVersion || (versionOnUpdate < 0 && foundVersion < 0) || (versionOnUpdate==1 && foundVersion > 0) ) {
+ if (versionOnUpdate == foundVersion || (versionOnUpdate < 0 && foundVersion < 0)
+ || (versionOnUpdate == 1 && foundVersion > 0)) {
// we're ok if versions match, or if both are negative (all missing docs are equal), or if cmd
// specified it must exist (versionOnUpdate==1) and it does.
} else {
- throw new SolrException(ErrorCode.CONFLICT, "version conflict for " + cmd.getPrintableId() + " expected=" + versionOnUpdate + " actual=" + foundVersion);
+ throw new SolrException(ErrorCode.CONFLICT, "version conflict for " + cmd.getPrintableId()
+ + " expected=" + versionOnUpdate + " actual=" + foundVersion);
}
}
-
long version = vinfo.getNewClock();
cmd.setVersion(version);
cmd.getSolrInputDocument().setField(CommonParams.VERSION_FIELD, version);
@@ -1131,25 +1133,28 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
// this was checked for (in waitForDependentUpdates()) before entering the synchronized block.
// So we shouldn't be here, unless what must've happened is:
// by the time synchronization block was entered, the prev update was deleted by DBQ. Since
- // now that update is not in index, the vinfo.lookupVersion() is possibly giving us a version
- // from the deleted list (which might be older than the prev update!)
+ // now that update is not in index, the vinfo.lookupVersion() is possibly giving us a version
+ // from the deleted list (which might be older than the prev update!)
UpdateCommand fetchedFromLeader = fetchFullUpdateFromLeader(cmd, versionOnUpdate);
if (fetchedFromLeader instanceof DeleteUpdateCommand) {
log.info("In-place update of {} failed to find valid lastVersion to apply to, and the document"
+ " was deleted at the leader subsequently.", idBytes.utf8ToString());
- versionDelete((DeleteUpdateCommand)fetchedFromLeader);
+ versionDelete((DeleteUpdateCommand) fetchedFromLeader);
return true;
} else {
assert fetchedFromLeader instanceof AddUpdateCommand;
- // Newer document was fetched from the leader. Apply that document instead of this current in-place update.
- log.info("In-place update of {} failed to find valid lastVersion to apply to, forced to fetch full doc from leader: {}",
+ // Newer document was fetched from the leader. Apply that document instead of this current in-place
+ // update.
+ log.info(
+ "In-place update of {} failed to find valid lastVersion to apply to, forced to fetch full doc from leader: {}",
idBytes.utf8ToString(), fetchedFromLeader);
- // Make this update to become a non-inplace update containing the full document obtained from the leader
- cmd.solrDoc = ((AddUpdateCommand)fetchedFromLeader).solrDoc;
+ // Make this update to become a non-inplace update containing the full document obtained from the
+ // leader
+ cmd.solrDoc = ((AddUpdateCommand) fetchedFromLeader).solrDoc;
cmd.prevVersion = -1;
- cmd.setVersion((long)cmd.solrDoc.getFieldValue(CommonParams.VERSION_FIELD));
+ cmd.setVersion((long) cmd.solrDoc.getFieldValue(CommonParams.VERSION_FIELD));
assert cmd.isInPlaceUpdate() == false;
}
} else {
@@ -1173,11 +1178,11 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
// in this bucket so far, so we know that no reordering has yet occurred.
bucket.updateHighest(versionOnUpdate);
} else {
- // there have been updates higher than the current update. we need to check
+ // there have been updates higher than the current update. we need to check
// the specific version for this id.
Long lastVersion = vinfo.lookupVersion(cmd.getIndexedId());
if (lastVersion != null && Math.abs(lastVersion) >= versionOnUpdate) {
- // This update is a repeat, or was reordered. We need to drop this update.
+ // This update is a repeat, or was reordered. We need to drop this update.
log.debug("Dropping add update due to version {}", idBytes.utf8ToString());
return true;
}
@@ -1188,9 +1193,9 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
}
}
}
-
+
boolean willDistrib = isLeader && nodes != null && nodes.size() > 0;
-
+
SolrInputDocument clonedDoc = null;
if (willDistrib && cloneRequiredOnLeader) {
clonedDoc = cmd.solrDoc.deepCopy();
@@ -1198,16 +1203,22 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
// TODO: possibly set checkDeleteByQueries as a flag on the command?
doLocalAdd(cmd);
-
+
if (willDistrib && cloneRequiredOnLeader) {
cmd.solrDoc = clonedDoc;
}
+ } finally {
- } // end synchronized (bucket)
- } finally {
- vinfo.unlockForUpdate();
+ bucket.unlock();
+
+ vinfo.unlockForUpdate();
+ }
+ return false;
+
+ } else {
+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
+ "Unable to get version bucket lock in " + bucket.getLockTimeoutMs() + " ms");
}
- return false;
}
@VisibleForTesting
@@ -1236,31 +1247,31 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
TimeOut waitTimeout = new TimeOut(5, TimeUnit.SECONDS, TimeSource.NANO_TIME);
vinfo.lockForUpdate();
- try {
- synchronized (bucket) {
+ if (bucket.tryLock()) {
+ try {
Long lookedUpVersion = vinfo.lookupVersion(cmd.getIndexedId());
- lastFoundVersion = lookedUpVersion == null ? 0L: lookedUpVersion;
+ lastFoundVersion = lookedUpVersion == null ? 0L : lookedUpVersion;
if (Math.abs(lastFoundVersion) < cmd.prevVersion) {
- log.debug("Re-ordered inplace update. version={}, prevVersion={}, lastVersion={}, replayOrPeerSync={}, id={}",
- (cmd.getVersion() == 0 ? versionOnUpdate : cmd.getVersion()), cmd.prevVersion, lastFoundVersion, isReplayOrPeersync, cmd.getPrintableId());
+ log.debug("Re-ordered inplace update. version={}, prevVersion={}, lastVersion={}, replayOrPeerSync={}, id={}",
+ (cmd.getVersion() == 0 ? versionOnUpdate : cmd.getVersion()), cmd.prevVersion, lastFoundVersion,
+ isReplayOrPeersync, cmd.getPrintableId());
}
- while (Math.abs(lastFoundVersion) < cmd.prevVersion && !waitTimeout.hasTimedOut()) {
- try {
- long timeLeft = waitTimeout.timeLeft(TimeUnit.MILLISECONDS);
- if (timeLeft > 0) { // wait(0) waits forever until notified, but we don't want that.
- bucket.wait(timeLeft);
- }
- } catch (InterruptedException ie) {
- throw new RuntimeException(ie);
- }
+ while (Math.abs(lastFoundVersion) < cmd.prevVersion && !waitTimeout.hasTimedOut()) {
+ bucket.awaitNanos(waitTimeout.timeLeft(TimeUnit.NANOSECONDS));
lookedUpVersion = vinfo.lookupVersion(cmd.getIndexedId());
- lastFoundVersion = lookedUpVersion == null ? 0L: lookedUpVersion;
+ lastFoundVersion = lookedUpVersion == null ? 0L : lookedUpVersion;
}
+ } finally {
+
+ bucket.unlock();
+
+ vinfo.unlockForUpdate();
}
- } finally {
- vinfo.unlockForUpdate();
+ } else {
+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
+ "Unable to get version bucket lock in " + bucket.getLockTimeoutMs() + " ms");
}
if (Math.abs(lastFoundVersion) > cmd.prevVersion) {
@@ -1793,7 +1804,8 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
return false;
}
- // This is only the hash for the bucket, and must be based only on the uniqueKey (i.e. do not use a pluggable hash here)
+ // This is only the hash for the bucket, and must be based only on the uniqueKey (i.e. do not use a pluggable hash
+ // here)
int bucketHash = bucketHash(idBytes);
// at this point, there is an update we need to try and apply.
@@ -1806,22 +1818,21 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
versionOnUpdate = versionOnUpdateS == null ? 0 : Long.parseLong(versionOnUpdateS);
}
long signedVersionOnUpdate = versionOnUpdate;
- versionOnUpdate = Math.abs(versionOnUpdate); // normalize to positive version
+ versionOnUpdate = Math.abs(versionOnUpdate); // normalize to positive version
boolean isReplayOrPeersync = (cmd.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0;
boolean leaderLogic = isLeader && !isReplayOrPeersync;
boolean forwardedFromCollection = cmd.getReq().getParams().get(DISTRIB_FROM_COLLECTION) != null;
- if (!leaderLogic && versionOnUpdate==0) {
+ if (!leaderLogic && versionOnUpdate == 0) {
throw new SolrException(ErrorCode.BAD_REQUEST, "missing _version_ on update from leader");
}
VersionBucket bucket = vinfo.bucket(bucketHash);
vinfo.lockForUpdate();
- try {
-
- synchronized (bucket) {
+ if (bucket.tryLock()) {
+ try {
if (versionsStored) {
long bucketVersion = bucket.highest;
@@ -1847,11 +1858,13 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
if (signedVersionOnUpdate != 0) {
Long lastVersion = vinfo.lookupVersion(cmd.getIndexedId());
long foundVersion = lastVersion == null ? -1 : lastVersion;
- if ( (signedVersionOnUpdate == foundVersion) || (signedVersionOnUpdate < 0 && foundVersion < 0) || (signedVersionOnUpdate == 1 && foundVersion > 0) ) {
+ if ((signedVersionOnUpdate == foundVersion) || (signedVersionOnUpdate < 0 && foundVersion < 0)
+ || (signedVersionOnUpdate == 1 && foundVersion > 0)) {
// we're ok if versions match, or if both are negative (all missing docs are equal), or if cmd
// specified it must exist (versionOnUpdate==1) and it does.
} else {
- throw new SolrException(ErrorCode.CONFLICT, "version conflict for " + cmd.getId() + " expected=" + signedVersionOnUpdate + " actual=" + foundVersion);
+ throw new SolrException(ErrorCode.CONFLICT, "version conflict for " + cmd.getId() + " expected="
+ + signedVersionOnUpdate + " actual=" + foundVersion);
}
}
@@ -1874,11 +1887,11 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
// in this bucket so far, so we know that no reordering has yet occured.
bucket.updateHighest(versionOnUpdate);
} else {
- // there have been updates higher than the current update. we need to check
+ // there have been updates higher than the current update. we need to check
// the specific version for this id.
Long lastVersion = vinfo.lookupVersion(cmd.getIndexedId());
if (lastVersion != null && Math.abs(lastVersion) >= versionOnUpdate) {
- // This update is a repeat, or was reordered. We need to drop this update.
+ // This update is a repeat, or was reordered. We need to drop this update.
log.debug("Dropping delete update due to version {}", idBytes.utf8ToString());
return true;
}
@@ -1892,10 +1905,13 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
doLocalDelete(cmd);
return false;
- } // end synchronized (bucket)
-
- } finally {
- vinfo.unlockForUpdate();
+ } finally {
+ bucket.unlock();
+ vinfo.unlockForUpdate();
+ }
+ } else {
+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
+ "Unable to get version bucket lock in " + bucket.getLockTimeoutMs() + " ms");
}
}
[23/37] lucene-solr:jira/http2: fix typo
Posted by da...@apache.org.
fix 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/f637c50c
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/f637c50c
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/f637c50c
Branch: refs/heads/jira/http2
Commit: f637c50c1190c8c5e3a0c1008f0542383738e3cd
Parents: f7faae0
Author: Shai Erera <sh...@apache.org>
Authored: Tue Dec 4 16:36:14 2018 +0200
Committer: Shai Erera <sh...@apache.org>
Committed: Tue Dec 4 16:36:14 2018 +0200
----------------------------------------------------------------------
.../src/java/org/apache/lucene/index/FrozenBufferedUpdates.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f637c50c/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 bb84a79f1..7743896 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
@@ -594,7 +594,7 @@ final class FrozenBufferedUpdates {
}
// TODO: we traverse the terms in update order (not term order) so that we
- // apply the updates in the correct order, i.e. if two terms udpate the
+ // apply the updates in the correct order, i.e. if two terms update the
// same document, the last one that came in wins, irrespective of the
// terms lexical order.
// we can apply the updates in terms order if we keep an updatesGen (and
[12/37] lucene-solr:jira/http2: LUCENE-8374 part 3/4: Reduce reads
for sparse DocValues
Posted by da...@apache.org.
LUCENE-8374 part 3/4: Reduce reads for sparse DocValues
Offset jump-table for variable bits per value blocks.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/7949b98f
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/7949b98f
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/7949b98f
Branch: refs/heads/jira/http2
Commit: 7949b98f802c9ab3a588a33cdb1771b83c9fcafb
Parents: 7ad0276
Author: Toke Eskildsen <to...@apache.org>
Authored: Mon Dec 3 14:29:54 2018 +0100
Committer: Toke Eskildsen <to...@apache.org>
Committed: Mon Dec 3 14:29:54 2018 +0100
----------------------------------------------------------------------
.../lucene/codecs/lucene70/IndexedDISI.java | 49 ++++++
.../codecs/lucene70/IndexedDISICache.java | 2 +-
.../lucene70/IndexedDISICacheFactory.java | 90 +++++++++-
.../lucene70/Lucene70DocValuesProducer.java | 165 ++++++++-----------
.../lucene/codecs/lucene70/TestIndexedDISI.java | 36 ++--
.../org/apache/lucene/index/TestDocValues.java | 4 +-
6 files changed, 232 insertions(+), 114 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7949b98f/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java
index 114710e..5eaefbc 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISI.java
@@ -303,6 +303,9 @@ final class IndexedDISI extends DocIdSetIterator {
final int targetInBlock = target & 0xFFFF;
final int targetWordIndex = targetInBlock >>> 6;
+ // If possible, skip ahead using the rank cache
+ disi.rankSkip(disi, target);
+
for (int i = disi.wordIndex + 1; i <= targetWordIndex; ++i) {
disi.word = disi.slice.readLong();
disi.numberOfOnes += Long.bitCount(disi.word);
@@ -337,6 +340,9 @@ final class IndexedDISI extends DocIdSetIterator {
final int targetInBlock = target & 0xFFFF;
final int targetWordIndex = targetInBlock >>> 6;
+ // If possible, skip ahead using the rank cache
+ disi.rankSkip(disi, target);
+
for (int i = disi.wordIndex + 1; i <= targetWordIndex; ++i) {
disi.word = disi.slice.readLong();
disi.numberOfOnes += Long.bitCount(disi.word);
@@ -373,4 +379,47 @@ final class IndexedDISI extends DocIdSetIterator {
abstract boolean advanceExactWithinBlock(IndexedDISI disi, int target) throws IOException;
}
+ /**
+ * If the distance between the current position and the target is > 8 words, the rank cache will
+ * be used to guarantee a worst-case of 1 rank-lookup and 7 word-read-and-count-bits operations.
+ * Note: This does not guarantee a skip up to target, only up to nearest rank boundary. It is the
+ * responsibility of the caller to iterate further to reach target.
+ * @param disi standard DISI.
+ * @param target the wanted docID for which to calculate set-flag and index.
+ * @throws IOException if a disi seek failed.
+ */
+ private void rankSkip(IndexedDISI disi, int target) throws IOException {
+ final int targetInBlock = target & 0xFFFF;
+ final int targetWordIndex = targetInBlock >>> 6;
+
+ // If the distance between the current position and the target is >= 8
+ // then it pays to use the rank to jump
+ if (!(disi.cache.hasRank() && targetWordIndex - disi.wordIndex >= IndexedDISICache.RANK_BLOCK_LONGS)) {
+ return;
+ }
+
+ int rankPos = disi.cache.denseRankPosition(target);
+ if (rankPos == -1) {
+ return;
+ }
+ int rank = disi.cache.getRankInBlock(rankPos);
+ if (rank == -1) {
+ return;
+ }
+ int rankIndex = disi.denseOrigoIndex + rank;
+ int rankWordIndex = (rankPos & 0xFFFF) >> 6;
+ long rankOffset = disi.blockStart + 4 + (rankWordIndex * 8);
+
+ long mark = disi.slice.getFilePointer();
+ disi.slice.seek(rankOffset);
+ long rankWord = disi.slice.readLong();
+ int rankNOO = rankIndex + Long.bitCount(rankWord);
+ rankOffset += Long.BYTES;
+
+
+ //disi.slice.seek(mark);
+ disi.wordIndex = rankWordIndex;
+ disi.word = rankWord;
+ disi.numberOfOnes = rankNOO;
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7949b98f/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
index be0beb7..fdf93cf 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
@@ -319,4 +319,4 @@ public class IndexedDISICache implements Accountable {
RamUsageEstimator.NUM_BYTES_OBJECT_REF*3 +
RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + creationStats.length()*2;
}
-}
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7949b98f/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
index 7a85727..610529a 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
@@ -44,6 +44,8 @@ public class IndexedDISICacheFactory implements Accountable {
// jump-table and rank for DISI blocks
private final Map<Long, IndexedDISICache> disiPool = new HashMap<>();
+ // jump-table for numerics with variable bits per value (dates, longs...)
+ private final Map<String, VaryingBPVJumpTable> vBPVPool = new HashMap<>();
/**
* Create a cached {@link IndexedDISI} instance.
@@ -75,6 +77,24 @@ public class IndexedDISICacheFactory implements Accountable {
}
/**
+ * Creates a cache (jump table) for variable bits per value numerics and returns it.
+ * If the cache has previously been created, the old cache is returned.
+ * @param name the name for the cache, typically the field name. Used as key for later retrieval.
+ * @param slice the long values with varying bits per value.
+ * @param valuesLength the length in bytes of the slice.
+ * @return a jump table for the longs in the given slice or null if the structure is not suitable for caching.
+ */
+ VaryingBPVJumpTable getVBPVJumpTable(String name, RandomAccessInput slice, long valuesLength) throws IOException {
+ VaryingBPVJumpTable jumpTable = vBPVPool.get(name);
+ if (jumpTable == null) {
+ // TODO: Avoid overlapping builds of the same jump table for performance reasons
+ jumpTable = new VaryingBPVJumpTable(slice, name, valuesLength);
+ vBPVPool.put(name, jumpTable);
+ }
+ return jumpTable;
+ }
+
+ /**
* Creates a cache (jump table) for {@link IndexedDISI}.
* If the cache has previously been created, the old cache is returned.
* @param data the slice to create a cache for.
@@ -133,16 +153,26 @@ public class IndexedDISICacheFactory implements Accountable {
public long getDISIBlocksWithRankCount() {
return disiPool.values().stream().filter(IndexedDISICache::hasRank).count();
}
+ public long getVaryingBPVCount() {
+ return vBPVPool.size();
+ }
@Override
public long ramBytesUsed() {
long mem = RamUsageEstimator.shallowSizeOf(this) +
- RamUsageEstimator.shallowSizeOf(disiPool);
+ RamUsageEstimator.shallowSizeOf(disiPool) +
+ RamUsageEstimator.shallowSizeOf(vBPVPool);
for (Map.Entry<Long, IndexedDISICache> cacheEntry: disiPool.entrySet()) {
mem += RamUsageEstimator.shallowSizeOf(cacheEntry);
mem += RamUsageEstimator.sizeOf(cacheEntry.getKey());
mem += cacheEntry.getValue().ramBytesUsed();
}
+ for (Map.Entry<String, VaryingBPVJumpTable> cacheEntry: vBPVPool.entrySet()) {
+ String key = cacheEntry.getKey();
+ mem += RamUsageEstimator.shallowSizeOf(cacheEntry);
+ mem += RamUsageEstimator.shallowSizeOf(key)+key.length()*2;
+ mem += cacheEntry.getValue().ramBytesUsed();
+ }
return mem;
}
@@ -151,5 +181,63 @@ public class IndexedDISICacheFactory implements Accountable {
*/
void releaseAll() {
disiPool.clear();
+ vBPVPool.clear();
+ }
+
+ /**
+ * Jump table used by Lucene70DocValuesProducer.VaryingBPVReader to avoid iterating all blocks from
+ * current to wanted index for numerics with variable bits per value. The jump table holds offsets for all blocks.
+ */
+ public static class VaryingBPVJumpTable implements Accountable {
+ // TODO: It is way overkill to use longs here for practically all indexes. Maybe a PackedInts representation?
+ long[] offsets = new long[10];
+ final String creationStats;
+
+ VaryingBPVJumpTable(RandomAccessInput slice, String name, long valuesLength) throws IOException {
+ final long startTime = System.nanoTime();
+
+ int block = -1;
+ long offset;
+ long blockEndOffset = 0;
+
+ int bitsPerValue;
+ do {
+ offset = blockEndOffset;
+
+ offsets = ArrayUtil.grow(offsets, block+2); // No-op if large enough
+ offsets[block+1] = offset;
+
+ bitsPerValue = slice.readByte(offset++);
+ offset += Long.BYTES; // Skip over delta as we do not resolve the values themselves at this point
+ if (bitsPerValue == 0) {
+ blockEndOffset = offset;
+ } else {
+ final int length = slice.readInt(offset);
+ offset += Integer.BYTES;
+ blockEndOffset = offset + length;
+ }
+ block++;
+ } while (blockEndOffset < valuesLength-Byte.BYTES);
+ offsets = ArrayUtil.copyOfSubArray(offsets, 0, block+1);
+ creationStats = String.format(Locale.ENGLISH,
+ "name=%s, blocks=%d, time=%dms",
+ name, offsets.length, (System.nanoTime()-startTime)/1000000);
+ }
+
+ /**
+ * @param block the logical block in the vBPV structure ( valueindex/16384 ).
+ * @return the index slice offset for the vBPV block (1 block = 16384 values) or -1 if not available.
+ */
+ long getBlockOffset(long block) {
+ // Technically a limitation in caching vs. VaryingBPVReader to limit to 2b blocks of 16K values
+ return offsets[(int) block];
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return RamUsageEstimator.shallowSizeOf(this) +
+ (offsets == null ? 0 : RamUsageEstimator.sizeOf(offsets)) + // offsets
+ RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + creationStats.length()*2; // creationStats
+ }
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7949b98f/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java
index 812caba..9b2b9e0 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesProducer.java
@@ -465,44 +465,18 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
};
} else {
- final RandomAccessInput slice = data.randomAccessSlice(entry.valuesOffset, entry.valuesLength);
if (entry.blockShift >= 0) {
// dense but split into blocks of different bits per value
- final int shift = entry.blockShift;
- final long mul = entry.gcd;
- final int mask = (1 << shift) - 1;
return new DenseNumericDocValues(maxDoc) {
- int block = -1;
- long delta;
- long offset;
- long blockEndOffset;
- LongValues values;
+ final VaryingBPVReader vBPVReader = new VaryingBPVReader(entry);
@Override
public long longValue() throws IOException {
- final int block = doc >>> shift;
- if (this.block != block) {
- int bitsPerValue;
- do {
- offset = blockEndOffset;
- bitsPerValue = slice.readByte(offset++);
- delta = slice.readLong(offset);
- offset += Long.BYTES;
- if (bitsPerValue == 0) {
- blockEndOffset = offset;
- } else {
- final int length = slice.readInt(offset);
- offset += Integer.BYTES;
- blockEndOffset = offset + length;
- }
- this.block ++;
- } while (this.block != block);
- values = bitsPerValue == 0 ? LongValues.ZEROES : DirectReader.getInstance(slice, bitsPerValue, offset);
- }
- return mul * values.get(doc & mask) + delta;
+ return vBPVReader.getLongValue(doc);
}
};
} else {
+ final RandomAccessInput slice = data.randomAccessSlice(entry.valuesOffset, entry.valuesLength);
final LongValues values = DirectReader.getInstance(slice, entry.bitsPerValue);
if (entry.table != null) {
final long[] table = entry.table;
@@ -536,45 +510,19 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
};
} else {
- final RandomAccessInput slice = data.randomAccessSlice(entry.valuesOffset, entry.valuesLength);
if (entry.blockShift >= 0) {
// sparse and split into blocks of different bits per value
- final int shift = entry.blockShift;
- final long mul = entry.gcd;
- final int mask = (1 << shift) - 1;
return new SparseNumericDocValues(disi) {
- int block = -1;
- long delta;
- long offset;
- long blockEndOffset;
- LongValues values;
+ final VaryingBPVReader vBPVReader = new VaryingBPVReader(entry);
@Override
public long longValue() throws IOException {
final int index = disi.index();
- final int block = index >>> shift;
- if (this.block != block) {
- int bitsPerValue;
- do {
- offset = blockEndOffset;
- bitsPerValue = slice.readByte(offset++);
- delta = slice.readLong(offset);
- offset += Long.BYTES;
- if (bitsPerValue == 0) {
- blockEndOffset = offset;
- } else {
- final int length = slice.readInt(offset);
- offset += Integer.BYTES;
- blockEndOffset = offset + length;
- }
- this.block ++;
- } while (this.block != block);
- values = bitsPerValue == 0 ? LongValues.ZEROES : DirectReader.getInstance(slice, bitsPerValue, offset);
- }
- return mul * values.get(index & mask) + delta;
+ return vBPVReader.getLongValue(index);
}
};
} else {
+ final RandomAccessInput slice = data.randomAccessSlice(entry.valuesOffset, entry.valuesLength);
final LongValues values = DirectReader.getInstance(slice, entry.bitsPerValue);
if (entry.table != null) {
final long[] table = entry.table;
@@ -608,47 +556,20 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
}
};
} else {
- final RandomAccessInput slice = data.randomAccessSlice(entry.valuesOffset, entry.valuesLength);
if (entry.blockShift >= 0) {
- final int shift = entry.blockShift;
- final long mul = entry.gcd;
- final long mask = (1L << shift) - 1;
return new LongValues() {
- long block = -1;
- long delta;
- long offset;
- long blockEndOffset;
- LongValues values;
-
+ final VaryingBPVReader vBPVReader = new VaryingBPVReader(entry);
+ @Override
public long get(long index) {
- final long block = index >>> shift;
- if (this.block != block) {
- assert block > this.block : "Reading backwards is illegal: " + this.block + " < " + block;
- int bitsPerValue;
- do {
- offset = blockEndOffset;
- try {
- bitsPerValue = slice.readByte(offset++);
- delta = slice.readLong(offset);
- offset += Long.BYTES;
- if (bitsPerValue == 0) {
- blockEndOffset = offset;
- } else {
- final int length = slice.readInt(offset);
- offset += Integer.BYTES;
- blockEndOffset = offset + length;
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- this.block ++;
- } while (this.block != block);
- values = bitsPerValue == 0 ? LongValues.ZEROES : DirectReader.getInstance(slice, bitsPerValue, offset);
+ try {
+ return vBPVReader.getLongValue(index);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
}
- return mul * values.get(index & mask) + delta;
}
};
} else {
+ final RandomAccessInput slice = data.randomAccessSlice(entry.valuesOffset, entry.valuesLength);
final LongValues values = DirectReader.getInstance(slice, entry.bitsPerValue);
if (entry.table != null) {
final long[] table = entry.table;
@@ -1457,4 +1378,64 @@ final class Lucene70DocValuesProducer extends DocValuesProducer implements Close
CodecUtil.checksumEntireFile(data);
}
+ /**
+ * Reader for longs split into blocks of different bits per values.
+ * The longs are requested by index and must be accessed in monotonically increasing order.
+ */
+ // Note: The order requirement could be removed as the jump-tables allow for backwards iteration.
+ private class VaryingBPVReader {
+ final RandomAccessInput slice;
+ final NumericEntry entry;
+ final int shift;
+ final long mul;
+ final int mask;
+
+ long block = -1;
+ long delta;
+ long offset;
+ long blockEndOffset;
+ LongValues values;
+
+ VaryingBPVReader(NumericEntry entry) throws IOException {
+ this.entry = entry;
+ slice = data.randomAccessSlice(entry.valuesOffset, entry.valuesLength);
+ shift = entry.blockShift;
+ mul = entry.gcd;
+ mask = (1 << shift) - 1;
+ }
+
+ long getLongValue(long index) throws IOException {
+ final long block = index >>> shift;
+ if (this.block != block) {
+ int bitsPerValue;
+ do {
+ // If the needed block is the one directly following the current block, it is cheaper to avoid the cache
+ if (block != this.block+1) {
+ IndexedDISICacheFactory.VaryingBPVJumpTable cache;
+ if ((cache = disiCacheFactory.getVBPVJumpTable(entry.name, slice, entry.valuesLength)) != null) {
+ long candidateOffset;
+ if ((candidateOffset = cache.getBlockOffset(block)) != -1) {
+ blockEndOffset = candidateOffset;
+ this.block = block - 1;
+ }
+ }
+ }
+ offset = blockEndOffset;
+ bitsPerValue = slice.readByte(offset++);
+ delta = slice.readLong(offset);
+ offset += Long.BYTES;
+ if (bitsPerValue == 0) {
+ blockEndOffset = offset;
+ } else {
+ final int length = slice.readInt(offset);
+ offset += Integer.BYTES;
+ blockEndOffset = offset + length;
+ }
+ this.block++;
+ } while (this.block != block);
+ values = bitsPerValue == 0 ? LongValues.ZEROES : DirectReader.getInstance(slice, bitsPerValue, offset);
+ }
+ return mul * values.get(index & mask) + delta;
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7949b98f/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java
index aae3a7f..5201aad 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestIndexedDISI.java
@@ -246,26 +246,26 @@ public class TestIndexedDISI extends LuceneTestCase {
private void assertAdvanceExactRandomized(IndexedDISI disi, BitSetIterator disi2, int disi2length, int step)
throws IOException {
- int index = -1;
+ int index = -1;
for (int target = 0; target < disi2length; ) {
- target += TestUtil.nextInt(random(), 0, step);
- int doc = disi2.docID();
- while (doc < target) {
- doc = disi2.nextDoc();
- index++;
- }
+ target += TestUtil.nextInt(random(), 0, step);
+ int doc = disi2.docID();
+ while (doc < target) {
+ doc = disi2.nextDoc();
+ index++;
+ }
- boolean exists = disi.advanceExact(target);
- assertEquals(doc == target, exists);
- if (exists) {
- assertEquals(index, disi.index());
- } else if (random().nextBoolean()) {
- assertEquals(doc, disi.nextDoc());
- assertEquals(index, disi.index());
- target = doc;
- }
- }
+ boolean exists = disi.advanceExact(target);
+ assertEquals(doc == target, exists);
+ if (exists) {
+ assertEquals(index, disi.index());
+ } else if (random().nextBoolean()) {
+ assertEquals(doc, disi.nextDoc());
+ assertEquals(index, disi.index());
+ target = doc;
}
+ }
+ }
private void assertSingleStepEquality(IndexedDISI disi, BitSetIterator disi2) throws IOException {
int i = 0;
@@ -274,7 +274,7 @@ public class TestIndexedDISI extends LuceneTestCase {
assertEquals(i++, disi.index());
}
assertEquals(DocIdSetIterator.NO_MORE_DOCS, disi.nextDoc());
- }
+ }
private void assertAdvanceEquality(IndexedDISI disi, BitSetIterator disi2, int step) throws IOException {
int index = -1;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7949b98f/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java b/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
index daebad9..3010047 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
@@ -228,8 +228,8 @@ public class TestDocValues extends LuceneTestCase {
}
dir.close();
}
-
- /**
+
+ /**
* field with binary docvalues
*/
public void testBinaryField() throws Exception {
[30/37] lucene-solr:jira/http2: SOLR-13040: Add AwaitsFix annotation
to TestSQLHandler and improve exception information related to that test.
Posted by da...@apache.org.
SOLR-13040: Add AwaitsFix annotation to TestSQLHandler and improve exception information related to that test.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/38cfd0e2
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/38cfd0e2
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/38cfd0e2
Branch: refs/heads/jira/http2
Commit: 38cfd0e25974e9a4cd676a25d373934e1ea8a528
Parents: b0e6a92
Author: markrmiller <ma...@apache.org>
Authored: Wed Dec 5 19:34:13 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Wed Dec 5 19:34:13 2018 -0600
----------------------------------------------------------------------
.../org/apache/solr/handler/export/ExportWriter.java | 2 +-
.../test/org/apache/solr/handler/TestSQLHandler.java | 14 ++++++++++----
2 files changed, 11 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/38cfd0e2/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
index 4aaa6d8..5dff529 100644
--- a/solr/core/src/java/org/apache/solr/handler/export/ExportWriter.java
+++ b/solr/core/src/java/org/apache/solr/handler/export/ExportWriter.java
@@ -310,7 +310,7 @@ public class ExportWriter implements SolrCore.RawWriter, Closeable {
}
if (!schemaField.hasDocValues()) {
- throw new IOException(field + " must have DocValues to use this feature.");
+ throw new IOException(schemaField + " must have DocValues to use this feature.");
}
boolean multiValued = schemaField.multiValued();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/38cfd0e2/solr/core/src/test/org/apache/solr/handler/TestSQLHandler.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/handler/TestSQLHandler.java b/solr/core/src/test/org/apache/solr/handler/TestSQLHandler.java
index 220d9ec..21c8a72 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestSQLHandler.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestSQLHandler.java
@@ -23,6 +23,7 @@ import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
+import java.util.concurrent.TimeUnit;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
@@ -34,6 +35,7 @@ import org.apache.solr.client.solrj.io.stream.SolrStream;
import org.apache.solr.client.solrj.io.stream.TupleStream;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.cloud.AbstractFullDistribZkTestBase;
+import org.apache.solr.cloud.SolrCloudTestCase;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
@@ -53,9 +55,15 @@ public class TestSQLHandler extends AbstractFullDistribZkTestBase {
sliceCount = 2;
}
+ @Override
protected String getCloudSolrConfig() {
return "solrconfig-sql.xml";
}
+
+ @Override
+ protected String getCloudSchemaFile() {
+ return schemaString;
+ }
@Before
@Override
@@ -77,11 +85,9 @@ public class TestSQLHandler extends AbstractFullDistribZkTestBase {
}
@Test
- //28-June-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 21-May-2018
- //@LuceneTestCase.BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 2-Aug-2018
- @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 15-Sep-2018
+ @AwaitsFix(bugUrl="https://issues.apache.org/jira/browse/SOLR-13040")
public void doTest() throws Exception {
- waitForRecoveriesToFinish(false);
+ cloudClient.waitForState(DEFAULT_COLLECTION, 30, TimeUnit.SECONDS, SolrCloudTestCase.activeClusterShape(sliceCount, 4));
testBasicSelect();
testWhere();
[37/37] lucene-solr:jira/http2: Merge with master
Posted by da...@apache.org.
Merge with master
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/9f765aaf
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/9f765aaf
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/9f765aaf
Branch: refs/heads/jira/http2
Commit: 9f765aaf8c31e8524ffd74318a45b4e87bbf4cc8
Parents: cb3ebcb f0db05b
Author: Cao Manh Dat <da...@apache.org>
Authored: Fri Dec 7 09:56:59 2018 +0000
Committer: Cao Manh Dat <da...@apache.org>
Committed: Fri Dec 7 09:56:59 2018 +0000
----------------------------------------------------------------------
lucene/CHANGES.txt | 28 ++
.../miscellaneous/WordDelimiterGraphFilter.java | 17 +-
.../WordDelimiterGraphFilterFactory.java | 5 +-
.../analysis/shingle/FixedShingleFilter.java | 269 ++++-----------
.../TestWordDelimiterGraphFilter.java | 42 ++-
.../shingle/FixedShingleFilterTest.java | 19 +-
.../lucene/analysis/ko/KoreanTokenizer.java | 51 ++-
.../lucene/analysis/ko/TestKoreanAnalyzer.java | 2 +-
.../lucene/analysis/ko/TestKoreanTokenizer.java | 38 +++
.../lucene/codecs/lucene70/Lucene70Codec.java | 5 +-
.../index/TestBackwardsCompatibility.java | 76 ++++-
lucene/common-build.xml | 25 +-
.../lucene/analysis/GraphTokenFilter.java | 284 ++++++++++++++++
.../lucene/codecs/lucene70/IndexedDISI.java | 114 ++++++-
.../codecs/lucene70/IndexedDISICache.java | 330 +++++++++++++++++++
.../lucene70/IndexedDISICacheFactory.java | 260 +++++++++++++++
.../lucene/codecs/lucene70/LongCompressor.java | 251 ++++++++++++++
.../lucene70/Lucene70DocValuesProducer.java | 250 +++++++-------
.../codecs/lucene70/Lucene70NormsProducer.java | 8 +-
.../apache/lucene/index/BufferedUpdates.java | 171 +++-------
.../lucene/index/BufferedUpdatesStream.java | 1 +
.../lucene/index/DocValuesFieldUpdates.java | 58 +++-
.../index/DocumentsWriterDeleteQueue.java | 2 +-
.../lucene/index/DocumentsWriterPerThread.java | 7 +-
.../apache/lucene/index/FieldUpdatesBuffer.java | 292 ++++++++++++++++
.../lucene/index/FrozenBufferedUpdates.java | 308 ++++++-----------
.../index/NumericDocValuesFieldUpdates.java | 20 ++
.../java/org/apache/lucene/util/RankBitSet.java | 302 +++++++++++++++++
.../lucene/analysis/TestGraphTokenFilter.java | 236 +++++++++++++
.../lucene/analysis/TestGraphTokenizers.java | 2 +-
.../apache/lucene/analysis/TestStopFilter.java | 165 +++++++---
.../lucene/codecs/lucene70/TestIndexedDISI.java | 125 ++++---
.../codecs/lucene70/TestLongCompressor.java | 87 +++++
.../org/apache/lucene/index/TestDocValues.java | 109 +++++-
.../lucene/index/TestDocValuesFieldUpdates.java | 63 ++++
.../lucene/index/TestFieldUpdatesBuffer.java | 238 +++++++++++++
.../org/apache/lucene/util/TestRankBitSet.java | 107 ++++++
.../intervals/DisjunctionIntervalsSource.java | 47 ++-
.../lucene/search/intervals/TestIntervals.java | 14 +
.../java/org/apache/lucene/analysis/Token.java | 7 +
lucene/tools/src/groovy/run-beaster.groovy | 86 ++++-
solr/CHANGES.txt | 11 +
.../handler/dataimport/MailEntityProcessor.java | 2 +-
.../client/solrj/embedded/JettySolrRunner.java | 37 ++-
.../apache/solr/handler/ReplicationHandler.java | 188 ++++++-----
.../solr/handler/export/ExportWriter.java | 2 +-
.../org/apache/solr/update/CommitTracker.java | 5 +
.../org/apache/solr/update/VersionBucket.java | 44 +++
.../org/apache/solr/update/VersionInfo.java | 13 +-
.../processor/DistributedUpdateProcessor.java | 120 ++++---
.../TimeRoutedAliasUpdateProcessor.java | 21 +-
.../test/org/apache/solr/MinimalSchemaTest.java | 3 +-
.../solrj/embedded/TestJettySolrRunner.java | 53 ++-
.../AutoAddReplicasPlanActionTest.java | 2 +-
.../cloud/autoscaling/sim/SimCloudManager.java | 5 +
.../sim/TestSimDistributedQueue.java | 6 +-
.../autoscaling/sim/TestSimExtremeIndexing.java | 3 +
.../org/apache/solr/core/PluginInfoTest.java | 23 +-
.../apache/solr/core/ResourceLoaderTest.java | 41 +--
.../org/apache/solr/core/TestCodecSupport.java | 51 ++-
.../test/org/apache/solr/core/TestConfig.java | 17 +-
.../solr/core/TestConfigSetProperties.java | 16 +-
.../org/apache/solr/core/TestConfigSets.java | 15 +-
.../org/apache/solr/core/TestCoreContainer.java | 118 +++----
.../org/apache/solr/core/TestCoreDiscovery.java | 62 ++--
.../org/apache/solr/core/TestLazyCores.java | 15 +-
.../solr/handler/TestReplicationHandler.java | 91 +++--
.../org/apache/solr/handler/TestSQLHandler.java | 14 +-
.../solr/update/MaxSizeAutoCommitTest.java | 231 +++++++++----
.../TimeRoutedAliasUpdateProcessorTest.java | 67 +++-
solr/solr-ref-guide/src/enabling-ssl.adoc | 2 +-
.../src/images/solr-cell/sample-pdf-query.png | Bin 0 -> 226063 bytes
...g-data-with-solr-cell-using-apache-tika.adoc | 310 ++++++++++++-----
.../solrj/request/json/TermsFacetMap.java | 26 ++
...JsonQueryRequestFacetingIntegrationTest.java | 23 ++
75 files changed, 4728 insertions(+), 1430 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9f765aaf/solr/CHANGES.txt
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9f765aaf/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9f765aaf/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
----------------------------------------------------------------------
[09/37] lucene-solr:jira/http2: LUCENE-8548: The KoreanTokenizer no
longer splits unknown words on combining diacritics and detects script
boundaries more accurately with Character#UnicodeScript#of.
Posted by da...@apache.org.
LUCENE-8548: The KoreanTokenizer no longer splits unknown words on combining diacritics and
detects script boundaries more accurately with Character#UnicodeScript#of.
Signed-off-by: Jim Ferenczi <ji...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/643ffc6f
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/643ffc6f
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/643ffc6f
Branch: refs/heads/jira/http2
Commit: 643ffc6f9fb3f7368d48975d750f75f8a66783e2
Parents: b6b9f95
Author: Christophe Bismuth <ch...@gmail.com>
Authored: Wed Nov 21 13:58:44 2018 +0100
Committer: Jim Ferenczi <ji...@apache.org>
Committed: Mon Dec 3 10:57:22 2018 +0100
----------------------------------------------------------------------
lucene/CHANGES.txt | 6 +++
.../lucene/analysis/ko/KoreanTokenizer.java | 51 ++++++++++++++++----
.../lucene/analysis/ko/TestKoreanAnalyzer.java | 2 +-
.../lucene/analysis/ko/TestKoreanTokenizer.java | 38 +++++++++++++++
4 files changed, 87 insertions(+), 10 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/643ffc6f/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 469d6fb..6b001b9 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -214,6 +214,12 @@ Build
* LUCENE-8537: ant test command fails under lucene/tools (Peter Somogyi)
+Bug fixes:
+
+* LUCENE-8548: The KoreanTokenizer no longer splits unknown words on combining diacritics and
+ detects script boundaries more accurately with Character#UnicodeScript#of.
+ (Christophe Bismuth, Jim Ferenczi)
+
New Features
* LUCENE-8026: ExitableDirectoryReader may now time out queries that run on
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/643ffc6f/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java
----------------------------------------------------------------------
diff --git a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java
index ab3205f..012352c 100644
--- a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java
+++ b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java
@@ -43,6 +43,8 @@ import org.apache.lucene.util.IntsRef;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.FST;
+import static java.lang.Character.UnicodeScript;
+
/**
* Tokenizer for Korean that uses morphological analysis.
* <p>
@@ -718,27 +720,42 @@ public final class KoreanTokenizer extends Tokenizer {
if (!anyMatches || characterDefinition.isInvoke(firstCharacter)) {
// Find unknown match:
- final int characterId = characterDefinition.getCharacterClass(firstCharacter);
- final boolean isPunct = isPunctuation(firstCharacter);
-
+ int characterId = characterDefinition.getCharacterClass(firstCharacter);
// NOTE: copied from UnknownDictionary.lookup:
int unknownWordLength;
if (!characterDefinition.isGroup(firstCharacter)) {
unknownWordLength = 1;
} else {
- // Extract unknown word. Characters with the same character class are considered to be part of unknown word
+ // Extract unknown word. Characters with the same script are considered to be part of unknown word
unknownWordLength = 1;
+ UnicodeScript scriptCode = UnicodeScript.of((int) firstCharacter);
+ final boolean isPunct = isPunctuation(firstCharacter);
for (int posAhead = pos + 1; unknownWordLength < MAX_UNKNOWN_WORD_LENGTH; posAhead++) {
- final int ch = buffer.get(posAhead);
- if (ch == -1) {
+ int next = buffer.get(posAhead);
+ if (next == -1) {
break;
}
- if (characterId == characterDefinition.getCharacterClass((char) ch) &&
- isPunctuation((char) ch) == isPunct) {
+ char ch = (char) next;
+ int chType = Character.getType(ch);
+ UnicodeScript sc = UnicodeScript.of(next);
+ boolean sameScript = isSameScript(scriptCode, sc)
+ // Non-spacing marks inherit the script of their base character,
+ // following recommendations from UTR #24.
+ || chType == Character.NON_SPACING_MARK;
+
+ if (sameScript
+ && isPunctuation(ch, chType) == isPunct
+ && characterDefinition.isGroup(ch)) {
unknownWordLength++;
} else {
break;
}
+ // Update the script code and character class if the original script
+ // is Inherited or Common.
+ if (isCommonOrInherited(scriptCode) && isCommonOrInherited(sc) == false) {
+ scriptCode = sc;
+ characterId = characterDefinition.getCharacterClass(ch);
+ }
}
}
@@ -932,11 +949,15 @@ public final class KoreanTokenizer extends Tokenizer {
}
private static boolean isPunctuation(char ch) {
+ return isPunctuation(ch, Character.getType(ch));
+ }
+
+ private static boolean isPunctuation(char ch, int cid) {
// special case for Hangul Letter Araea (interpunct)
if (ch == 0x318D) {
return true;
}
- switch(Character.getType(ch)) {
+ switch(cid) {
case Character.SPACE_SEPARATOR:
case Character.LINE_SEPARATOR:
case Character.PARAGRAPH_SEPARATOR:
@@ -958,4 +979,16 @@ public final class KoreanTokenizer extends Tokenizer {
return false;
}
}
+
+ private static boolean isCommonOrInherited(UnicodeScript script) {
+ return script == UnicodeScript.INHERITED ||
+ script == UnicodeScript.COMMON;
+ }
+
+ /** Determine if two scripts are compatible. */
+ private static boolean isSameScript(UnicodeScript scriptOne, UnicodeScript scriptTwo) {
+ return scriptOne == scriptTwo
+ || isCommonOrInherited(scriptOne)
+ || isCommonOrInherited(scriptTwo);
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/643ffc6f/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanAnalyzer.java
----------------------------------------------------------------------
diff --git a/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanAnalyzer.java b/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanAnalyzer.java
index fd574ce..a56047a 100644
--- a/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanAnalyzer.java
+++ b/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanAnalyzer.java
@@ -106,4 +106,4 @@ public class TestKoreanAnalyzer extends BaseTokenStreamTestCase {
new int[]{1, 1, 1}
);
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/643ffc6f/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java
----------------------------------------------------------------------
diff --git a/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java b/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java
index 7c204fa..50104ff 100644
--- a/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java
+++ b/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java
@@ -328,6 +328,44 @@ public class TestKoreanTokenizer extends BaseTokenStreamTestCase {
analyzer.close();
}
+ public void testCombining() throws IOException {
+ assertAnalyzesTo(analyzer, "Ба̀лтичко мо̑ре",
+ new String[]{"Ба̀лтичко", "мо̑ре"},
+ new int[]{0, 10},
+ new int[]{9, 15},
+ new int[]{1, 1}
+ );
+ assertPartsOfSpeech(analyzer, "Ба̀лтичко мо̑ре",
+ new POS.Type[]{POS.Type.MORPHEME, POS.Type.MORPHEME},
+ new POS.Tag[]{POS.Tag.SL, POS.Tag.SL},
+ new POS.Tag[]{POS.Tag.SL, POS.Tag.SL}
+ );
+
+ assertAnalyzesTo(analyzer, "ka̠k̚t͡ɕ͈a̠k̚",
+ new String[]{"ka̠k̚t͡ɕ͈a̠k̚"},
+ new int[]{0},
+ new int[]{13},
+ new int[]{1}
+ );
+ assertPartsOfSpeech(analyzer, "ka̠k̚t͡ɕ͈a̠k̚",
+ new POS.Type[]{POS.Type.MORPHEME},
+ new POS.Tag[]{POS.Tag.SL},
+ new POS.Tag[]{POS.Tag.SL}
+ );
+
+ assertAnalyzesTo(analyzer, "εἰμί",
+ new String[]{"εἰμί"},
+ new int[]{0},
+ new int[]{4},
+ new int[]{1}
+ );
+ assertPartsOfSpeech(analyzer, "εἰμί",
+ new POS.Type[]{POS.Type.MORPHEME},
+ new POS.Tag[]{POS.Tag.SL},
+ new POS.Tag[]{POS.Tag.SL}
+ );
+ }
+
private void assertReadings(Analyzer analyzer, String input, String... readings) throws IOException {
try (TokenStream ts = analyzer.tokenStream("ignored", input)) {
ReadingAttribute readingAtt = ts.addAttribute(ReadingAttribute.class);
[19/37] lucene-solr:jira/http2: LUCENE-8586: Fix infinite loop in
Intervals.or()
Posted by da...@apache.org.
LUCENE-8586: Fix infinite loop in Intervals.or()
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/c78429a5
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/c78429a5
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/c78429a5
Branch: refs/heads/jira/http2
Commit: c78429a554d28611dacd90c388e6c34039b228d1
Parents: 75a053d
Author: Alan Woodward <ro...@apache.org>
Authored: Mon Dec 3 16:04:54 2018 +0000
Committer: Alan Woodward <ro...@apache.org>
Committed: Tue Dec 4 09:47:42 2018 +0000
----------------------------------------------------------------------
lucene/CHANGES.txt | 3 ++
.../intervals/DisjunctionIntervalsSource.java | 47 +++++++++++++++++++-
.../lucene/search/intervals/TestIntervals.java | 14 ++++++
3 files changed, 62 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c78429a5/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 0a41d70..3c2a409 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -305,6 +305,9 @@ Bug fixes
* LUCENE-8556: Use latitude and longitude instead of encoding values to check if triangle is ear
when using morton optimisation. (Ignacio Vera)
+* LUCENE-8586: Intervals.or() could get stuck in an infinite loop on certain indexes
+ (Alan Woodward)
+
New Features
* LUCENE-8496: Selective indexing - modify BKDReader/BKDWriter to allow users
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c78429a5/lucene/sandbox/src/java/org/apache/lucene/search/intervals/DisjunctionIntervalsSource.java
----------------------------------------------------------------------
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/intervals/DisjunctionIntervalsSource.java b/lucene/sandbox/src/java/org/apache/lucene/search/intervals/DisjunctionIntervalsSource.java
index 79c1bcf..c54f18b 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/intervals/DisjunctionIntervalsSource.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/intervals/DisjunctionIntervalsSource.java
@@ -146,7 +146,7 @@ class DisjunctionIntervalsSource extends IntervalsSource {
@Override
public int nextInterval() throws IOException {
- if (current == EMPTY) {
+ if (current == EMPTY || current == EXHAUSTED) {
if (intervalQueue.size() > 0) {
current = intervalQueue.top();
}
@@ -160,7 +160,7 @@ class DisjunctionIntervalsSource extends IntervalsSource {
}
}
if (intervalQueue.size() == 0) {
- current = EMPTY;
+ current = EXHAUSTED;
return NO_MORE_INTERVALS;
}
current = intervalQueue.top();
@@ -239,4 +239,47 @@ class DisjunctionIntervalsSource extends IntervalsSource {
}
};
+ private static final IntervalIterator EXHAUSTED = new IntervalIterator() {
+
+ @Override
+ public int docID() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public long cost() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int start() {
+ return NO_MORE_INTERVALS;
+ }
+
+ @Override
+ public int end() {
+ return NO_MORE_INTERVALS;
+ }
+
+ @Override
+ public int nextInterval() {
+ return NO_MORE_INTERVALS;
+ }
+
+ @Override
+ public float matchCost() {
+ return 0;
+ }
+ };
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c78429a5/lucene/sandbox/src/test/org/apache/lucene/search/intervals/TestIntervals.java
----------------------------------------------------------------------
diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/intervals/TestIntervals.java b/lucene/sandbox/src/test/org/apache/lucene/search/intervals/TestIntervals.java
index d7754be..6002b3a 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/search/intervals/TestIntervals.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/search/intervals/TestIntervals.java
@@ -56,6 +56,8 @@ public class TestIntervals extends LuceneTestCase {
"Porridge is great"
};
+ // 0 1 2 3 4 5 6 7 8 9
+ // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
private static String field2_docs[] = {
"In Xanadu did Kubla Khan a stately pleasure dome decree",
"Where Alph the sacred river ran through caverns measureless to man",
@@ -260,6 +262,18 @@ public class TestIntervals extends LuceneTestCase {
assertFalse(mi.next());
}
+ public void testCombinationDisjunction() throws IOException {
+ IntervalsSource source = Intervals.ordered(
+ Intervals.or(Intervals.term("alph"), Intervals.term("sacred")),
+ Intervals.term("measureless")
+ );
+ checkIntervals(source, "field2", 1, new int[][]{
+ {},
+ { 3, 8 },
+ {}, {}, {}, {}
+ });
+ }
+
public void testNesting() throws IOException {
IntervalsSource source = Intervals.unordered(
Intervals.term("pease"),
[29/37] lucene-solr:jira/http2: LUCENE-8590: Optimize DocValues
update datastructures
Posted by da...@apache.org.
LUCENE-8590: Optimize DocValues update datastructures
Today we are using a LinkedHashMap to buffer doc-values updates in
BufferedUpdates. This on the one hand uses an Object based datastructure
and on the other requires re-encoding the data into a more compact representation
once the BufferedUpdates are frozen. This change uses a more compact represenation
for the updates already in the BufferedUpdates in a parallel-array like datastructure
that can be reused in FrozenBufferedDeletes. It also adds an much simpler to use
API to consume the updates and allows for internal memory optimization for common
case updates.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/b0e6a92e
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/b0e6a92e
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/b0e6a92e
Branch: refs/heads/jira/http2
Commit: b0e6a92ede321dc6932348978bed1a4c04a70d8c
Parents: c81822e
Author: Simon Willnauer <si...@apache.org>
Authored: Tue Dec 4 17:36:46 2018 +0100
Committer: Simon Willnauer <si...@apache.org>
Committed: Wed Dec 5 17:22:40 2018 +0100
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 +
.../apache/lucene/index/BufferedUpdates.java | 171 +++--------
.../lucene/index/BufferedUpdatesStream.java | 1 +
.../index/DocumentsWriterDeleteQueue.java | 2 +-
.../lucene/index/DocumentsWriterPerThread.java | 7 +-
.../apache/lucene/index/FieldUpdatesBuffer.java | 280 +++++++++++++++++
.../lucene/index/FrozenBufferedUpdates.java | 300 ++++++-------------
.../lucene/index/TestFieldUpdatesBuffer.java | 231 ++++++++++++++
8 files changed, 656 insertions(+), 340 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b0e6a92e/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 3c2a409..51b831d 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -260,6 +260,10 @@ Optimizations
* LUCENE-8552: FieldInfos.getMergedFieldInfos no longer does any merging if there is <= 1 segment.
(Christophe Bismuth via David Smiley)
+* LUCENE-8590: BufferedUpdates now uses an optimized storage for buffering docvalues updates that
+ can safe up to 80% of the heap used compared to the previous implementation and uses non-object
+ based datastructures. (Simon Willnauer, Mike McCandless, Shai Erera, Adrien Grant)
+
Other
* LUCENE-8573: BKDWriter now uses FutureArrays#mismatch to compute shared prefixes.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b0e6a92e/lucene/core/src/java/org/apache/lucene/index/BufferedUpdates.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/BufferedUpdates.java b/lucene/core/src/java/org/apache/lucene/index/BufferedUpdates.java
index ae37f14..04b19b7 100644
--- a/lucene/core/src/java/org/apache/lucene/index/BufferedUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/BufferedUpdates.java
@@ -19,16 +19,15 @@ package org.apache.lucene.index;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.function.IntFunction;
import org.apache.lucene.index.DocValuesUpdate.BinaryDocValuesUpdate;
import org.apache.lucene.index.DocValuesUpdate.NumericDocValuesUpdate;
import org.apache.lucene.search.Query;
+import org.apache.lucene.util.Accountable;
+import org.apache.lucene.util.Counter;
import org.apache.lucene.util.RamUsageEstimator;
/** Holds buffered deletes and updates, by docID, term or query for a
@@ -42,7 +41,7 @@ import org.apache.lucene.util.RamUsageEstimator;
// instance on DocumentWriterPerThread, or via sync'd code by
// DocumentsWriterDeleteQueue
-class BufferedUpdates {
+class BufferedUpdates implements Accountable {
/* Rough logic: HashMap has an array[Entry] w/ varying
load factor (say 2 * POINTER). Entry is object w/ Term
@@ -67,94 +66,20 @@ class BufferedUpdates {
(OBJ_HEADER + 3*POINTER + INT). Query we often
undercount (say 24 bytes). Integer is OBJ_HEADER + INT. */
final static int BYTES_PER_DEL_QUERY = 5*RamUsageEstimator.NUM_BYTES_OBJECT_REF + 2*RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 2*Integer.BYTES + 24;
-
- /* Rough logic: NumericUpdate calculates its actual size,
- * including the update Term and DV field (String). The
- * per-field map holds a reference to the updated field, and
- * therefore we only account for the object reference and
- * map space itself. This is incremented when we first see
- * an updated field.
- *
- * HashMap has an array[Entry] w/ varying load
- * factor (say 2*POINTER). Entry is an object w/ String key,
- * LinkedHashMap val, int hash, Entry next (OBJ_HEADER + 3*POINTER + INT).
- *
- * LinkedHashMap (val) is counted as OBJ_HEADER, array[Entry] ref + header, 4*INT, 1*FLOAT,
- * Set (entrySet) (2*OBJ_HEADER + ARRAY_HEADER + 2*POINTER + 4*INT + FLOAT)
- */
- final static int BYTES_PER_NUMERIC_FIELD_ENTRY =
- 7*RamUsageEstimator.NUM_BYTES_OBJECT_REF + 3*RamUsageEstimator.NUM_BYTES_OBJECT_HEADER +
- RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + 5*Integer.BYTES + Float.BYTES;
-
- /* Rough logic: Incremented when we see another Term for an already updated
- * field.
- * LinkedHashMap has an array[Entry] w/ varying load factor
- * (say 2*POINTER). Entry is an object w/ Term key, NumericUpdate val,
- * int hash, Entry next, Entry before, Entry after (OBJ_HEADER + 5*POINTER + INT).
- *
- * Term (key) is counted only as POINTER.
- * NumericUpdate (val) counts its own size and isn't accounted for here.
- */
- final static int BYTES_PER_NUMERIC_UPDATE_ENTRY = 7*RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + Integer.BYTES;
-
- /* Rough logic: BinaryUpdate calculates its actual size,
- * including the update Term and DV field (String). The
- * per-field map holds a reference to the updated field, and
- * therefore we only account for the object reference and
- * map space itself. This is incremented when we first see
- * an updated field.
- *
- * HashMap has an array[Entry] w/ varying load
- * factor (say 2*POINTER). Entry is an object w/ String key,
- * LinkedHashMap val, int hash, Entry next (OBJ_HEADER + 3*POINTER + INT).
- *
- * LinkedHashMap (val) is counted as OBJ_HEADER, array[Entry] ref + header, 4*INT, 1*FLOAT,
- * Set (entrySet) (2*OBJ_HEADER + ARRAY_HEADER + 2*POINTER + 4*INT + FLOAT)
- */
- final static int BYTES_PER_BINARY_FIELD_ENTRY =
- 7*RamUsageEstimator.NUM_BYTES_OBJECT_REF + 3*RamUsageEstimator.NUM_BYTES_OBJECT_HEADER +
- RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + 5*Integer.BYTES + Float.BYTES;
-
- /* Rough logic: Incremented when we see another Term for an already updated
- * field.
- * LinkedHashMap has an array[Entry] w/ varying load factor
- * (say 2*POINTER). Entry is an object w/ Term key, BinaryUpdate val,
- * int hash, Entry next, Entry before, Entry after (OBJ_HEADER + 5*POINTER + INT).
- *
- * Term (key) is counted only as POINTER.
- * BinaryUpdate (val) counts its own size and isn't accounted for here.
- */
- final static int BYTES_PER_BINARY_UPDATE_ENTRY = 7*RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + Integer.BYTES;
-
final AtomicInteger numTermDeletes = new AtomicInteger();
- final AtomicInteger numNumericUpdates = new AtomicInteger();
- final AtomicInteger numBinaryUpdates = new AtomicInteger();
+ final AtomicInteger numFieldUpdates = new AtomicInteger();
final Map<Term,Integer> deleteTerms = new HashMap<>();
final Map<Query,Integer> deleteQueries = new HashMap<>();
final List<Integer> deleteDocIDs = new ArrayList<>();
- // Map<dvField,Map<updateTerm,NumericUpdate>>
- // For each field we keep an ordered list of NumericUpdates, key'd by the
- // update Term. LinkedHashMap guarantees we will later traverse the map in
- // insertion order (so that if two terms affect the same document, the last
- // one that came in wins), and helps us detect faster if the same Term is
- // used to update the same field multiple times (so we later traverse it
- // only once).
- final Map<String,LinkedHashMap<Term,NumericDocValuesUpdate>> numericUpdates = new HashMap<>();
+ final Map<String,FieldUpdatesBuffer> fieldUpdates = new HashMap<>();
- // Map<dvField,Map<updateTerm,BinaryUpdate>>
- // For each field we keep an ordered list of BinaryUpdates, key'd by the
- // update Term. LinkedHashMap guarantees we will later traverse the map in
- // insertion order (so that if two terms affect the same document, the last
- // one that came in wins), and helps us detect faster if the same Term is
- // used to update the same field multiple times (so we later traverse it
- // only once).
- final Map<String,LinkedHashMap<Term,BinaryDocValuesUpdate>> binaryUpdates = new HashMap<>();
public static final Integer MAX_INT = Integer.valueOf(Integer.MAX_VALUE);
- final AtomicLong bytesUsed;
+ private final Counter bytesUsed = Counter.newCounter(true);
+ final Counter fieldUpdatesBytesUsed = Counter.newCounter(true);
private final static boolean VERBOSE_DELETES = false;
@@ -163,7 +88,6 @@ class BufferedUpdates {
final String segmentName;
public BufferedUpdates(String segmentName) {
- this.bytesUsed = new AtomicLong();
this.segmentName = segmentName;
}
@@ -171,8 +95,8 @@ class BufferedUpdates {
public String toString() {
if (VERBOSE_DELETES) {
return "gen=" + gen + " numTerms=" + numTermDeletes + ", deleteTerms=" + deleteTerms
- + ", deleteQueries=" + deleteQueries + ", deleteDocIDs=" + deleteDocIDs + ", numericUpdates=" + numericUpdates
- + ", binaryUpdates=" + binaryUpdates + ", bytesUsed=" + bytesUsed;
+ + ", deleteQueries=" + deleteQueries + ", deleteDocIDs=" + deleteDocIDs + ", fieldUpdates=" + fieldUpdates
+ + ", bytesUsed=" + bytesUsed;
} else {
String s = "gen=" + gen;
if (numTermDeletes.get() != 0) {
@@ -184,11 +108,8 @@ class BufferedUpdates {
if (deleteDocIDs.size() != 0) {
s += " " + deleteDocIDs.size() + " deleted docIDs";
}
- if (numNumericUpdates.get() != 0) {
- s += " " + numNumericUpdates.get() + " numeric updates (unique count=" + numericUpdates.size() + ")";
- }
- if (numBinaryUpdates.get() != 0) {
- s += " " + numBinaryUpdates.get() + " binary updates (unique count=" + binaryUpdates.size() + ")";
+ if (numFieldUpdates.get() != 0) {
+ s += " " + numFieldUpdates.get() + " field updates (unique count=" + fieldUpdates.size() + ")";
}
if (bytesUsed.get() != 0) {
s += " bytesUsed=" + bytesUsed.get();
@@ -235,48 +156,23 @@ class BufferedUpdates {
}
void addNumericUpdate(NumericDocValuesUpdate update, int docIDUpto) {
- if (addDocValuesUpdate(numericUpdates, update, docIDUpto, update::prepareForApply, BYTES_PER_NUMERIC_UPDATE_ENTRY,
- BYTES_PER_NUMERIC_FIELD_ENTRY)) {
- numNumericUpdates.incrementAndGet();
+ FieldUpdatesBuffer buffer = fieldUpdates.computeIfAbsent(update.field, k -> new FieldUpdatesBuffer(fieldUpdatesBytesUsed, update, docIDUpto));
+ if (update.hasValue) {
+ buffer.addUpdate(update.term, update.getValue(), docIDUpto);
+ } else {
+ buffer.addNoValue(update.term, docIDUpto);
}
+ numFieldUpdates.incrementAndGet();
}
void addBinaryUpdate(BinaryDocValuesUpdate update, int docIDUpto) {
- if (addDocValuesUpdate(binaryUpdates, update, docIDUpto, update::prepareForApply, BYTES_PER_BINARY_UPDATE_ENTRY,
- BYTES_PER_BINARY_FIELD_ENTRY)) {
- numBinaryUpdates.incrementAndGet();
- }
- }
-
- private <T extends DocValuesUpdate> boolean addDocValuesUpdate(Map<String,LinkedHashMap<Term,T>> updates, T update,
- int docIDUpto, IntFunction<T> prepareForApply,
- long bytesPerUpdateEntry, long bytesPerFieldEntry) {
- LinkedHashMap<Term,T> fieldUpdates = updates.get(update.field);
- if (fieldUpdates == null) {
- fieldUpdates = new LinkedHashMap<>();
- updates.put(update.field, fieldUpdates);
- bytesUsed.addAndGet(bytesPerFieldEntry);
- }
- final T current = fieldUpdates.get(update.term);
- if (current != null && docIDUpto < current.docIDUpto) {
- // Only record the new number if it's greater than or equal to the current
- // one. This is important because if multiple threads are replacing the
- // same doc at nearly the same time, it's possible that one thread that
- // got a higher docID is scheduled before the other threads.
- return false;
- }
-
- // since it's a LinkedHashMap, we must first remove the Term entry so that
- // it's added last (we're interested in insertion-order).
- if (current != null) {
- fieldUpdates.remove(update.term);
- }
-
- fieldUpdates.put(update.term, prepareForApply.apply(docIDUpto)); // only make a copy if necessary
- if (current == null) {
- bytesUsed.addAndGet(bytesPerUpdateEntry + update.sizeInBytes());
+ FieldUpdatesBuffer buffer = fieldUpdates.computeIfAbsent(update.field, k -> new FieldUpdatesBuffer(fieldUpdatesBytesUsed, update, docIDUpto));
+ if (update.hasValue) {
+ buffer.addUpdate(update.term, update.getValue(), docIDUpto);
+ } else {
+ buffer.addNoValue(update.term, docIDUpto);
}
- return true;
+ numFieldUpdates.incrementAndGet();
}
void clearDeleteTerms() {
@@ -288,15 +184,24 @@ class BufferedUpdates {
deleteTerms.clear();
deleteQueries.clear();
deleteDocIDs.clear();
- numericUpdates.clear();
- binaryUpdates.clear();
numTermDeletes.set(0);
- numNumericUpdates.set(0);
- numBinaryUpdates.set(0);
- bytesUsed.set(0);
+ numFieldUpdates.set(0);
+ fieldUpdates.clear();
+ bytesUsed.addAndGet(-bytesUsed.get());
+ fieldUpdatesBytesUsed.addAndGet(-fieldUpdatesBytesUsed.get());
}
boolean any() {
- return deleteTerms.size() > 0 || deleteDocIDs.size() > 0 || deleteQueries.size() > 0 || numericUpdates.size() > 0 || binaryUpdates.size() > 0;
+ return deleteTerms.size() > 0 || deleteDocIDs.size() > 0 || deleteQueries.size() > 0 || numFieldUpdates.get() > 0;
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return bytesUsed.get() + fieldUpdatesBytesUsed.get();
+ }
+
+ void clearDeletedDocIds() {
+ deleteDocIDs.clear();
+ bytesUsed.addAndGet(-deleteDocIDs.size() * BufferedUpdates.BYTES_PER_DEL_DOCID);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b0e6a92e/lucene/core/src/java/org/apache/lucene/index/BufferedUpdatesStream.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/BufferedUpdatesStream.java b/lucene/core/src/java/org/apache/lucene/index/BufferedUpdatesStream.java
index 9a669e0..a76d624 100644
--- a/lucene/core/src/java/org/apache/lucene/index/BufferedUpdatesStream.java
+++ b/lucene/core/src/java/org/apache/lucene/index/BufferedUpdatesStream.java
@@ -345,4 +345,5 @@ final class BufferedUpdatesStream implements Accountable {
}
}
}
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b0e6a92e/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java
index 0db043a..e940d9ef 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java
@@ -469,7 +469,7 @@ final class DocumentsWriterDeleteQueue implements Accountable {
@Override
public long ramBytesUsed() {
- return globalBufferedUpdates.bytesUsed.get();
+ return globalBufferedUpdates.ramBytesUsed();
}
@Override
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b0e6a92e/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
index c8ebc4d..22b8e3a 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
@@ -443,8 +443,7 @@ final class DocumentsWriterPerThread {
flushState.liveDocs.clear(delDocID);
}
flushState.delCountOnFlush = pendingUpdates.deleteDocIDs.size();
- pendingUpdates.bytesUsed.addAndGet(-pendingUpdates.deleteDocIDs.size() * BufferedUpdates.BYTES_PER_DEL_DOCID);
- pendingUpdates.deleteDocIDs.clear();
+ pendingUpdates.clearDeletedDocIds();
}
if (aborted) {
@@ -493,7 +492,7 @@ final class DocumentsWriterPerThread {
}
final BufferedUpdates segmentDeletes;
- if (pendingUpdates.deleteQueries.isEmpty() && pendingUpdates.numericUpdates.isEmpty() && pendingUpdates.binaryUpdates.isEmpty()) {
+ if (pendingUpdates.deleteQueries.isEmpty() && pendingUpdates.numFieldUpdates.get() == 0) {
pendingUpdates.clear();
segmentDeletes = null;
} else {
@@ -636,7 +635,7 @@ final class DocumentsWriterPerThread {
}
long bytesUsed() {
- return bytesUsed.get() + pendingUpdates.bytesUsed.get();
+ return bytesUsed.get() + pendingUpdates.ramBytesUsed();
}
/* Initial chunks size of the shared byte[] blocks used to
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b0e6a92e/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java b/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java
new file mode 100644
index 0000000..acfa88e
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/index/FieldUpdatesBuffer.java
@@ -0,0 +1,280 @@
+/*
+ * 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.lucene.index;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefArray;
+import org.apache.lucene.util.BytesRefIterator;
+import org.apache.lucene.util.Counter;
+import org.apache.lucene.util.FixedBitSet;
+import org.apache.lucene.util.RamUsageEstimator;
+
+/**
+ * This class efficiently buffers numeric and binary field updates and stores
+ * terms, values and metadata in a memory efficient way without creating large amounts
+ * of objects. Update terms are stored without de-duplicating the update term.
+ * In general we try to optimize for several use-cases. For instance we try to use constant
+ * space for update terms field since the common case always updates on the same field. Also for docUpTo
+ * we try to optimize for the case when updates should be applied to all docs ie. docUpTo=Integer.MAX_VALUE.
+ * In other cases each update will likely have a different docUpTo.
+ * Along the same lines this impl optimizes the case when all updates have a value. Lastly, if all updates share the
+ * same value for a numeric field we only store the value once.
+ */
+final class FieldUpdatesBuffer {
+ private static final long SELF_SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(FieldUpdatesBuffer.class);
+ private static final long STRING_SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(String.class);
+ private final Counter bytesUsed;
+ private int numUpdates = 1;
+ // we use a very simple approach and store the update term values without de-duplication
+ // which is also not a common case to keep updating the same value more than once...
+ // we might pay a higher price in terms of memory in certain cases but will gain
+ // on CPU for those. We also save on not needing to sort in order to apply the terms in order
+ // since by definition we store them in order.
+ private final BytesRefArray termValues;
+ private final BytesRefArray byteValues; // this will be null if we are buffering numerics
+ private int[] docsUpTo;
+ private long[] numericValues; // this will be null if we are buffering binaries
+ private FixedBitSet hasValues;
+ private String[] fields;
+ private final boolean isNumeric;
+
+ private FieldUpdatesBuffer(Counter bytesUsed, DocValuesUpdate initialValue, int docUpTo, boolean isNumeric) {
+ this.bytesUsed = bytesUsed;
+ this.bytesUsed.addAndGet(SELF_SHALLOW_SIZE);
+ termValues = new BytesRefArray(bytesUsed);
+ termValues.append(initialValue.term.bytes);
+ fields = new String[] {initialValue.term.field};
+ bytesUsed.addAndGet(sizeOfString(initialValue.term.field));
+ docsUpTo = new int[] {docUpTo};
+ if (initialValue.hasValue == false) {
+ hasValues = new FixedBitSet(1);
+ bytesUsed.addAndGet(hasValues.ramBytesUsed());
+ }
+ this.isNumeric = isNumeric;
+ byteValues = isNumeric ? null : new BytesRefArray(bytesUsed);
+ }
+
+ private static long sizeOfString(String string) {
+ return STRING_SHALLOW_SIZE + (string.length() * Character.BYTES);
+ }
+
+ FieldUpdatesBuffer(Counter bytesUsed, DocValuesUpdate.NumericDocValuesUpdate initialValue, int docUpTo) {
+ this(bytesUsed, initialValue, docUpTo, true);
+ if (initialValue.hasValue()) {
+ numericValues = new long[] {initialValue.getValue()};
+ } else {
+ numericValues = new long[] {0};
+ }
+ bytesUsed.addAndGet(Long.BYTES);
+ }
+
+ FieldUpdatesBuffer(Counter bytesUsed, DocValuesUpdate.BinaryDocValuesUpdate initialValue, int docUpTo) {
+ this(bytesUsed, initialValue, docUpTo, false);
+ if (initialValue.hasValue()) {
+ byteValues.append(initialValue.getValue());
+ }
+ }
+
+ void add(String field, int docUpTo, int ord, boolean hasValue) {
+ if (fields[0].equals(field) == false || fields.length != 1 ) {
+ if (fields.length <= ord) {
+ String[] array = ArrayUtil.grow(fields, ord+1);
+ if (fields.length == 1) {
+ Arrays.fill(array, 1, ord, fields[0]);
+ }
+ bytesUsed.addAndGet((array.length - fields.length) * RamUsageEstimator.NUM_BYTES_OBJECT_REF);
+ fields = array;
+ }
+ if (field != fields[0]) { // that's an easy win of not accounting if there is an outlier
+ bytesUsed.addAndGet(sizeOfString(field));
+ }
+ fields[ord] = field;
+ }
+
+ if (docsUpTo[0] != docUpTo || docsUpTo.length != 1) {
+ if (docsUpTo.length <= ord) {
+ int[] array = ArrayUtil.grow(docsUpTo, ord+1);
+ if (docsUpTo.length == 1) {
+ Arrays.fill(array, 1, ord, docsUpTo[0]);
+ }
+ bytesUsed.addAndGet((array.length-docsUpTo.length) * Integer.BYTES);
+ docsUpTo = array;
+ }
+ docsUpTo[ord] = docUpTo;
+ }
+
+ if (hasValue == false || hasValues != null) {
+ if (hasValues == null) {
+ hasValues = new FixedBitSet(ord+1);
+ hasValues.set(0, ord);
+ bytesUsed.addAndGet(hasValues.ramBytesUsed());
+ } else if (hasValues.length() <= ord) {
+ FixedBitSet fixedBitSet = FixedBitSet.ensureCapacity(hasValues, ArrayUtil.oversize(ord + 1, 1));
+ bytesUsed.addAndGet(fixedBitSet.ramBytesUsed()-hasValues.ramBytesUsed());
+ hasValues = fixedBitSet;
+ }
+ if (hasValue) {
+ hasValues.set(ord);
+ }
+ }
+ }
+
+ void addUpdate(Term term, long value, int docUpTo) {
+ assert isNumeric;
+ final int ord = append(term);
+ String field = term.field;
+ add(field, docUpTo, ord, true);
+ if (numericValues[0] != value || numericValues.length != 1) {
+ if (numericValues.length <= ord) {
+ long[] array = ArrayUtil.grow(numericValues, ord+1);
+ if (numericValues.length == 1) {
+ Arrays.fill(array, 1, ord, numericValues[0]);
+ }
+ bytesUsed.addAndGet((array.length-numericValues.length) * Long.BYTES);
+ numericValues = array;
+ }
+ numericValues[ord] = value;
+ }
+ }
+
+ void addNoValue(Term term, int docUpTo) {
+ final int ord = append(term);
+ add(term.field, docUpTo, ord, false);
+ }
+
+ void addUpdate(Term term, BytesRef value, int docUpTo) {
+ assert isNumeric == false;
+ final int ord = append(term);
+ byteValues.append(value);
+ add(term.field, docUpTo, ord, true);
+ }
+
+ private int append(Term term) {
+ termValues.append(term.bytes);
+ return numUpdates++;
+ }
+
+ BufferedUpdateIterator iterator() {
+ return new BufferedUpdateIterator();
+ }
+
+ boolean isNumeric() {
+ assert isNumeric || byteValues != null;
+ return isNumeric;
+ }
+
+ /**
+ * Struct like class that is used to iterate over all updates in this buffer
+ */
+ static class BufferedUpdate {
+
+ private BufferedUpdate() {};
+ /**
+ * the max document ID this update should be applied to
+ */
+ int docUpTo;
+ /**
+ * a numeric value or 0 if this buffer holds binary updates
+ */
+ long numericValue;
+ /**
+ * a binary value or null if this buffer holds numeric updates
+ */
+ BytesRef binaryValue;
+ /**
+ * <code>true</code> if this update has a value
+ */
+ boolean hasValue;
+ /**
+ * The update terms field. This will never be null.
+ */
+ String termField;
+ /**
+ * The update terms value. This will never be null.
+ */
+ BytesRef termValue;
+
+ @Override
+ public int hashCode() {
+ throw new UnsupportedOperationException(
+ "this struct should not be use in map or other data-stuctures that use hashCode / equals");
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ throw new UnsupportedOperationException(
+ "this struct should not be use in map or other data-stuctures that use hashCode / equals");
+ }
+ }
+
+ /**
+ * An iterator that iterates over all updates in insertion order
+ */
+ class BufferedUpdateIterator {
+ private final BytesRefIterator termValuesIterator;
+ private final BytesRefIterator byteValuesIterator;
+ private final BufferedUpdate bufferedUpdate = new BufferedUpdate();
+ private final Bits updatesWithValue;
+ private int index = 0;
+
+ BufferedUpdateIterator() {
+ this.termValuesIterator = termValues.iterator();
+ this.byteValuesIterator = isNumeric ? null : byteValues.iterator();
+ updatesWithValue = hasValues == null ? new Bits.MatchAllBits(numUpdates) : hasValues;
+ }
+
+ /**
+ * Moves to the next BufferedUpdate or return null if all updates are consumed.
+ * The returned instance is a shared instance and must be fully consumed before the next call to this method.
+ */
+ BufferedUpdate next() throws IOException {
+ BytesRef next = termValuesIterator.next();
+ if (next != null) {
+ final int idx = index++;
+ bufferedUpdate.termValue = next;
+ bufferedUpdate.hasValue = updatesWithValue.get(idx);
+ bufferedUpdate.termField = fields[getArrayIndex(fields.length, idx)];
+ bufferedUpdate.docUpTo = docsUpTo[getArrayIndex(docsUpTo.length, idx)];
+ if (bufferedUpdate.hasValue) {
+ if (isNumeric) {
+ bufferedUpdate.numericValue = numericValues[getArrayIndex(numericValues.length, idx)];
+ bufferedUpdate.binaryValue = null;
+ } else {
+ bufferedUpdate.binaryValue = byteValuesIterator.next();
+ }
+ } else {
+ bufferedUpdate.binaryValue = null;
+ bufferedUpdate.numericValue = 0;
+ }
+ return bufferedUpdate;
+ } else {
+ return null;
+ }
+ }
+ }
+
+ private static int getArrayIndex(int arrayLength, int index) {
+ assert arrayLength == 1 || arrayLength > index : "illegal array index length: " + arrayLength + " index: " + index;
+ return Math.min(arrayLength-1, index);
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b0e6a92e/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 7743896..266db31 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java
@@ -23,7 +23,6 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -33,20 +32,15 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntConsumer;
-import org.apache.lucene.index.DocValuesUpdate.BinaryDocValuesUpdate;
-import org.apache.lucene.index.DocValuesUpdate.NumericDocValuesUpdate;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreMode;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
-import org.apache.lucene.store.ByteArrayDataInput;
-import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.Counter;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.RamUsageEstimator;
@@ -73,21 +67,14 @@ final class FrozenBufferedUpdates {
final Query[] deleteQueries;
final int[] deleteQueryLimits;
- // numeric DV update term and their updates
- final byte[] numericDVUpdates;
-
- // binary DV update term and their updates
- final byte[] binaryDVUpdates;
-
- private final int numericDVUpdateCount;
- private final int binaryDVUpdateCount;
-
/** Counts down once all deletes/updates have been applied */
public final CountDownLatch applied = new CountDownLatch(1);
private final ReentrantLock applyLock = new ReentrantLock();
+ private final Map<String, FieldUpdatesBuffer> fieldUpdates;
/** How many total documents were deleted/updated. */
public long totalDelCount;
+ private final int fieldUpdatesCount;
final int bytesUsed;
final int numTermDeletes;
@@ -120,80 +107,25 @@ final class FrozenBufferedUpdates {
deleteQueryLimits[upto] = ent.getValue();
upto++;
}
- Counter counter = Counter.newCounter();
// TODO if a Term affects multiple fields, we could keep the updates key'd by Term
// so that it maps to all fields it affects, sorted by their docUpto, and traverse
// that Term only once, applying the update to all fields that still need to be
// updated.
- numericDVUpdates = freezeDVUpdates(updates.numericUpdates, counter::addAndGet);
- numericDVUpdateCount = (int)counter.get();
- counter.addAndGet(-counter.get());
- assert counter.get() == 0;
- // TODO if a Term affects multiple fields, we could keep the updates key'd by Term
- // so that it maps to all fields it affects, sorted by their docUpto, and traverse
- // that Term only once, applying the update to all fields that still need to be
- // updated.
- binaryDVUpdates = freezeDVUpdates(updates.binaryUpdates, counter::addAndGet);
- binaryDVUpdateCount = (int)counter.get();
+ this.fieldUpdates = Collections.unmodifiableMap(new HashMap<>(updates.fieldUpdates));
+ this.fieldUpdatesCount = updates.numFieldUpdates.get();
- bytesUsed = (int) (deleteTerms.ramBytesUsed() + deleteQueries.length * BYTES_PER_DEL_QUERY
- + numericDVUpdates.length + binaryDVUpdates.length);
+ bytesUsed = (int) ((deleteTerms.ramBytesUsed() + deleteQueries.length * BYTES_PER_DEL_QUERY)
+ + updates.fieldUpdatesBytesUsed.get());
numTermDeletes = updates.numTermDeletes.get();
if (infoStream != null && infoStream.isEnabled("BD")) {
infoStream.message("BD", String.format(Locale.ROOT,
"compressed %d to %d bytes (%.2f%%) for deletes/updates; private segment %s",
- updates.bytesUsed.get(), bytesUsed, 100.*bytesUsed/updates.bytesUsed.get(),
+ updates.ramBytesUsed(), bytesUsed, 100.*bytesUsed/updates.ramBytesUsed(),
privateSegment));
}
}
- private static <T extends DocValuesUpdate> byte[] freezeDVUpdates(Map<String,LinkedHashMap<Term, T>> dvUpdates,
- IntConsumer updateSizeConsumer)
- throws IOException {
- // TODO: we could do better here, e.g. collate the updates by field
- // so if you are updating 2 fields interleaved we don't keep writing the field strings
- try (RAMOutputStream out = new RAMOutputStream()) {
- String lastTermField = null;
- String lastUpdateField = null;
- for (LinkedHashMap<Term, T> updates : dvUpdates.values()) {
- updateSizeConsumer.accept(updates.size());
- for (T update : updates.values()) {
- int code = update.term.bytes().length << 3;
-
- String termField = update.term.field();
- if (termField.equals(lastTermField) == false) {
- code |= 1;
- }
- String updateField = update.field;
- if (updateField.equals(lastUpdateField) == false) {
- code |= 2;
- }
- if (update.hasValue()) {
- code |= 4;
- }
- out.writeVInt(code);
- out.writeVInt(update.docIDUpto);
- if (termField.equals(lastTermField) == false) {
- out.writeString(termField);
- lastTermField = termField;
- }
- if (updateField.equals(lastUpdateField) == false) {
- out.writeString(updateField);
- lastUpdateField = updateField;
- }
- out.writeBytes(update.term.bytes().bytes, update.term.bytes().offset, update.term.bytes().length);
- if (update.hasValue()) {
- update.writeTo(out);
- }
- }
- }
- byte[] bytes = new byte[(int) out.getFilePointer()];
- out.writeTo(bytes, 0);
- return bytes;
- }
- }
-
/** Returns the {@link SegmentCommitInfo} that this packet is supposed to apply its deletes to, or null
* if the private segment was already merged away. */
private List<SegmentCommitInfo> getInfosToApply(IndexWriter writer) {
@@ -491,7 +423,7 @@ final class FrozenBufferedUpdates {
private long applyDocValuesUpdates(BufferedUpdatesStream.SegmentState[] segStates) throws IOException {
- if (numericDVUpdates.length == 0 && binaryDVUpdates.length == 0) {
+ if (fieldUpdates.isEmpty()) {
return 0;
}
@@ -513,33 +445,30 @@ final class FrozenBufferedUpdates {
continue;
}
final boolean isSegmentPrivateDeletes = privateSegment != null;
- if (numericDVUpdates.length > 0) {
- updateCount += applyDocValuesUpdates(segState, numericDVUpdates, true, delGen, isSegmentPrivateDeletes);
+ if (fieldUpdates.isEmpty() == false) {
+ updateCount += applyDocValuesUpdates(segState, fieldUpdates, delGen, isSegmentPrivateDeletes);
}
- if (binaryDVUpdates.length > 0) {
- updateCount += applyDocValuesUpdates(segState, binaryDVUpdates, false, delGen, isSegmentPrivateDeletes);
- }
}
if (infoStream.isEnabled("BD")) {
infoStream.message("BD",
- String.format(Locale.ROOT, "applyDocValuesUpdates %.1f msec for %d segments, %d numeric updates and %d binary updates; %d new updates",
+ String.format(Locale.ROOT, "applyDocValuesUpdates %.1f msec for %d segments, %d field updates; %d new updates",
(System.nanoTime()-startNS)/1000000.,
segStates.length,
- numericDVUpdateCount,
- binaryDVUpdateCount,
+ fieldUpdatesCount,
updateCount));
}
return updateCount;
}
- private static long applyDocValuesUpdates(BufferedUpdatesStream.SegmentState segState, byte[] updates,
- boolean isNumeric, long delGen,
+ private static long applyDocValuesUpdates(BufferedUpdatesStream.SegmentState segState,
+ Map<String, FieldUpdatesBuffer> updates,
+ long delGen,
boolean segmentPrivateDeletes) throws IOException {
- TermsEnum termsEnum = null;
+ TermsEnum termsEnum;
PostingsEnum postingsEnum = null;
// TODO: we can process the updates per DV field, from last to first so that
@@ -556,126 +485,96 @@ final class FrozenBufferedUpdates {
// We first write all our updates private, and only in the end publish to the ReadersAndUpdates */
Map<String, DocValuesFieldUpdates> holder = new HashMap<>();
-
- ByteArrayDataInput in = new ByteArrayDataInput(updates);
-
- String termField = null;
- String updateField = null;
- BytesRef term = new BytesRef();
- term.bytes = new byte[16];
-
- BytesRef scratch = new BytesRef();
- scratch.bytes = new byte[16];
-
- while (in.getPosition() != updates.length) {
- int code = in.readVInt();
- int docIDUpto = in.readVInt();
- term.length = code >> 3;
-
- if ((code & 1) != 0) {
- termField = in.readString();
- }
- if ((code & 2) != 0) {
- updateField = in.readString();
- }
- boolean hasValue = (code & 4) != 0;
-
- if (term.bytes.length < term.length) {
- term.bytes = ArrayUtil.grow(term.bytes, term.length);
- }
- in.readBytes(term.bytes, 0, term.length);
-
- final int limit;
- if (delGen == segState.delGen) {
- assert segmentPrivateDeletes;
- limit = docIDUpto;
- } else {
- limit = Integer.MAX_VALUE;
- }
-
- // TODO: we traverse the terms in update order (not term order) so that we
- // apply the updates in the correct order, i.e. if two terms update the
- // same document, the last one that came in wins, irrespective of the
- // terms lexical order.
- // we can apply the updates in terms order if we keep an updatesGen (and
- // increment it with every update) and attach it to each NumericUpdate. Note
- // that we cannot rely only on docIDUpto because an app may send two updates
- // which will get same docIDUpto, yet will still need to respect the order
- // those updates arrived.
-
- // TODO: we could at least *collate* by field?
-
- // This is the field used to resolve to docIDs, e.g. an "id" field, not the doc values field we are updating!
- if ((code & 1) != 0) {
- Terms terms = segState.reader.terms(termField);
+ for (Map.Entry<String, FieldUpdatesBuffer> fieldUpdate : updates.entrySet()) {
+ String updateField = fieldUpdate.getKey();
+ FieldUpdatesBuffer value = fieldUpdate.getValue();
+ boolean isNumeric = value.isNumeric();
+ FieldUpdatesBuffer.BufferedUpdateIterator iterator = value.iterator();
+ FieldUpdatesBuffer.BufferedUpdate bufferedUpdate;
+ while ((bufferedUpdate = iterator.next()) != null) {
+ Terms terms = segState.reader.terms(bufferedUpdate.termField);
if (terms != null) {
termsEnum = terms.iterator();
} else {
- termsEnum = null;
+ // no terms in this segment for this field
+ continue;
}
- }
- final BytesRef binaryValue;
- final long longValue;
- if (hasValue == false) {
- longValue = -1;
- binaryValue = null;
- } else if (isNumeric) {
- longValue = NumericDocValuesUpdate.readFrom(in);
- binaryValue = null;
- } else {
- longValue = -1;
- binaryValue = BinaryDocValuesUpdate.readFrom(in, scratch);
- }
-
- if (termsEnum == null) {
- // no terms in this segment for this field
- continue;
- }
-
- if (termsEnum.seekExact(term)) {
- // we don't need term frequencies for this
- postingsEnum = termsEnum.postings(postingsEnum, PostingsEnum.NONE);
- DocValuesFieldUpdates dvUpdates = holder.get(updateField);
- if (dvUpdates == null) {
- if (isNumeric) {
- dvUpdates = new NumericDocValuesFieldUpdates(delGen, updateField, segState.reader.maxDoc());
- } else {
- dvUpdates = new BinaryDocValuesFieldUpdates(delGen, updateField, segState.reader.maxDoc());
- }
- holder.put(updateField, dvUpdates);
+ final int limit;
+ if (delGen == segState.delGen) {
+ assert segmentPrivateDeletes;
+ limit = bufferedUpdate.docUpTo;
+ } else {
+ limit = Integer.MAX_VALUE;
}
- final IntConsumer docIdConsumer;
- final DocValuesFieldUpdates update = dvUpdates;
- if (hasValue == false) {
- docIdConsumer = doc -> update.reset(doc);
- } else if (isNumeric) {
- docIdConsumer = doc -> update.add(doc, longValue);
+
+ // TODO: we traverse the terms in update order (not term order) so that we
+ // apply the updates in the correct order, i.e. if two terms update the
+ // same document, the last one that came in wins, irrespective of the
+ // terms lexical order.
+ // we can apply the updates in terms order if we keep an updatesGen (and
+ // increment it with every update) and attach it to each NumericUpdate. Note
+ // that we cannot rely only on docIDUpto because an app may send two updates
+ // which will get same docIDUpto, yet will still need to respect the order
+ // those updates arrived.
+
+ // TODO: we could at least *collate* by field?
+
+
+ final BytesRef binaryValue;
+ final long longValue;
+ if (bufferedUpdate.hasValue == false) {
+ longValue = -1;
+ binaryValue = null;
} else {
- docIdConsumer = doc -> update.add(doc, binaryValue);
+ longValue = bufferedUpdate.numericValue;
+ binaryValue = bufferedUpdate.binaryValue;
}
- final Bits acceptDocs = segState.rld.getLiveDocs();
- if (segState.rld.sortMap != null && segmentPrivateDeletes) {
- // This segment was sorted on flush; we must apply seg-private deletes carefully in this case:
- int doc;
- while ((doc = postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
- if (acceptDocs == null || acceptDocs.get(doc)) {
- // The limit is in the pre-sorted doc space:
- if (segState.rld.sortMap.newToOld(doc) < limit) {
- docIdConsumer.accept(doc);
- updateCount++;
- }
+
+ if (termsEnum.seekExact(bufferedUpdate.termValue)) {
+ // we don't need term frequencies for this
+ postingsEnum = termsEnum.postings(postingsEnum, PostingsEnum.NONE);
+ DocValuesFieldUpdates dvUpdates = holder.get(updateField);
+ if (dvUpdates == null) {
+ if (isNumeric) {
+ dvUpdates = new NumericDocValuesFieldUpdates(delGen, updateField, segState.reader.maxDoc());
+ } else {
+ dvUpdates = new BinaryDocValuesFieldUpdates(delGen, updateField, segState.reader.maxDoc());
}
+ holder.put(updateField, dvUpdates);
}
- } else {
- int doc;
- while ((doc = postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
- if (doc >= limit) {
- break; // no more docs that can be updated for this term
+ final IntConsumer docIdConsumer;
+ final DocValuesFieldUpdates update = dvUpdates;
+ if (bufferedUpdate.hasValue == false) {
+ docIdConsumer = doc -> update.reset(doc);
+ } else if (isNumeric) {
+ docIdConsumer = doc -> update.add(doc, longValue);
+ } else {
+ docIdConsumer = doc -> update.add(doc, binaryValue);
+ }
+ final Bits acceptDocs = segState.rld.getLiveDocs();
+ if (segState.rld.sortMap != null && segmentPrivateDeletes) {
+ // This segment was sorted on flush; we must apply seg-private deletes carefully in this case:
+ int doc;
+ while ((doc = postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ if (acceptDocs == null || acceptDocs.get(doc)) {
+ // The limit is in the pre-sorted doc space:
+ if (segState.rld.sortMap.newToOld(doc) < limit) {
+ docIdConsumer.accept(doc);
+ updateCount++;
+ }
+ }
}
- if (acceptDocs == null || acceptDocs.get(doc)) {
- docIdConsumer.accept(doc);
- updateCount++;
+ } else {
+ int doc;
+ while ((doc = postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ if (doc >= limit) {
+ break; // no more docs that can be updated for this term
+ }
+ if (acceptDocs == null || acceptDocs.get(doc)) {
+ docIdConsumer.accept(doc);
+ updateCount++;
+ }
}
}
}
@@ -896,11 +795,8 @@ final class FrozenBufferedUpdates {
if (deleteQueries.length != 0) {
s += " numDeleteQueries=" + deleteQueries.length;
}
- if (numericDVUpdates.length > 0) {
- s += " numNumericDVUpdates=" + numericDVUpdateCount;
- }
- if (binaryDVUpdates.length > 0) {
- s += " numBinaryDVUpdates=" + binaryDVUpdateCount;
+ if (fieldUpdates.size() > 0) {
+ s += " fieldUpdates=" + fieldUpdatesCount;
}
if (bytesUsed != 0) {
s += " bytesUsed=" + bytesUsed;
@@ -913,6 +809,6 @@ final class FrozenBufferedUpdates {
}
boolean any() {
- return deleteTerms.size() > 0 || deleteQueries.length > 0 || numericDVUpdates.length > 0 || binaryDVUpdates.length > 0;
+ return deleteTerms.size() > 0 || deleteQueries.length > 0 || fieldUpdatesCount > 0 ;
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b0e6a92e/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java b/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java
new file mode 100644
index 0000000..ae4442f
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/index/TestFieldUpdatesBuffer.java
@@ -0,0 +1,231 @@
+/*
+ * 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.lucene.index;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import com.carrotsearch.randomizedtesting.generators.RandomPicks;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.Counter;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.TestUtil;
+
+public class TestFieldUpdatesBuffer extends LuceneTestCase {
+
+ public void testBascis() throws IOException {
+ Counter counter = Counter.newCounter();
+ DocValuesUpdate.NumericDocValuesUpdate update =
+ new DocValuesUpdate.NumericDocValuesUpdate(new Term("id", "1"), "age", 6);
+ FieldUpdatesBuffer buffer = new FieldUpdatesBuffer(counter, update, 15);
+ buffer.addUpdate(new Term("id", "10"), 6, 15);
+ buffer.addUpdate(new Term("id", "8"), 12, 15);
+ buffer.addUpdate(new Term("some_other_field", "8"), 13, 17);
+ buffer.addUpdate(new Term("id", "8"), 12, 16);
+ assertTrue(buffer.isNumeric());
+ FieldUpdatesBuffer.BufferedUpdateIterator iterator = buffer.iterator();
+ FieldUpdatesBuffer.BufferedUpdate value = iterator.next();
+ assertNotNull(value);
+ assertEquals("id", value.termField);
+ assertEquals("1", value.termValue.utf8ToString());
+ assertEquals(6, value.numericValue);
+ assertEquals(15, value.docUpTo);
+
+ value = iterator.next();
+ assertNotNull(value);
+ assertEquals("id", value.termField);
+ assertEquals("10", value.termValue.utf8ToString());
+ assertEquals(6, value.numericValue);
+ assertEquals(15, value.docUpTo);
+
+ value = iterator.next();
+ assertNotNull(value);
+ assertEquals("id", value.termField);
+ assertEquals("8", value.termValue.utf8ToString());
+ assertEquals(12, value.numericValue);
+ assertEquals(15, value.docUpTo);
+
+ value = iterator.next();
+ assertNotNull(value);
+ assertEquals("some_other_field", value.termField);
+ assertEquals("8", value.termValue.utf8ToString());
+ assertEquals(13, value.numericValue);
+ assertEquals(17, value.docUpTo);
+
+ value = iterator.next();
+ assertNotNull(value);
+ assertEquals("id", value.termField);
+ assertEquals("8", value.termValue.utf8ToString());
+ assertEquals(12, value.numericValue);
+ assertEquals(16, value.docUpTo);
+ assertNull(iterator.next());
+ }
+
+ public void testUpdateShareValues() throws IOException {
+ Counter counter = Counter.newCounter();
+ int intValue = random().nextInt();
+ boolean valueForThree = random().nextBoolean();
+ DocValuesUpdate.NumericDocValuesUpdate update =
+ new DocValuesUpdate.NumericDocValuesUpdate(new Term("id", "0"), "enabled", intValue);
+ FieldUpdatesBuffer buffer = new FieldUpdatesBuffer(counter, update, Integer.MAX_VALUE);
+ buffer.addUpdate(new Term("id", "1"), intValue, Integer.MAX_VALUE);
+ buffer.addUpdate(new Term("id", "2"), intValue, Integer.MAX_VALUE);
+ if (valueForThree) {
+ buffer.addUpdate(new Term("id", "3"), intValue, Integer.MAX_VALUE);
+ } else {
+ buffer.addNoValue(new Term("id", "3"), Integer.MAX_VALUE);
+ }
+ buffer.addUpdate(new Term("id", "4"), intValue, Integer.MAX_VALUE);
+ FieldUpdatesBuffer.BufferedUpdateIterator iterator = buffer.iterator();
+ FieldUpdatesBuffer.BufferedUpdate value;
+ int count = 0;
+ while ((value = iterator.next()) != null) {
+ boolean hasValue = count != 3 || valueForThree;
+ assertEquals("" + (count++), value.termValue.utf8ToString());
+ assertEquals("id", value.termField);
+ assertEquals(hasValue, value.hasValue);
+ if (hasValue) {
+ assertEquals(intValue, value.numericValue);
+ } else {
+ assertEquals(0, value.numericValue);
+ }
+ assertEquals(Integer.MAX_VALUE, value.docUpTo);
+ }
+ assertTrue(buffer.isNumeric());
+ }
+
+ public void testUpdateShareValuesBinary() throws IOException {
+ Counter counter = Counter.newCounter();
+ boolean valueForThree = random().nextBoolean();
+ DocValuesUpdate.BinaryDocValuesUpdate update =
+ new DocValuesUpdate.BinaryDocValuesUpdate(new Term("id", "0"), "enabled", new BytesRef(""));
+ FieldUpdatesBuffer buffer = new FieldUpdatesBuffer(counter, update, Integer.MAX_VALUE);
+ buffer.addUpdate(new Term("id", "1"), new BytesRef(""), Integer.MAX_VALUE);
+ buffer.addUpdate(new Term("id", "2"), new BytesRef(""), Integer.MAX_VALUE);
+ if (valueForThree) {
+ buffer.addUpdate(new Term("id", "3"), new BytesRef(""), Integer.MAX_VALUE);
+ } else {
+ buffer.addNoValue(new Term("id", "3"), Integer.MAX_VALUE);
+ }
+ buffer.addUpdate(new Term("id", "4"), new BytesRef(""), Integer.MAX_VALUE);
+ FieldUpdatesBuffer.BufferedUpdateIterator iterator = buffer.iterator();
+ FieldUpdatesBuffer.BufferedUpdate value;
+ int count = 0;
+ while ((value = iterator.next()) != null) {
+ boolean hasValue = count != 3 || valueForThree;
+ assertEquals("" + (count++), value.termValue.utf8ToString());
+ assertEquals("id", value.termField);
+ assertEquals(hasValue, value.hasValue);
+ if (hasValue) {
+ assertEquals(new BytesRef(""), value.binaryValue);
+ } else {
+ assertNull(value.binaryValue);
+ }
+ assertEquals(Integer.MAX_VALUE, value.docUpTo);
+ }
+ assertFalse(buffer.isNumeric());
+ }
+
+ public <T extends DocValuesUpdate> T getRandomUpdate(boolean binary) {
+ String termField = RandomPicks.randomFrom(random(), Arrays.asList("id", "_id", "some_other_field"));
+ String docId = "" + random().nextInt(10);
+ if (binary) {
+ DocValuesUpdate.BinaryDocValuesUpdate value = new DocValuesUpdate.BinaryDocValuesUpdate(new Term(termField, docId), "binary",
+ rarely() ? null : new BytesRef(TestUtil.randomRealisticUnicodeString(random())));
+ return (T) (rarely() ? value.prepareForApply(random().nextInt(100)) : value);
+ } else {
+ DocValuesUpdate.NumericDocValuesUpdate value = new DocValuesUpdate.NumericDocValuesUpdate(new Term(termField, docId), "numeric",
+ rarely() ? null : Long.valueOf(random().nextInt(100)));
+
+ return (T) (rarely() ? value.prepareForApply(random().nextInt(100)) : value);
+ }
+ }
+
+ public void testBinaryRandom() throws IOException {
+ List<DocValuesUpdate.BinaryDocValuesUpdate> updates = new ArrayList<>();
+ int numUpdates = 1 + random().nextInt(1000);
+ Counter counter = Counter.newCounter();
+ DocValuesUpdate.BinaryDocValuesUpdate randomUpdate = getRandomUpdate(true);
+ updates.add(randomUpdate);
+ FieldUpdatesBuffer buffer = new FieldUpdatesBuffer(counter, randomUpdate, randomUpdate.docIDUpto);
+ for (int i = 0; i < numUpdates; i++) {
+ randomUpdate = getRandomUpdate(true);
+ updates.add(randomUpdate);
+ if (randomUpdate.hasValue) {
+ buffer.addUpdate(randomUpdate.term, randomUpdate.getValue(), randomUpdate.docIDUpto);
+ } else {
+ buffer.addNoValue(randomUpdate.term, randomUpdate.docIDUpto);
+ }
+ }
+ FieldUpdatesBuffer.BufferedUpdateIterator iterator = buffer.iterator();
+ FieldUpdatesBuffer.BufferedUpdate value;
+
+ int count = 0;
+ while ((value = iterator.next()) != null) {
+ randomUpdate = updates.get(count++);
+ assertEquals(randomUpdate.term.bytes.utf8ToString(), value.termValue.utf8ToString());
+ assertEquals(randomUpdate.term.field, value.termField);
+ assertEquals("count: " + count, randomUpdate.hasValue, value.hasValue);
+ if (randomUpdate.hasValue) {
+ assertEquals(randomUpdate.getValue(), value.binaryValue);
+ } else {
+ assertNull(value.binaryValue);
+ }
+ assertEquals(randomUpdate.docIDUpto, value.docUpTo);
+ }
+ assertEquals(count, updates.size());
+ }
+
+ public void testNumericRandom() throws IOException {
+ List<DocValuesUpdate.NumericDocValuesUpdate> updates = new ArrayList<>();
+ int numUpdates = 1 + random().nextInt(1000);
+ Counter counter = Counter.newCounter();
+ DocValuesUpdate.NumericDocValuesUpdate randomUpdate = getRandomUpdate(false);
+ updates.add(randomUpdate);
+ FieldUpdatesBuffer buffer = new FieldUpdatesBuffer(counter, randomUpdate, randomUpdate.docIDUpto);
+ for (int i = 0; i < numUpdates; i++) {
+ randomUpdate = getRandomUpdate(false);
+ updates.add(randomUpdate);
+ if (randomUpdate.hasValue) {
+ buffer.addUpdate(randomUpdate.term, randomUpdate.getValue(), randomUpdate.docIDUpto);
+ } else {
+ buffer.addNoValue(randomUpdate.term, randomUpdate.docIDUpto);
+ }
+ }
+ FieldUpdatesBuffer.BufferedUpdateIterator iterator = buffer.iterator();
+ FieldUpdatesBuffer.BufferedUpdate value;
+
+ int count = 0;
+ while ((value = iterator.next()) != null) {
+ randomUpdate = updates.get(count++);
+ assertEquals(randomUpdate.term.bytes.utf8ToString(), value.termValue.utf8ToString());
+ assertEquals(randomUpdate.term.field, value.termField);
+ assertEquals(randomUpdate.hasValue, value.hasValue);
+ if (randomUpdate.hasValue) {
+ assertEquals(randomUpdate.getValue(), value.numericValue);
+ } else {
+ assertEquals(0, value.numericValue);
+ }
+ assertEquals(randomUpdate.docIDUpto, value.docUpTo);
+ }
+ assertEquals(count, updates.size());
+ }
+
+}
[04/37] lucene-solr:jira/http2: SOLR-12555: Use `expectThrows` for
expected exceptions
Posted by da...@apache.org.
SOLR-12555: Use `expectThrows` for expected exceptions
This commit replaces the `try { doX(); fail(); }` pattern with the
`expectThrows` test helper, which was created for this purpose.
This commit makes these changes in the core package:
`o.a.solr.core`.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/6e4c9b3b
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/6e4c9b3b
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/6e4c9b3b
Branch: refs/heads/jira/http2
Commit: 6e4c9b3b58148a48f582095a5a51aca2a63d0d35
Parents: e5281ef
Author: Jason Gerlowski <ge...@apache.org>
Authored: Sat Dec 1 14:33:49 2018 -0500
Committer: Jason Gerlowski <ge...@apache.org>
Committed: Sat Dec 1 17:19:34 2018 -0500
----------------------------------------------------------------------
.../org/apache/solr/core/PluginInfoTest.java | 23 ++--
.../apache/solr/core/ResourceLoaderTest.java | 41 +++----
.../org/apache/solr/core/TestCodecSupport.java | 51 ++++----
.../test/org/apache/solr/core/TestConfig.java | 17 ++-
.../solr/core/TestConfigSetProperties.java | 16 +--
.../org/apache/solr/core/TestConfigSets.java | 15 +--
.../org/apache/solr/core/TestCoreContainer.java | 118 +++++++------------
.../org/apache/solr/core/TestCoreDiscovery.java | 62 ++++------
.../org/apache/solr/core/TestLazyCores.java | 15 +--
9 files changed, 141 insertions(+), 217 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java b/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java
index c0cfe56..a567eb2 100644
--- a/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java
+++ b/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java
@@ -63,15 +63,16 @@ public class PluginInfoTest extends DOMUtilTestBase {
@Test
public void testNameRequired() throws Exception {
Node nodeWithNoName = getNode("<plugin></plugin>", "plugin");
- SolrTestCaseJ4.ignoreException("missing mandatory attribute");
try {
- PluginInfo pi = new PluginInfo(nodeWithNoName, "Node with No name", true, false);
- fail("Exception should have been thrown");
- } catch (RuntimeException e) {
- assertTrue(e.getMessage().contains("missing mandatory attribute"));
+ SolrTestCaseJ4.ignoreException("missing mandatory attribute");
+ RuntimeException thrown = expectThrows(RuntimeException.class, () -> {
+ PluginInfo pi = new PluginInfo(nodeWithNoName, "Node with No name", true, false);
+ });
+ assertTrue(thrown.getMessage().contains("missing mandatory attribute"));
} finally {
SolrTestCaseJ4.resetExceptionIgnores();
}
+
Node nodeWithAName = getNode("<plugin name=\"myName\" />", "plugin");
PluginInfo pi2 = new PluginInfo(nodeWithAName, "Node with a Name", true, false);
assertTrue(pi2.name.equals("myName"));
@@ -80,16 +81,16 @@ public class PluginInfoTest extends DOMUtilTestBase {
@Test
public void testClassRequired() throws Exception {
Node nodeWithNoClass = getNode("<plugin></plugin>", "plugin");
- SolrTestCaseJ4.ignoreException("missing mandatory attribute");
try {
- @SuppressWarnings("unused")
- PluginInfo pi = new PluginInfo(nodeWithNoClass, "Node with No Class", false, true);
- fail("Exception should have been thrown");
- } catch (RuntimeException e) {
- assertTrue(e.getMessage().contains("missing mandatory attribute"));
+ SolrTestCaseJ4.ignoreException("missing mandatory attribute");
+ RuntimeException thrown = expectThrows(RuntimeException.class, () -> {
+ PluginInfo pi = new PluginInfo(nodeWithNoClass, "Node with No Class", false, true);
+ });
+ assertTrue(thrown.getMessage().contains("missing mandatory attribute"));
} finally {
SolrTestCaseJ4.resetExceptionIgnores();
}
+
Node nodeWithAClass = getNode("<plugin class=\"myName\" />", "plugin");
PluginInfo pi2 = new PluginInfo(nodeWithAClass, "Node with a Class", false, true);
assertTrue(pi2.className.equals("myName"));
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/ResourceLoaderTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/ResourceLoaderTest.java b/solr/core/src/test/org/apache/solr/core/ResourceLoaderTest.java
index dc06a6f..eb88dbb 100644
--- a/solr/core/src/test/org/apache/solr/core/ResourceLoaderTest.java
+++ b/solr/core/src/test/org/apache/solr/core/ResourceLoaderTest.java
@@ -29,7 +29,6 @@ import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
-import junit.framework.Assert;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.KeywordTokenizerFactory;
import org.apache.lucene.analysis.ngram.NGramFilterFactory;
@@ -59,6 +58,7 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
Files.write(temp.resolve("dummy.txt"), new byte[]{});
Path instanceDir = temp.resolve("instance");
Files.createDirectories(instanceDir.resolve("conf"));
+
try (SolrResourceLoader loader = new SolrResourceLoader(instanceDir)) {
loader.openResource("../../dummy.txt").close();
fail();
@@ -70,11 +70,11 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
public void testAwareCompatibility() throws Exception {
- Class<?> clazz = ResourceLoaderAware.class;
+ final Class<?> clazz1 = ResourceLoaderAware.class;
// Check ResourceLoaderAware valid objects
//noinspection unchecked
- assertAwareCompatibility(clazz, new NGramFilterFactory(map("minGramSize", "1", "maxGramSize", "2")));
- assertAwareCompatibility(clazz, new KeywordTokenizerFactory(new HashMap<>()));
+ assertAwareCompatibility(clazz1, new NGramFilterFactory(map("minGramSize", "1", "maxGramSize", "2")));
+ assertAwareCompatibility(clazz1, new KeywordTokenizerFactory(new HashMap<>()));
// Make sure it throws an error for invalid objects
Object[] invalid = new Object[] {
@@ -84,19 +84,15 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
new JSONResponseWriter()
};
for( Object obj : invalid ) {
- try {
- assertAwareCompatibility(clazz, obj);
- Assert.fail( "Should be invalid class: "+obj + " FOR " + clazz );
- }
- catch( SolrException ex ) { } // OK
+ expectThrows(SolrException.class, () -> assertAwareCompatibility(clazz1, obj));
}
- clazz = SolrCoreAware.class;
+ final Class<?> clazz2 = SolrCoreAware.class;
// Check ResourceLoaderAware valid objects
- assertAwareCompatibility(clazz, new LukeRequestHandler());
- assertAwareCompatibility(clazz, new FacetComponent());
- assertAwareCompatibility(clazz, new JSONResponseWriter());
+ assertAwareCompatibility(clazz2, new LukeRequestHandler());
+ assertAwareCompatibility(clazz2, new FacetComponent());
+ assertAwareCompatibility(clazz2, new JSONResponseWriter());
// Make sure it throws an error for invalid objects
//noinspection unchecked
@@ -106,13 +102,8 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
new KeywordTokenizerFactory(new HashMap<>())
};
for( Object obj : invalid ) {
- try {
- assertAwareCompatibility(clazz, obj);
- Assert.fail( "Should be invalid class: "+obj + " FOR " + clazz );
- }
- catch( SolrException ex ) { } // OK
+ expectThrows(SolrException.class, () -> assertAwareCompatibility(clazz2, obj));
}
-
}
public void testBOMMarkers() throws Exception {
@@ -145,15 +136,11 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
public void testWrongEncoding() throws Exception {
String wrongEncoding = "stopwordsWrongEncoding.txt";
- SolrResourceLoader loader = new SolrResourceLoader(TEST_PATH().resolve("collection1"));
- // ensure we get our exception
- try {
- loader.getLines(wrongEncoding);
- fail();
- } catch (SolrException expected) {
- assertTrue(expected.getCause() instanceof CharacterCodingException);
+ try(SolrResourceLoader loader = new SolrResourceLoader(TEST_PATH().resolve("collection1"))) {
+ // ensure we get our exception
+ SolrException thrown = expectThrows(SolrException.class, () -> loader.getLines(wrongEncoding));
+ assertTrue(thrown.getCause() instanceof CharacterCodingException);
}
- loader.close();
}
public void testClassLoaderLibs() throws Exception {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/TestCodecSupport.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/TestCodecSupport.java b/solr/core/src/test/org/apache/solr/core/TestCodecSupport.java
index 9d6d310..2da830f 100644
--- a/solr/core/src/test/org/apache/solr/core/TestCodecSupport.java
+++ b/solr/core/src/test/org/apache/solr/core/TestCodecSupport.java
@@ -159,39 +159,32 @@ public class TestCodecSupport extends SolrTestCaseJ4 {
}
public void testBadCompressionMode() throws Exception {
- try {
+ SolrException thrown = expectThrows(SolrException.class, () -> {
doTestCompressionMode("something_that_doesnt_exist", "something_that_doesnt_exist");
- fail("Expecting exception");
- } catch (SolrException e) {
- assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, e.code());
- assertTrue("Unexpected Exception message: " + e.getMessage(),
- e.getMessage().contains("Unable to reload core"));
- }
+ });
+ assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, thrown.code());
+ assertTrue("Unexpected Exception message: " + thrown.getMessage(),
+ thrown.getMessage().contains("Unable to reload core"));
- SchemaCodecFactory factory = new SchemaCodecFactory();
- NamedList<String> nl = new NamedList<>();
+ final SchemaCodecFactory factory1 = new SchemaCodecFactory();
+ final NamedList<String> nl = new NamedList<>();
nl.add(SchemaCodecFactory.COMPRESSION_MODE, "something_that_doesnt_exist");
- try {
- factory.init(nl);
- fail("Expecting exception");
- } catch (SolrException e) {
- assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, e.code());
- assertTrue("Unexpected Exception message: " + e.getMessage(),
- e.getMessage().contains("Invalid compressionMode: 'something_that_doesnt_exist'"));
- }
-
- factory = new SchemaCodecFactory();
- nl = new NamedList<>();
- nl.add(SchemaCodecFactory.COMPRESSION_MODE, "");
- try {
- factory.init(nl);
- fail("Expecting exception");
- } catch (SolrException e) {
- assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, e.code());
- assertTrue("Unexpected Exception message: " + e.getMessage(),
- e.getMessage().contains("Invalid compressionMode: ''"));
- }
+ thrown = expectThrows(SolrException.class, () -> {
+ factory1.init(nl);
+ });
+ assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, thrown.code());
+ assertTrue("Unexpected Exception message: " + thrown.getMessage(),
+ thrown.getMessage().contains("Invalid compressionMode: 'something_that_doesnt_exist'"));
+ final SchemaCodecFactory factory2 = new SchemaCodecFactory();
+ final NamedList<String> nl2 = new NamedList<>();
+ nl2.add(SchemaCodecFactory.COMPRESSION_MODE, "");
+ thrown = expectThrows(SolrException.class, () -> {
+ factory2.init(nl2);
+ });
+ assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, thrown.code());
+ assertTrue("Unexpected Exception message: " + thrown.getMessage(),
+ thrown.getMessage().contains("Invalid compressionMode: ''"));
}
public void testCompressionModeDefault() throws IOException {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/TestConfig.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/TestConfig.java b/solr/core/src/test/org/apache/solr/core/TestConfig.java
index aa43c25..57c2223 100644
--- a/solr/core/src/test/org/apache/solr/core/TestConfig.java
+++ b/solr/core/src/test/org/apache/solr/core/TestConfig.java
@@ -196,18 +196,15 @@ public class TestConfig extends SolrTestCaseJ4 {
Assert.assertEquals(-1, SolrConfig.convertHeapOptionStyleConfigStringToBytes(""));
// Invalid values
- try {
+ RuntimeException thrown = expectThrows(RuntimeException.class, () -> {
SolrConfig.convertHeapOptionStyleConfigStringToBytes("3jbk32k"); // valid suffix but non-numeric prefix
- Assert.fail();
- } catch (RuntimeException e) {
- Assert.assertTrue(e.getMessage().contains("Invalid"));
- }
- try {
+ });
+ assertTrue(thrown.getMessage().contains("Invalid"));
+
+ thrown = expectThrows(RuntimeException.class, () -> {
SolrConfig.convertHeapOptionStyleConfigStringToBytes("300x"); // valid prefix but invalid suffix
- Assert.fail();
- } catch (RuntimeException e) {
- Assert.assertTrue(e.getMessage().contains("Invalid"));
- }
+ });
+ assertTrue(thrown.getMessage().contains("Invalid"));
}
@Test
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/TestConfigSetProperties.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/TestConfigSetProperties.java b/solr/core/src/test/org/apache/solr/core/TestConfigSetProperties.java
index 4c22771..bdabb07 100644
--- a/solr/core/src/test/org/apache/solr/core/TestConfigSetProperties.java
+++ b/solr/core/src/test/org/apache/solr/core/TestConfigSetProperties.java
@@ -46,22 +46,18 @@ public class TestConfigSetProperties extends SolrTestCaseJ4 {
@Test
public void testEmptyConfigSetProperties() throws Exception {
- try {
+ SolrException thrown = expectThrows(SolrException.class, () -> {
createConfigSetProps("");
- fail("Excepted SolrException");
- } catch (SolrException ex) {
- assertEquals(ErrorCode.SERVER_ERROR.code, ex.code());
- }
+ });
+ assertEquals(ErrorCode.SERVER_ERROR.code, thrown.code());
}
@Test
public void testConfigSetPropertiesNotMap() throws Exception {
- try {
+ SolrException thrown = expectThrows(SolrException.class, () -> {
createConfigSetProps(JSONUtil.toJSON(new String[] {"test"}));
- fail("Expected SolrException");
- } catch (SolrException ex) {
- assertEquals(ErrorCode.SERVER_ERROR.code, ex.code());
- }
+ });
+ assertEquals(ErrorCode.SERVER_ERROR.code, thrown.code());
}
@Test
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/TestConfigSets.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/TestConfigSets.java b/solr/core/src/test/org/apache/solr/core/TestConfigSets.java
index ae11fd6..b0d8212 100644
--- a/solr/core/src/test/org/apache/solr/core/TestConfigSets.java
+++ b/solr/core/src/test/org/apache/solr/core/TestConfigSets.java
@@ -88,19 +88,16 @@ public class TestConfigSets extends SolrTestCaseJ4 {
@Test
public void testNonExistentConfigSetThrowsException() {
- CoreContainer container = null;
+ final CoreContainer container = setupContainer(getFile("solr/configsets").getAbsolutePath());
try {
- container = setupContainer(getFile("solr/configsets").getAbsolutePath());
Path testDirectory = container.getResourceLoader().getInstancePath();
- container.create("core1", ImmutableMap.of("configSet", "nonexistent"));
- fail("Expected core creation to fail");
- }
- catch (Exception e) {
- Throwable wrappedException = getWrappedException(e);
+ Exception thrown = expectThrows(Exception.class, "Expected core creation to fail", () -> {
+ container.create("core1", ImmutableMap.of("configSet", "nonexistent"));
+ });
+ Throwable wrappedException = getWrappedException(thrown);
assertThat(wrappedException.getMessage(), containsString("nonexistent"));
- }
- finally {
+ } finally {
if (container != null)
container.shutdown();
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java
index cbef887..d492d73 100644
--- a/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java
+++ b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java
@@ -166,26 +166,17 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
assertEquals("There should not be cores", 0, cores.getCores().size());
// try and remove a core that does not exist
- try {
+ SolrException thrown = expectThrows(SolrException.class, () -> {
cores.unload("non_existent_core");
- fail("Should have thrown an exception when unloading a non-existent core");
- }
- catch (SolrException e) {
- assertThat(e.getMessage(), containsString("Cannot unload non-existent core [non_existent_core]"));
- }
+ });
+ assertThat(thrown.getMessage(), containsString("Cannot unload non-existent core [non_existent_core]"));
+
// try and remove a null core
- try {
+ thrown = expectThrows(SolrException.class, () -> {
cores.unload(null);
- fail("Should have thrown an exception when unloading a null core");
- }
- catch (Exception e) {
- if (!(e instanceof SolrException)) {
- fail("Should not have thrown SolrException but got " + e);
- }
- assertThat(e.getMessage(), containsString("Cannot unload non-existent core [null]"));
- }
-
+ });
+ assertThat(thrown.getMessage(), containsString("Cannot unload non-existent core [null]"));
} finally {
cores.shutdown();
}
@@ -411,16 +402,13 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// -----
// try to add a collection with a configset that doesn't exist
- try {
- ignoreException(Pattern.quote("bogus_path"));
+ ignoreException(Pattern.quote("bogus_path"));
+ SolrException thrown = expectThrows(SolrException.class, () -> {
cc.create("bogus", ImmutableMap.of("configSet", "bogus_path"));
- fail("bogus inst dir failed to trigger exception from create");
- } catch (SolrException e) {
- Throwable cause = Throwables.getRootCause(e);
- assertTrue("init exception doesn't mention bogus dir: " + cause.getMessage(),
- 0 < cause.getMessage().indexOf("bogus_path"));
-
- }
+ });
+ Throwable rootCause = Throwables.getRootCause(thrown);
+ assertTrue("init exception doesn't mention bogus dir: " + rootCause.getMessage(),
+ 0 < rootCause.getMessage().indexOf("bogus_path"));
// check that we have the cores we expect
cores = cc.getLoadedCoreNames();
@@ -439,16 +427,13 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// check that we get null accessing a non-existent core
assertNull(cc.getCore("does_not_exist"));
// check that we get a 500 accessing the core with an init failure
- try {
+ thrown = expectThrows(SolrException.class, () -> {
SolrCore c = cc.getCore("bogus");
- fail("Failed to get Exception on accessing core with init failure");
- } catch (SolrException ex) {
- assertEquals(500, ex.code());
- String cause = Throwables.getRootCause(ex).getMessage();
- assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
- 0 < cause.indexOf("bogus_path"));
-
- }
+ });
+ assertEquals(500, thrown.code());
+ String cause = Throwables.getRootCause(thrown).getMessage();
+ assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
+ 0 < cause.indexOf("bogus_path"));
cc.shutdown();
}
@@ -494,16 +479,12 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// check that we get null accessing a non-existent core
assertNull(cc.getCore("does_not_exist"));
// check that we get a 500 accessing the core with an init failure
- try {
+ SolrException thrown = expectThrows(SolrException.class, () -> {
SolrCore c = cc.getCore("col_bad");
- fail("Failed to get Exception on accessing core with init failure");
- } catch (SolrException ex) {
- assertEquals(500, ex.code());
- // double wrapped
- String cause = ex.getCause().getCause().getMessage();
- assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
- 0 < cause.indexOf("DummyMergePolicy"));
- }
+ });
+ assertEquals(500, thrown.code());
+ String cause = thrown.getCause().getCause().getMessage();
+ assertTrue("getCore() ex cause doesn't mention init fail: " + cause, 0 < cause.indexOf("DummyMergePolicy"));
// -----
// "fix" the bad collection
@@ -528,15 +509,12 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// -----
// try to add a collection with a path that doesn't exist
- try {
- ignoreException(Pattern.quote("bogus_path"));
+ ignoreException(Pattern.quote("bogus_path"));
+ thrown = expectThrows(SolrException.class, () -> {
cc.create("bogus", ImmutableMap.of("configSet", "bogus_path"));
- fail("bogus inst dir failed to trigger exception from create");
- } catch (SolrException e) {
- assertTrue("init exception doesn't mention bogus dir: " + e.getCause().getCause().getMessage(),
- 0 < e.getCause().getCause().getMessage().indexOf("bogus_path"));
-
- }
+ });
+ assertTrue("init exception doesn't mention bogus dir: " + thrown.getCause().getCause().getMessage(),
+ 0 < thrown.getCause().getCause().getMessage().indexOf("bogus_path"));
// check that we have the cores we expect
cores = cc.getLoadedCoreNames();
@@ -557,16 +535,13 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// check that we get null accessing a non-existent core
assertNull(cc.getCore("does_not_exist"));
// check that we get a 500 accessing the core with an init failure
- try {
+ thrown = expectThrows(SolrException.class, () -> {
SolrCore c = cc.getCore("bogus");
- fail("Failed to get Exception on accessing core with init failure");
- } catch (SolrException ex) {
- assertEquals(500, ex.code());
- // double wrapped
- String cause = ex.getCause().getMessage();
- assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
- 0 < cause.indexOf("bogus_path"));
- }
+ });
+ assertEquals(500, thrown.code());
+ cause = thrown.getCause().getMessage();
+ assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
+ 0 < cause.indexOf("bogus_path"));
// -----
// break col_bad's config and try to RELOAD to add failure
@@ -578,19 +553,16 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
"This is giberish, not valid XML <",
IOUtils.UTF_8);
- try {
- ignoreException(Pattern.quote("SAX"));
- cc.reload("col_bad");
- fail("corrupt solrconfig.xml failed to trigger exception from reload");
- } catch (SolrException e) {
- Throwable rootException = getWrappedException(e);
- assertTrue("We're supposed to have a wrapped SAXParserException here, but we don't",
- rootException instanceof SAXParseException);
- SAXParseException se = (SAXParseException) rootException;
- assertTrue("reload exception doesn't refer to slrconfig.xml " + se.getSystemId(),
- 0 < se.getSystemId().indexOf("solrconfig.xml"));
-
- }
+ ignoreException(Pattern.quote("SAX"));
+ thrown = expectThrows(SolrException.class,
+ "corrupt solrconfig.xml failed to trigger exception from reload",
+ () -> { cc.reload("col_bad"); });
+ Throwable rootException = getWrappedException(thrown);
+ assertTrue("We're supposed to have a wrapped SAXParserException here, but we don't",
+ rootException instanceof SAXParseException);
+ SAXParseException se = (SAXParseException) rootException;
+ assertTrue("reload exception doesn't refer to slrconfig.xml " + se.getSystemId(),
+ 0 < se.getSystemId().indexOf("solrconfig.xml"));
assertEquals("Failed core reload should not have changed start time",
col_bad_old_start, getCoreStartTime(cc, "col_bad"));
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.java b/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.java
index 4e944c3..f960c89 100644
--- a/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.java
+++ b/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.java
@@ -228,12 +228,8 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {
CoreContainer cc = init();
try {
- try {
- cc.getCore("corep1");
- fail("Should have thrown exception");
- } catch (SolrCoreInitializationException scie) {
- assertTrue(scie.getMessage().contains("init failure"));
- }
+ Exception thrown = expectThrows(SolrCoreInitializationException.class, () -> cc.getCore("corep1"));
+ assertTrue(thrown.getMessage().contains("init failure"));
try (SolrCore sc = cc.getCore("corep2")) {
assertNotNull("Core corep2 should be loaded", sc);
}
@@ -249,17 +245,15 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {
corePropFile = Paths.get(solrHomeDirectory.toString(), "corep4", "core.properties");
assertFalse("Should not be a properties file yet for corep4", Files.exists(corePropFile));
- try {
+ thrown = expectThrows(SolrException.class, () -> {
cc.create("corep4", ImmutableMap.of(
CoreDescriptor.CORE_NAME, "corep4",
CoreDescriptor.CORE_SCHEMA, "not-there.xml",
CoreDescriptor.CORE_CONFIG, "solrconfig-minimal.xml",
CoreDescriptor.CORE_TRANSIENT, "false",
CoreDescriptor.CORE_LOADONSTARTUP, "true"));
- fail("Should have thrown exception getting core ");
- } catch (SolrException se) {
- assertTrue(se.getMessage().contains("Can't find resource"));
- }
+ });
+ assertTrue(thrown.getMessage().contains("Can't find resource"));
assertFalse("Failed corep4 should not have left a core.properties file around", Files.exists(corePropFile));
// Finally, just for yucks, let's determine that a this create path also leaves a prop file.
@@ -344,23 +338,18 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {
// name, isLazy, loadOnStartup
addCoreWithProps("core1", makeCoreProperties("core1", false, true));
addCoreWithProps("core2", makeCoreProperties("core2", false, false, "name=core1"));
- CoreContainer cc = null;
- try {
- cc = init();
- fail("Should have thrown exception in testDuplicateNames");
- } catch (SolrException se) {
- String message = se.getMessage();
- assertTrue("Wrong exception thrown on duplicate core names",
- message.indexOf("Found multiple cores with the name [core1]") != -1);
- assertTrue(File.separator + "core1 should have been mentioned in the message: " + message,
- message.indexOf(File.separator + "core1") != -1);
- assertTrue(File.separator + "core2 should have been mentioned in the message:" + message,
- message.indexOf(File.separator + "core2") != -1);
- } finally {
- if (cc != null) {
- cc.shutdown();
- }
- }
+ SolrException thrown = expectThrows(SolrException.class, () -> {
+ CoreContainer cc = null;
+ try { cc = init(); }
+ finally { if (cc != null) cc.shutdown(); }
+ });
+ final String message = thrown.getMessage();
+ assertTrue("Wrong exception thrown on duplicate core names",
+ message.indexOf("Found multiple cores with the name [core1]") != -1);
+ assertTrue(File.separator + "core1 should have been mentioned in the message: " + message,
+ message.indexOf(File.separator + "core1") != -1);
+ assertTrue(File.separator + "core2 should have been mentioned in the message:" + message,
+ message.indexOf(File.separator + "core2") != -1);
}
@@ -533,17 +522,12 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {
assumeTrue("Cannot make " + homeDir + " non-readable. Test aborted.", homeDir.setReadable(false, false));
assumeFalse("Appears we are a super user, skip test", homeDir.canRead());
- CoreContainer cc = null;
- try {
- cc = init();
- fail("Should have thrown an exception here");
- } catch (Exception ex) {
- assertThat(ex.getMessage(), containsString("Error reading core root directory"));
- } finally {
- if (cc != null) {
- cc.shutdown();
- }
- }
+ Exception thrown = expectThrows(Exception.class, () -> {
+ CoreContainer cc = null;
+ try { cc = init(); }
+ finally { if (cc != null) cc.shutdown(); }
+ });
+ assertThat(thrown.getMessage(), containsString("Error reading core root directory"));
// So things can be cleaned up by the framework!
homeDir.setReadable(true, false);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6e4c9b3b/solr/core/src/test/org/apache/solr/core/TestLazyCores.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/core/TestLazyCores.java b/solr/core/src/test/org/apache/solr/core/TestLazyCores.java
index f8ffb84..0831da2 100644
--- a/solr/core/src/test/org/apache/solr/core/TestLazyCores.java
+++ b/solr/core/src/test/org/apache/solr/core/TestLazyCores.java
@@ -309,7 +309,7 @@ public class TestLazyCores extends SolrTestCaseJ4 {
}
private void tryCreateFail(CoreAdminHandler admin, String name, String dataDir, String... errs) throws Exception {
- try {
+ SolrException thrown = expectThrows(SolrException.class, () -> {
SolrQueryResponse resp = new SolrQueryResponse();
SolrQueryRequest request = req(CoreAdminParams.ACTION,
@@ -320,14 +320,11 @@ public class TestLazyCores extends SolrTestCaseJ4 {
"config", "solrconfig.xml");
admin.handleRequestBody(request, resp);
- fail("Should have thrown an error");
- } catch (SolrException se) {
- //SolrException cause = (SolrException)se.getCause();
- assertEquals("Exception code should be 500", 500, se.code());
- for (String err : errs) {
- assertTrue("Should have seen an exception containing the an error",
- se.getMessage().contains(err));
- }
+ });
+ assertEquals("Exception code should be 500", 500, thrown.code());
+ for (String err : errs) {
+ assertTrue("Should have seen an exception containing the an error",
+ thrown.getMessage().contains(err));
}
}
@Test
[05/37] lucene-solr:jira/http2: LUCENE-8546: Fix ant beast to fail
and succeed based on whether beasting actually fails or succeeds.
Posted by da...@apache.org.
LUCENE-8546: Fix ant beast to fail and succeed based on whether beasting actually fails or succeeds.
LUCENE-8541: Fix ant beast to not overwrite junit xml results for each beast.iters iteration.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/16241f44
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/16241f44
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/16241f44
Branch: refs/heads/jira/http2
Commit: 16241f448441c1805898e8ebd67e446f3f334f56
Parents: 6e4c9b3
Author: markrmiller <ma...@apache.org>
Authored: Sun Dec 2 10:10:10 2018 -0600
Committer: markrmiller <ma...@apache.org>
Committed: Sun Dec 2 10:10:10 2018 -0600
----------------------------------------------------------------------
lucene/common-build.xml | 25 ++++---
lucene/tools/src/groovy/run-beaster.groovy | 86 +++++++++++++++++++------
2 files changed, 84 insertions(+), 27 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/16241f44/lucene/common-build.xml
----------------------------------------------------------------------
diff --git a/lucene/common-build.xml b/lucene/common-build.xml
index c9463ea..789fc5f 100644
--- a/lucene/common-build.xml
+++ b/lucene/common-build.xml
@@ -276,6 +276,13 @@
<isset property="fetch.sources.javadocs"/>
</condition>
+ <target name="install-ant-contrib" unless="ant-contrib.uptodate" depends="ivy-availability-check,ivy-fail,ivy-configure">
+ <property name="ant-contrib.uptodate" value="true"/>
+ <ivy:cachepath organisation="ant-contrib" module="ant-contrib" revision="1.0b3"
+ inline="true" conf="master" type="jar" pathid="ant-contrib.classpath"/>
+ <taskdef resource="ant-contrib.tasks" classpathref="ant-contrib.classpath"/>
+ </target>
+
<!-- Check for minimum supported ANT version. -->
<fail message="Minimum supported ANT version is 1.8.2. Yours: ${ant.version}">
<condition>
@@ -1272,18 +1279,16 @@
showSuiteSummary="false"
timestamps="true"
/>
-
+
<!-- Emit the information about tests timings (could be used to determine
the slowest tests or for reuse in balancing). -->
<junit4:report-execution-times file="${tests.cachedir}/${name}/timehints.txt" historyLength="20" />
<!-- ANT-compatible XMLs for jenkins records etc. -->
- <junit4:report-ant-xml dir="@{junit.output.dir}" outputStreams="no" />
+ <junit4:report-ant-xml dir="@{junit.output.dir}" outputStreams="no" ignoreDuplicateSuites="true"/>
+
+ <!-- <junit4:report-json file="@{junit.output.dir}/tests-report-${ant.project.name}/index.html" outputStreams="no" /> -->
- <!--
- Enable if you wish to have a nice HTML5 report.
- <junit4:report-json file="@{junit.output.dir}/tests-report-${ant.project.name}/index.html" outputStreams="no" />
- -->
</listeners>
<!-- Input test classes. -->
@@ -1508,7 +1513,7 @@ ${tests-output}/junit4-*.suites - per-JVM executed suites
</target>
<target name="test" depends="clover,compile-test,patch-mrjar-classes,install-junit4-taskdef,validate,-init-totals,-test,-check-totals" description="Runs unit tests"/>
- <target name="beast" depends="clover,compile-test,patch-mrjar-classes,install-junit4-taskdef,validate,-init-totals,-beast,-check-totals" description="Runs unit tests in a loop (-Dbeast.iters=n)"/>
+ <target name="beast" depends="install-ant-contrib,clover,compile-test,patch-mrjar-classes,install-junit4-taskdef,validate,-init-totals,-beast,-check-totals" description="Runs unit tests in a loop (-Dbeast.iters=n)"/>
<target name="test-nocompile" depends="-clover.disable,install-junit4-taskdef,-init-totals,-test,-check-totals"
description="Only runs unit tests. Jars are not downloaded; compilation is not updated; and Clover is not enabled."/>
@@ -1568,13 +1573,15 @@ ${tests-output}/junit4-*.suites - per-JVM executed suites
</target>
<!-- Beast the actual tests (must be wrapped with -init-totals, -check-totals) -->
- <target name="-beast" depends="resolve-groovy">
+ <target name="-beast" depends="resolve-groovy,install-ant-contrib">
<fail message="The Beast only works inside of individual modules (where 'junit.classpath' is defined)">
<condition>
<not><isreference refid="junit.classpath"/></not>
</condition>
</fail>
- <groovy taskname="beaster" src="${common.dir}/tools/src/groovy/run-beaster.groovy"/>
+ <taskdef name="antcallback" classname="net.sf.antcontrib.logic.AntCallBack" classpathref="ant-contrib.classpath"/>
+ <groovy classpathref="ant-contrib.classpath" taskname="beaster" src="${common.dir}/tools/src/groovy/run-beaster.groovy"/>
+ <fail message="Fail baby fail" if="groovy.error"/>
</target>
<target name="-check-totals" if="tests.totals.toplevel" depends="resolve-groovy">
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/16241f44/lucene/tools/src/groovy/run-beaster.groovy
----------------------------------------------------------------------
diff --git a/lucene/tools/src/groovy/run-beaster.groovy b/lucene/tools/src/groovy/run-beaster.groovy
index f94a456..057c147 100644
--- a/lucene/tools/src/groovy/run-beaster.groovy
+++ b/lucene/tools/src/groovy/run-beaster.groovy
@@ -23,24 +23,32 @@ import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildLogger;
import org.apache.tools.ant.Project;
+
+static boolean logFailOutput(Object task, String outdir) {
+ def logFile = new File(outdir, "tests-failures.txt");
+ if (logFile.exists()) {
+ logFile.eachLine("UTF-8", { line ->
+ task.log(line, Project.MSG_ERR);
+ });
+ }
+}
+
int iters = (properties['beast.iters'] ?: '1') as int;
if (iters <= 1) {
throw new BuildException("Please give -Dbeast.iters with an int value > 1.");
}
-def antcall = project.createTask('antcall');
-antcall.with {
- target = '-test';
- inheritAll = true;
- inheritRefs = true;
- createParam().with {
- name = "tests.isbeasting";
- value = "true";
- };
-};
+def antcall = project.createTask('antcallback');
+
+def junitOutDir = properties["junit.output.dir"];
+
+def failed = false;
(1..iters).each { i ->
- task.log('Beast round: ' + i, Project.MSG_INFO);
+
+ def outdir = junitOutDir + "/" + i;
+ task.log('Beast round ' + i + " results: " + outdir, Project.MSG_INFO);
+
try {
// disable verbose build logging:
project.buildListeners.each { listener ->
@@ -49,15 +57,46 @@ antcall.with {
}
};
+ new File(outdir).mkdirs();
+
+ properties["junit.output.dir"] = outdir;
+
+ antcall.setReturn("tests.failed");
+ antcall.setTarget("-test");
+ antcall.setInheritAll(true);
+ antcall.setInheritRefs(true);
+
+ antcall.with {
+
+ createParam().with {
+ name = "tests.isbeasting";
+ value = "true";
+ };
+ createParam().with {
+ name = "tests.timeoutSuite";
+ value = "900000";
+ };
+ createParam().with {
+ name = "junit.output.dir";
+ value = outdir;
+ };
+
+ };
+
+ properties["junit.output.dir"] = outdir;
+
antcall.execute();
+
+ def antcallResult = project.properties.'tests.failed' as boolean;
+
+ if (antcallResult) {
+ failed = true;
+ logFailOutput(task, outdir)
+ }
} catch (BuildException be) {
- def logFile = new File(properties["junit.output.dir"], "tests-failures.txt");
- if (logFile.exists()) {
- logFile.eachLine("UTF-8", { line ->
- task.log(line, Project.MSG_ERR);
- });
- }
+ task.log(be.getMessage(), Project.MSG_ERR);
+ logFailOutput(task, outdir)
throw be;
} finally {
// restore build logging (unfortunately there is no way to get the original logging level (write-only property):
@@ -68,4 +107,15 @@ antcall.with {
};
}
};
-task.log('Beasting finished.', Project.MSG_INFO);
+
+// restore junit output dir
+properties["junit.output.dir"] = junitOutDir;
+
+
+if (failed) {
+ task.log('Beasting finished with failure.', Project.MSG_INFO);
+ throw new BuildException("Beasting Failed!");
+} else {
+ task.log('Beasting finished Successfully.', Project.MSG_INFO);
+}
+
[22/37] lucene-solr:jira/http2: SOLR-13019: Fix typo in
MailEntityProcessor
Posted by da...@apache.org.
SOLR-13019: Fix typo in MailEntityProcessor
Path provided by Tommy Marshment-Howell.
Closes #509
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/f7faae07
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/f7faae07
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/f7faae07
Branch: refs/heads/jira/http2
Commit: f7faae075bdde4a55158ea00d183193ee09ce490
Parents: c78429a
Author: Jason Gerlowski <ge...@apache.org>
Authored: Tue Dec 4 08:36:48 2018 -0500
Committer: Jason Gerlowski <ge...@apache.org>
Committed: Tue Dec 4 08:49:58 2018 -0500
----------------------------------------------------------------------
.../org/apache/solr/handler/dataimport/MailEntityProcessor.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f7faae07/solr/contrib/dataimporthandler-extras/src/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler-extras/src/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java b/solr/contrib/dataimporthandler-extras/src/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java
index 54f5984..91847d4 100644
--- a/solr/contrib/dataimporthandler-extras/src/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java
+++ b/solr/contrib/dataimporthandler-extras/src/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java
@@ -66,7 +66,7 @@ public class MailEntityProcessor extends EntityProcessorBase {
public void init(Context context) {
super.init(context);
- // set attributes using XXX getXXXFromContext(attribute, defualtValue);
+ // set attributes using XXX getXXXFromContext(attribute, defaultValue);
// applies variable resolver and return default if value is not found or null
// REQUIRED : connection and folder info
user = getStringFromContext("user", null);
[24/37] lucene-solr:jira/http2: close DirectoryReader in test
Posted by da...@apache.org.
close DirectoryReader in test
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/ca4555ed
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/ca4555ed
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/ca4555ed
Branch: refs/heads/jira/http2
Commit: ca4555ed936c62fc6d7da5165d14ee51ab2a1c8c
Parents: f637c50
Author: Shai Erera <sh...@apache.org>
Authored: Tue Dec 4 16:37:35 2018 +0200
Committer: Shai Erera <sh...@apache.org>
Committed: Tue Dec 4 16:37:35 2018 +0200
----------------------------------------------------------------------
lucene/core/src/test/org/apache/lucene/index/TestDocValues.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ca4555ed/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java b/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
index 3010047..98b7d9e 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java
@@ -206,7 +206,6 @@ public class TestDocValues extends LuceneTestCase {
iw.close();
DirectoryReader dr = DirectoryReader.open(zeroDir);
-
for (int id = 0 ; id < docValues.size() ; id++) {
int readerIndex = dr.readerIndex(id);
// We create a new reader each time as we want to test vBPV-skipping and not sequential iteration
@@ -215,6 +214,7 @@ public class TestDocValues extends LuceneTestCase {
assertEquals(designation + ": The value for docID " + id + " should be as expected",
docValues.get(id), Long.valueOf(numDV.longValue()));
}
+ dr.close();
// Clean up
deleteAndClose(zeroDir);
[17/37] lucene-solr:jira/http2: SOLR-13036 Fix retry logic in
JettySolrRunner
Posted by da...@apache.org.
SOLR-13036 Fix retry logic in JettySolrRunner
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/59919b4a
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/59919b4a
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/59919b4a
Branch: refs/heads/jira/http2
Commit: 59919b4ac06a5907e050ffe399013f16dc8c2f99
Parents: e14432e
Author: Gus Heck <gu...@apache.org>
Authored: Mon Dec 3 21:54:34 2018 -0500
Committer: Gus Heck <gu...@apache.org>
Committed: Mon Dec 3 21:54:34 2018 -0500
----------------------------------------------------------------------
solr/CHANGES.txt | 5 ++
.../client/solrj/embedded/JettySolrRunner.java | 35 ++++++++++---
.../solrj/embedded/TestJettySolrRunner.java | 53 +++++++++++++++++++-
3 files changed, 85 insertions(+), 8 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/59919b4a/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index d5240be..dcc6267 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -113,6 +113,8 @@ Other Changes
* SOLR-12775: LowerCaseTokenizer is deprecated, and should be replaced by LetterTokenizer and
LowerCaseFilter (Alan Woodward)
+* SOLR-13036: Fix retry logic in JettySolrRunner (Gus Heck)
+
================== 7.7.0 ==================
Consult the LUCENE_CHANGES.txt file for additional, low level, changes in this release.
@@ -172,6 +174,9 @@ Other Changes
* SOLR-12932: ant test (without badapples=false) should pass easily for developers. (Mark Miller)
+* SOLR-13036: Fix retry logic in JettySolrRunner (Gus Heck)
+
+
================== 7.6.0 ==================
Consult the LUCENE_CHANGES.txt file for additional, low level, changes in this release.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/59919b4a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java b/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
index e9d8419..24caec8 100644
--- a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
+++ b/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java
@@ -509,12 +509,15 @@ public class JettySolrRunner {
log.info("Trying to start Jetty on port {} try number {} ...", port, tryCnt++);
server.start();
break;
- } catch (BindException e) {
- log.info("Port is in use, will try again until timeout of " + timeout);
- server.stop();
- Thread.sleep(3000);
- if (!timeout.hasTimedOut()) {
- continue;
+ } catch (IOException ioe) {
+ Exception e = lookForBindException(ioe);
+ if (e instanceof BindException) {
+ log.info("Port is in use, will try again until timeout of " + timeout);
+ server.stop();
+ Thread.sleep(3000);
+ if (!timeout.hasTimedOut()) {
+ continue;
+ }
}
throw e;
@@ -523,6 +526,26 @@ public class JettySolrRunner {
}
/**
+ * Traverses the cause chain looking for a BindException. Returns either a bind exception
+ * that was found in the chain or the original argument.
+ *
+ * @param ioe An IOException that might wrap a BindException
+ * @return A bind exception if present otherwise ioe
+ */
+ Exception lookForBindException(IOException ioe) {
+ Exception e = ioe;
+ while(e.getCause() != null && !(e == e.getCause()) && ! (e instanceof BindException)) {
+ if (e.getCause() instanceof Exception) {
+ e = (Exception) e.getCause();
+ if (e instanceof BindException) {
+ return e;
+ }
+ }
+ }
+ return ioe;
+ }
+
+ /**
* Stop the Jetty server
*
* @throws Exception if an error occurs on shutdown
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/59919b4a/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestJettySolrRunner.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestJettySolrRunner.java b/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestJettySolrRunner.java
index 6b21aa1..ae8312e 100644
--- a/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestJettySolrRunner.java
+++ b/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestJettySolrRunner.java
@@ -19,8 +19,12 @@ package org.apache.solr.client.solrj.embedded;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.request.CoreAdminRequest;
+import org.apache.solr.cloud.MiniSolrCloudCluster;
import org.junit.Test;
+import java.io.IOException;
+import java.net.BindException;
+import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -62,11 +66,56 @@ public class TestJettySolrRunner extends SolrTestCaseJ4 {
assertTrue(Files.exists(coresDir.resolve("newcore").resolve("core.properties")));
- }
- finally {
+ } finally {
runner.stop();
}
}
+
+ @SuppressWarnings("ThrowableNotThrown")
+ @Test
+ public void testLookForBindException() throws IOException {
+ Path solrHome = createTempDir();
+ Files.write(solrHome.resolve("solr.xml"), MiniSolrCloudCluster.DEFAULT_CLOUD_SOLR_XML.getBytes(Charset.defaultCharset()));
+
+ JettyConfig config = JettyConfig.builder().build();
+
+ JettySolrRunner jetty = new JettySolrRunner(solrHome.toString(), config);
+
+ Exception result;
+ BindException be = new BindException();
+ IOException test = new IOException();
+
+ result = jetty.lookForBindException(test);
+ assertEquals(result, test);
+
+ test = new IOException();
+ result = jetty.lookForBindException(test);
+ assertEquals(result, test);
+
+ test = new IOException((Throwable) null);
+ result = jetty.lookForBindException(test);
+ assertEquals(result, test);
+
+ test = new IOException() {
+ @Override
+ public synchronized Throwable getCause() {
+ return this;
+ }
+ };
+ result = jetty.lookForBindException(test);
+ assertEquals(result, test);
+
+ test = new IOException(new RuntimeException());
+ result = jetty.lookForBindException(test);
+ assertEquals(result, test);
+
+ test = new IOException(new RuntimeException(be));
+ result = jetty.lookForBindException(test);
+ assertEquals(result, be);
+
+ }
+
+
}
[08/37] lucene-solr:jira/http2: SOLR-12801 fix cut/paste oops in
comment
Posted by da...@apache.org.
SOLR-12801 fix cut/paste oops in comment
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/b6b9f955
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/b6b9f955
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/b6b9f955
Branch: refs/heads/jira/http2
Commit: b6b9f9554e6a30d92afd2b277554e1d1f81ede5d
Parents: cf4d749
Author: Gus Heck <gu...@apache.org>
Authored: Sun Dec 2 16:41:55 2018 -0500
Committer: Gus Heck <gu...@apache.org>
Committed: Sun Dec 2 16:41:55 2018 -0500
----------------------------------------------------------------------
.../solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b6b9f955/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java b/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
index b500a7e..1fc1e25 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/TimeRoutedAliasUpdateProcessorTest.java
@@ -534,7 +534,7 @@ public class TimeRoutedAliasUpdateProcessorTest extends SolrCloudTestCase {
assertTrue("Preemptive creation beyond ROUTER_PREEMPTIVE_CREATE_MATH setting of 3DAY!",!cols.contains("myalias_2017-11-04"));
assertUpdateResponse(add(alias, Collections.singletonList(
- sdoc("id", "18", "timestamp_dt", "2017-11-01T23:01:00Z")), // should NOT cause preemptive creation 11-04
+ sdoc("id", "18", "timestamp_dt", "2017-11-01T23:01:00Z")), // should cause preemptive creation 11-04
params));
waitCol("2017-11-04",numShards);
[25/37] lucene-solr:jira/http2: SOLR-13032: harden
MaxSizeAutoCommitTest to eliminate race conditions and eliminate use of
arbitrary sleep
Posted by da...@apache.org.
SOLR-13032: harden MaxSizeAutoCommitTest to eliminate race conditions and eliminate use of arbitrary sleep
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/868e0057
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/868e0057
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/868e0057
Branch: refs/heads/jira/http2
Commit: 868e005760e95b0e3632f9bc8cec57656aeddabc
Parents: ca4555e
Author: Chris Hostetter <ho...@apache.org>
Authored: Tue Dec 4 10:44:05 2018 -0700
Committer: Chris Hostetter <ho...@apache.org>
Committed: Tue Dec 4 10:44:05 2018 -0700
----------------------------------------------------------------------
.../org/apache/solr/update/CommitTracker.java | 5 +
.../solr/update/MaxSizeAutoCommitTest.java | 233 +++++++++++++------
2 files changed, 165 insertions(+), 73 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/868e0057/solr/core/src/java/org/apache/solr/update/CommitTracker.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/update/CommitTracker.java b/solr/core/src/java/org/apache/solr/update/CommitTracker.java
index d3929b2..55b2287 100644
--- a/solr/core/src/java/org/apache/solr/update/CommitTracker.java
+++ b/solr/core/src/java/org/apache/solr/update/CommitTracker.java
@@ -326,4 +326,9 @@ public final class CommitTracker implements Runnable {
public void setOpenSearcher(boolean openSearcher) {
this.openSearcher = openSearcher;
}
+
+ // only for testing - not thread safe
+ public boolean hasPending() {
+ return (null != pending && !pending.isDone());
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/868e0057/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java b/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java
index 612e55b..36298b5 100644
--- a/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java
+++ b/solr/core/src/test/org/apache/solr/update/MaxSizeAutoCommitTest.java
@@ -17,9 +17,13 @@
package org.apache.solr.update;
+import java.lang.invoke.MethodHandles;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@@ -27,16 +31,24 @@ import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrCore;
+import org.apache.solr.core.SolrEventListener;
+import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.handler.UpdateRequestHandler;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.response.SolrQueryResponse;
+
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
public class MaxSizeAutoCommitTest extends SolrTestCaseJ4 {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
// Given an ID, returns an XML string for an "add document" request
private static final Function<Integer, String> ADD_DOC_FN = (id) -> adoc("id", Integer.toString(id));
@@ -44,11 +56,14 @@ public class MaxSizeAutoCommitTest extends SolrTestCaseJ4 {
private static final Function<Integer, String> DELETE_DOC_FN = (id) -> delI(Integer.toString(id));
// How long to sleep while checking for commits
private static final int COMMIT_CHECKING_SLEEP_TIME_MS = 50;
-
+ // max TLOG file size
+ private static final int MAX_FILE_SIZE = 1000;
+
private SolrCore core;
private DirectUpdateHandler2 updateHandler;
private CommitTracker hardCommitTracker;
private UpdateRequestHandler updateRequestHandler;
+ private MockEventListener monitor;
@Before
public void setup() throws Exception {
@@ -56,63 +71,73 @@ public class MaxSizeAutoCommitTest extends SolrTestCaseJ4 {
initCore("solrconfig-tlog.xml", "schema.xml");
core = h.getCore();
updateHandler = (DirectUpdateHandler2) core.getUpdateHandler();
+
+ // we don't care about auto-commit's opening a new Searcher in this test, just skip it.
+ updateHandler.softCommitTracker.setOpenSearcher(false);
+ updateHandler.commitTracker.setOpenSearcher(false);
+
+ // we don't care about soft commit's at all
+ updateHandler.softCommitTracker.setTimeUpperBound(-1);
+ updateHandler.softCommitTracker.setDocsUpperBound(-1);
+ updateHandler.softCommitTracker.setTLogFileSizeUpperBound(-1);
+
hardCommitTracker = updateHandler.commitTracker;
// Only testing file-size based auto hard commits - disable other checks
hardCommitTracker.setTimeUpperBound(-1);
hardCommitTracker.setDocsUpperBound(-1);
+ hardCommitTracker.setTLogFileSizeUpperBound(MAX_FILE_SIZE);
+
+ monitor = new MockEventListener();
+ updateHandler.registerCommitCallback(monitor);
+
updateRequestHandler = new UpdateRequestHandler();
updateRequestHandler.init( null );
}
@After
public void tearDown() throws Exception {
+ monitor.assertSaneOffers();
+ monitor.clear();
super.tearDown();
System.clearProperty("solr.ulog");
deleteCore();
}
@Test
- @AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/SOLR-13032")
public void testAdds() throws Exception {
- int maxFileSizeBound = 1000;
- // Set max size bound
- hardCommitTracker.setTLogFileSizeUpperBound(maxFileSizeBound);
-
- // Add a large number of docs - should trigger a commit
- int numDocsToAdd = 500;
- SolrQueryResponse updateResp = new SolrQueryResponse();
Assert.assertEquals("There have been no updates yet, so there shouldn't have been any commits", 0,
- hardCommitTracker.getCommitCount());
+ hardCommitTracker.getCommitCount());
long tlogSizePreUpdates = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
Assert.assertEquals("There have been no updates yet, so tlog should be empty", 0, tlogSizePreUpdates);
- updateRequestHandler.handleRequest(constructBatchAddDocRequest(0, numDocsToAdd), updateResp);
-
- // The long sleep is to allow for the triggered commit to finish
- waitForCommit(1000);
-
- // Verify commit information
- Assert.assertTrue("At least one commit should have occurred", hardCommitTracker.getCommitCount() > 0);
- long tlogSizePostUpdates = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
- Assert.assertTrue("Current tlog size is larger than the max bound", tlogSizePostUpdates < maxFileSizeBound);
+ // Add a large number of docs - should trigger a commit
+ int numDocsToAdd = 500;
+ SolrQueryResponse updateResp = new SolrQueryResponse();
+
+ monitor.doStuffAndExpectAtLeastOneCommit(hardCommitTracker, updateHandler, () -> {
+ updateRequestHandler.handleRequest(constructBatchAddDocRequest(0, numDocsToAdd), updateResp);
+ });
}
@Test
public void testRedundantDeletes() throws Exception {
- int maxFileSizeBound = 1000;
- // Set max size bound
- hardCommitTracker.setTLogFileSizeUpperBound(maxFileSizeBound);
+ Assert.assertEquals("There have been no updates yet, so there shouldn't have been any commits", 0,
+ hardCommitTracker.getCommitCount());
+
+ long tlogSizePreUpdates = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
+ Assert.assertEquals("There have been no updates yet, so tlog should be empty", 0, tlogSizePreUpdates);
+
// Add docs
int numDocsToAdd = 150;
SolrQueryResponse updateResp = new SolrQueryResponse();
- updateRequestHandler.handleRequest(constructBatchAddDocRequest(0, numDocsToAdd), updateResp);
- waitForCommit(1000);
- // Get the current commit info
- int commitCountPreDeletes = hardCommitTracker.getCommitCount();
+ monitor.doStuffAndExpectAtLeastOneCommit(hardCommitTracker, updateHandler, () -> {
+ updateRequestHandler.handleRequest(constructBatchAddDocRequest(0, numDocsToAdd), updateResp);
+ });
+
// Send a bunch of redundant deletes
int numDeletesToSend = 500;
@@ -124,63 +149,36 @@ public class MaxSizeAutoCommitTest extends SolrTestCaseJ4 {
docs.add(delI(Integer.toString(docIdToDelete)));
}
batchSingleDeleteRequest.setContentStreams(toContentStreams(docs));
-
- updateRequestHandler.handleRequest(batchSingleDeleteRequest, updateResp);
-
- // The long sleep is to allow for the expected triggered commit to finish
- waitForCommit(1000);
-
- // Verify commit information
- Assert.assertTrue("At least one commit should have occurred",
- hardCommitTracker.getCommitCount() > commitCountPreDeletes);
- long tlogSizePostDeletes = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
- Assert.assertTrue("Current tlog size is larger than the max bound", tlogSizePostDeletes < maxFileSizeBound);
+
+ monitor.doStuffAndExpectAtLeastOneCommit(hardCommitTracker, updateHandler, () -> {
+ updateRequestHandler.handleRequest(batchSingleDeleteRequest, updateResp);
+ });
+
}
@Test
- @AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/SOLR-13032")
public void testDeletes() throws Exception {
- int maxFileSizeBound = 1000;
- // Set max size bound
- hardCommitTracker.setTLogFileSizeUpperBound(maxFileSizeBound);
+ Assert.assertEquals("There have been no updates yet, so there shouldn't have been any commits", 0,
+ hardCommitTracker.getCommitCount());
+ long tlogSizePreUpdates = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
+ Assert.assertEquals("There have been no updates yet, so tlog should be empty", 0, tlogSizePreUpdates);
+
// Add docs
int numDocsToAdd = 500;
SolrQueryResponse updateResp = new SolrQueryResponse();
- updateRequestHandler.handleRequest(constructBatchAddDocRequest(0, numDocsToAdd), updateResp);
- waitForCommit(1000);
-
- // Get the current commit info
- int commitCountPreDeletes = hardCommitTracker.getCommitCount();
-
+
+ monitor.doStuffAndExpectAtLeastOneCommit(hardCommitTracker, updateHandler, () -> {
+ updateRequestHandler.handleRequest(constructBatchAddDocRequest(0, numDocsToAdd), updateResp);
+ });
+
// Delete all documents - should trigger a commit
- updateRequestHandler.handleRequest(constructBatchDeleteDocRequest(0, numDocsToAdd), updateResp);
-
- // The long sleep is to allow for the expected triggered commit to finish
- waitForCommit(1000);
-
- // Verify commit information
- Assert.assertTrue("At least one commit should have occurred",
- hardCommitTracker.getCommitCount() > commitCountPreDeletes);
- long tlogSizePostDeletes = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
- Assert.assertTrue("Current tlog size is larger than the max bound", tlogSizePostDeletes < maxFileSizeBound);
- }
-
- /**
- * Sleeps in increments of COMMIT_CHECKING_SLEEP_TIME_MS while checking to see if a commit completed. If it did,
- * then return. If not, continue this cycle for at most the amount of time specified
- * @param maxTotalWaitTimeMillis the max amount of time (in ms) to wait/check for a commit
- */
- private void waitForCommit(long maxTotalWaitTimeMillis) throws Exception {
- long startTimeNanos = System.nanoTime();
- long maxTotalWaitTimeNanos = TimeUnit.MILLISECONDS.toNanos(maxTotalWaitTimeMillis);
- while (System.nanoTime() - startTimeNanos < maxTotalWaitTimeNanos) {
- Thread.sleep(COMMIT_CHECKING_SLEEP_TIME_MS);
- if (!updateHandler.getUpdateLog().hasUncommittedChanges()) {
- return;
- }
- }
+
+ monitor.doStuffAndExpectAtLeastOneCommit(hardCommitTracker, updateHandler, () -> {
+ updateRequestHandler.handleRequest(constructBatchDeleteDocRequest(0, numDocsToAdd), updateResp);
+ });
+
}
/**
@@ -232,4 +230,93 @@ public class MaxSizeAutoCommitTest extends SolrTestCaseJ4 {
}
return streams;
}
+
+ private static final class MockEventListener implements SolrEventListener {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ public MockEventListener() {
+ /* No-Op */
+ }
+
+ // use capacity bound Queue just so we're sure we don't OOM
+ public final BlockingQueue<Long> hard = new LinkedBlockingQueue<>(1000);
+
+ // if non enpty, then at least one offer failed (queues full)
+ private StringBuffer fail = new StringBuffer();
+
+ @Override
+ public void init(NamedList args) {}
+
+ @Override
+ public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) {
+ // No-Op
+ }
+
+ @Override
+ public void postCommit() {
+ Long now = System.nanoTime();
+ if (!hard.offer(now)) fail.append(", hardCommit @ " + now);
+ }
+
+ @Override
+ public void postSoftCommit() {
+ // No-Op
+ }
+
+ public void clear() {
+ hard.clear();
+ fail.setLength(0);
+ }
+
+ public void doStuffAndExpectAtLeastOneCommit(final CommitTracker commitTracker,
+ final DirectUpdateHandler2 updateHandler,
+ final Runnable stuff) throws InterruptedException {
+ assertSaneOffers();
+
+ final int POLL_TIME = 5;
+ final TimeUnit POLL_UNIT = TimeUnit.SECONDS;
+
+ final int preAutoCommitCount = commitTracker.getCommitCount();
+ log.info("Auto-Commit count prior to doing work: {}", preAutoCommitCount);
+ stuff.run();
+ log.info("Work Completed");
+
+ int numIters = 0;
+ Long lastPostCommitTimeStampSeen = null;
+ final long startTimeNanos = System.nanoTime();
+ final long cutOffTime = startTimeNanos + TimeUnit.SECONDS.toNanos(300);
+ while (System.nanoTime() < cutOffTime) {
+ numIters++;
+ log.info("Polling at most {} {} for expected (post-)commit#{}", POLL_TIME, POLL_UNIT, numIters);
+ lastPostCommitTimeStampSeen = hard.poll(POLL_TIME, POLL_UNIT);
+ assertNotNull("(post-)commit#" + numIters + " didn't occur in allowed time frame",
+ lastPostCommitTimeStampSeen);
+
+ synchronized (commitTracker) {
+ final int currentAutoCommitCount = commitTracker.getCommitCount() - preAutoCommitCount;
+ final long currentFileSize = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
+ if ((currentFileSize < MAX_FILE_SIZE) &&
+ (currentAutoCommitCount == numIters) &&
+ ( ! commitTracker.hasPending() )) {
+ // if all of these condiions are met, then we should be completely done
+ assertSaneOffers(); // last minute sanity check
+ return;
+ }
+ // else: log & loop...
+ log.info("(Auto-)commits triggered: {}; (post-)commits seen: {}; current tlog file size: {}",
+ currentAutoCommitCount, numIters, currentFileSize);
+ }
+ }
+
+ // if we didn't return already, then we ran out of time
+ fail("Exhausted cut off time polling for post-commit events (got " + numIters + ")");
+ }
+
+ public void assertSaneOffers() {
+ assertEquals("Failure of MockEventListener" + fail.toString(),
+ 0, fail.length());
+ }
+ }
+
}
+
[11/37] lucene-solr:jira/http2: LUCENE-8374 part 2/4: Reduce reads
for sparse DocValues
Posted by da...@apache.org.
LUCENE-8374 part 2/4: Reduce reads for sparse DocValues
Index jump-table for DENSE indexedDISI blocks.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/7ad02762
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/7ad02762
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/7ad02762
Branch: refs/heads/jira/http2
Commit: 7ad027627a179daa7d8d56be191d5b287dfec6f4
Parents: 58a7a8a
Author: Toke Eskildsen <to...@apache.org>
Authored: Mon Dec 3 14:24:40 2018 +0100
Committer: Toke Eskildsen <to...@apache.org>
Committed: Mon Dec 3 14:24:40 2018 +0100
----------------------------------------------------------------------
.../codecs/lucene70/IndexedDISICache.java | 102 ++++++-
.../lucene70/IndexedDISICacheFactory.java | 5 +
.../lucene/codecs/lucene70/LongCompressor.java | 246 +++++++++++++++
.../java/org/apache/lucene/util/RankBitSet.java | 302 +++++++++++++++++++
.../codecs/lucene70/TestLongCompressor.java | 87 ++++++
.../org/apache/lucene/util/TestRankBitSet.java | 107 +++++++
6 files changed, 842 insertions(+), 7 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ad02762/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
index 9a80689..be0beb7 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICache.java
@@ -33,7 +33,7 @@ import static org.apache.lucene.codecs.lucene70.IndexedDISI.MAX_ARRAY_LENGTH;
/**
* Caching of IndexedDISI with two strategies:
*
- * A lookup table for block blockCache and index.
+ * A lookup table for block blockCache and index, and a rank structure for DENSE block lookups.
*
* The lookup table is an array of {@code long}s with an entry for each block. It allows for
* direct jumping to the block, as opposed to iteration from the current position and forward
@@ -53,8 +53,30 @@ import static org.apache.lucene.codecs.lucene70.IndexedDISI.MAX_ARRAY_LENGTH;
* In the case of non-existing blocks, the entry in the lookup table has index equal to the
* previous entry and offset equal to the next non-empty block.
*
- * The performance overhead for creating a cache instance is equivalent to visiting every 65536th
- * doc value for the given field, i.e. it scales lineary to field size.
+ *
+ * The rank structure for DENSE blocks is an array of unsigned {@code short}s with an entry
+ * for each sub-block of 512 bits out of the 65536 bits in the outer block.
+ *
+ * Each rank-entry states the number of set bits within the block up to the bit before the
+ * bit positioned at the start of the sub-block.
+ * Note that that the rank entry of the first sub-block is always 0 and that the last entry can
+ * at most be 65536-512 = 65024 and thus will always fit into an unsigned short.
+ *
+ * See https://en.wikipedia.org/wiki/Succinct_data_structure for details on rank structures.
+ * The alternative to using the rank structure is iteration and summing of set bits for all
+ * entries in the DENSE sub-block up until the wanted bit, with a worst-case of 1024 entries.
+ * The rank cache overhead for a single DENSE block is 128 shorts (128*16 = 2048 bits) or
+ * 1/32th.
+ *
+ * The ranks for the DENSE blocks are stored in a structure shared for the whole array of
+ * blocks, DENSE or not. To avoid overhead that structure is itself sparse. See
+ * {@link LongCompressor} for details on DENSE structure sparseness.
+ *
+ *
+ * The performance overhead for creating a cache instance is equivalent to accessing all
+ * DocValues values for the given field, i.e. it scales lineary to field size. On modern
+ * hardware it is in the ballpark of 1ms for 5M values on modern hardware. Caveat lector:
+ * At the point of writing, performance points are only available for 2 real-world setups.
*/
public class IndexedDISICache implements Accountable {
private static final int BLOCK = 65536; // The number of docIDs that a single block represents
@@ -63,6 +85,12 @@ public class IndexedDISICache implements Accountable {
private static final long BLOCK_INDEX_MASK = ~0L << BLOCK_INDEX_SHIFT; // The index bits in a lookup entry
private static final long BLOCK_LOOKUP_MASK = ~BLOCK_INDEX_MASK; // The offset bits in a lookup entry
+ private static final int RANK_BLOCK = 512; // The number of docIDs/bits in each rank-sub-block within a DENSE block
+ static final int RANK_BLOCK_LONGS = 512/Long.SIZE; // The number of longs making up a rank-block (8)
+ private static final int RANK_BLOCK_BITS = 9;
+ private static final int RANKS_PER_BLOCK = BLOCK/RANK_BLOCK;
+
+ private PackedInts.Reader rank; // One every 512 docs, sparsely represented as not all blocks are DENSE
private long[] blockCache = null; // One every 65536 docs, contains index & slice position
private String creationStats = "";
private final String name; // Identifier for debug, log & inspection
@@ -86,6 +114,7 @@ public class IndexedDISICache implements Accountable {
private IndexedDISICache() {
this.blockCache = null;
+ this.rank = null;
this.name = "";
}
@@ -117,10 +146,45 @@ public class IndexedDISICache implements Accountable {
-1 : (int)(blockCache[targetBlock] >>> BLOCK_INDEX_SHIFT);
}
+ /**
+ * Given a target (docID), this method returns the first docID in the entry containing the target.
+ * @param target the docID for which an index is wanted.
+ * @return the docID where the rank is known. This will be lte target.
+ */
+ // TODO: This method requires a lot of knowledge of the intrinsics of the cache. Usage should be simplified
+ int denseRankPosition(int target) {
+ return target >> RANK_BLOCK_BITS << RANK_BLOCK_BITS;
+ }
+
public boolean hasOffsets() {
return blockCache != null;
}
+ boolean hasRank() {
+ return rank != null;
+ }
+
+ /**
+ * Get the rank (index) for all set bits up to just before the given rankPosition in the block.
+ * The caller is responsible for deriving the count of bits up to the docID target from the rankPosition.
+ * The caller is also responsible for keeping track of set bits up to the current block.
+ * Important: This only accepts rankPositions that aligns to {@link #RANK_BLOCK} boundaries.
+ * Note 1: Use {@link #denseRankPosition(int)} to obtain a calid rankPosition for a wanted docID.
+ * Note 2: The caller should seek to the rankPosition in the underlying slice to keep everything in sync.
+ * @param rankPosition a docID target that aligns to {@link #RANK_BLOCK}.
+ * @return the rank (index / set bits count) up to just before the given rankPosition.
+ * If rank is disabled, -1 is returned.
+ */
+ // TODO: This method requires a lot of knowledge of the intrinsics of the cache. Usage should be simplified
+ int getRankInBlock(int rankPosition) {
+ if (rank == null) {
+ return -1;
+ }
+ assert rankPosition == denseRankPosition(rankPosition);
+ int rankIndex = rankPosition >> RANK_BLOCK_BITS;
+ return rankIndex >= rank.size() ? -1 : (int) rank.get(rankIndex);
+ }
+
private void updateCaches(IndexInput slice) throws IOException {
final long startOffset = slice.getFilePointer();
@@ -135,17 +199,19 @@ public class IndexedDISICache implements Accountable {
slice.seek(startOffset); // Leave it as we found it
creationStats = String.format(Locale.ENGLISH,
- "name=%s, blocks=%d (ALL=%d, DENSE=%d, SPARSE=%d, EMPTY=%d), time=%dms, block=%d bytes",
+ "name=%s, blocks=%d (ALL=%d, DENSE=%d, SPARSE=%d, EMPTY=%d), time=%dms, block=%d bytes, rank=%d bytes",
name,
largestBlock+1, statBlockALL.get(), statBlockDENSE.get(), statBlockSPARSE.get(),
(largestBlock+1-statBlockALL.get()-statBlockDENSE.get()-statBlockSPARSE.get()),
(System.nanoTime()-startTime)/1000000,
- blockCache == null ? 0 : blockCache.length*Long.BYTES);
+ blockCache == null ? 0 : blockCache.length*Long.BYTES,
+ rank == null ? 0 : rank.ramBytesUsed());
}
private int fillCache(
IndexInput slice, AtomicInteger statBlockALL, AtomicInteger statBlockDENSE, AtomicInteger statBlockSPARSE)
throws IOException {
+ char[] buildRank = new char[256];
int largestBlock = -1;
long index = 0;
int rankIndex = -1;
@@ -180,7 +246,27 @@ public class IndexedDISICache implements Accountable {
// The block is DENSE
statBlockDENSE.incrementAndGet();
long nextBlockOffset = slice.getFilePointer() + (1 << 13);
- slice.seek(nextBlockOffset);
+ int setBits = 0;
+ int rankOrigo = blockIndex << 16 >> 9; // Double shift for clarity: The compiler will simplify it
+ for (int rankDelta = 0 ; rankDelta < RANKS_PER_BLOCK ; rankDelta++) { // 128 rank-entries in a block
+ rankIndex = rankOrigo + rankDelta;
+ buildRank = ArrayUtil.grow(buildRank, rankIndex+1);
+ buildRank[rankIndex] = (char)setBits;
+ for (int i = 0 ; i < 512/64 ; i++) { // 8 longs for each rank-entry
+ setBits += Long.bitCount(slice.readLong());
+ }
+ }
+ assert slice.getFilePointer() == nextBlockOffset;
+ }
+ // Compress the buildRank as it is potentially very sparse
+ if (rankIndex < 0) {
+ rank = null;
+ } else {
+ PackedInts.Mutable ranks = PackedInts.getMutable(rankIndex, 16, PackedInts.DEFAULT); // Char = 16 bit
+ for (int i = 0 ; i < rankIndex ; i++) {
+ ranks.set(i, buildRank[i]);
+ }
+ rank = LongCompressor.compress(ranks);
}
return largestBlock;
@@ -189,6 +275,7 @@ public class IndexedDISICache implements Accountable {
private void freezeCaches(int largestBlock) {
if (largestBlock == -1) { // No set bit: Disable the caches
blockCache = null;
+ rank = null;
return;
}
@@ -228,7 +315,8 @@ public class IndexedDISICache implements Accountable {
@Override
public long ramBytesUsed() {
return (blockCache == null ? 0 : RamUsageEstimator.sizeOf(blockCache)) +
+ (rank == null ? 0 : rank.ramBytesUsed()) +
RamUsageEstimator.NUM_BYTES_OBJECT_REF*3 +
RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + creationStats.length()*2;
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ad02762/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
index 6cf8af1..7a85727 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/IndexedDISICacheFactory.java
@@ -118,6 +118,8 @@ public class IndexedDISICacheFactory implements Accountable {
IndexedDISICache cache = disiPool.get(key);
if (cache == null) {
// TODO: Avoid overlapping builds of the same cache
+ // Both BLOCK & DENSE caches are created as they might be requested later for the field,
+ // regardless of whether they are requested now
cache = new IndexedDISICache(slice, name);
disiPool.put(key, cache);
}
@@ -128,6 +130,9 @@ public class IndexedDISICacheFactory implements Accountable {
public long getDISIBlocksWithOffsetsCount() {
return disiPool.values().stream().filter(IndexedDISICache::hasOffsets).count();
}
+ public long getDISIBlocksWithRankCount() {
+ return disiPool.values().stream().filter(IndexedDISICache::hasRank).count();
+ }
@Override
public long ramBytesUsed() {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ad02762/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java
new file mode 100644
index 0000000..1c030a7
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene70/LongCompressor.java
@@ -0,0 +1,246 @@
+/*
+ * 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.lucene.codecs.lucene70;
+
+import org.apache.lucene.util.MathUtil;
+import org.apache.lucene.util.RankBitSet;
+import org.apache.lucene.util.packed.PackedInts;
+
+/**
+ * Utility class for generating compressed read-only in-memory representations of longs.
+ * The representation is optimized towards random access primarily and space secondarily.
+ *
+ * The representation always applies delta-to-minvalue and greatest-common-divisor compression.
+ *
+ * Depending on the number of 0-entries and the length of the array, a sparse representation is
+ * used, using rank to improve access speed. Sparseness introduces an O(1) access time overhead.
+ * Sparseness can be turned off.
+ */
+public class LongCompressor {
+
+ /**
+ * The minimum amount of total values in the data set for sparse to be active.
+ */
+ private static final int DEFAULT_MIN_TOTAL_VALUES_FOR_SPARSE = 10_000;
+
+ /**
+ * The minimum total amount of zero values in the data set for sparse to be active.
+ */
+ private static final int DEFAULT_MIN_ZERO_VALUES_FOR_SPARSE = 500;
+
+ /**
+ * The minimum fraction of the data set that must be zero for sparse to be active.
+ */
+ private static final double DEFAULT_MIN_ZERO_VALUES_FRACTION_FOR_SPARSE = 0.2; // 20% (just guessing of a value here)
+
+ /**
+ * Create a compact version of the given values.
+ * @param values PackedInts with no special constraints.
+ * @return a compact version of the given values or the given values if compression did not improve on heap overhead.
+ */
+ public static PackedInts.Reader compress(PackedInts.Reader values) {
+ return compress(values, values.size());
+ }
+
+ /**
+ * Create a compact version of the given values from index 0 to length-1.
+ * @param values PackedInts with no special constraints.
+ * @param length the number of values to compress.
+ * @return a compact version of the given values or the given values if compression did not improve on heap overhead.
+ */
+ public static PackedInts.Reader compress(PackedInts.Reader values, int length) {
+ return compress(values, values.size(), true);
+ }
+
+ /**
+ * Create a compact version of the given values from index 0 to length-1.
+ * @param values PackedInts with no special constraints.
+ * @param length the number of values to compress.
+ * @param allowSparse if true and is the default limits matches the input, a sparse representation will be created.
+ * @return a compact version of the given values or the given values if compression did not improve on heap overhead.
+ */
+ public static PackedInts.Reader compress(PackedInts.Reader values, int length, boolean allowSparse) {
+ return compress(values, length, allowSparse,
+ DEFAULT_MIN_TOTAL_VALUES_FOR_SPARSE,
+ DEFAULT_MIN_ZERO_VALUES_FOR_SPARSE,
+ DEFAULT_MIN_ZERO_VALUES_FRACTION_FOR_SPARSE);
+ }
+
+ /**
+ * Create a compact version of the given values from index 0 to length-1.
+ * @param values PackedInts with no special constraints.
+ * @param length the number of values to compress.
+ * @param allowSparse if true and is the default limits matches the input, a sparse representation will be created.
+ * @param minTotalSparse the minimum absolute number of 0-entries needed for a sparse representation.
+ * 0-entries are counted after minValue compression: {@code 3, 5, 3, 7, 16} has two 0-entries.
+ * @return a compact version of the given values or the given values if compression did not improve on heap overhead.
+ */
+ public static PackedInts.Reader compress(
+ PackedInts.Reader values, int length, boolean allowSparse,
+ int minTotalSparse, int minZeroSparse, double minZeroFractionSparse) {
+ if (length == 0) {
+ return PackedInts.getMutable(0, 1, PackedInts.DEFAULT);
+ }
+
+ final long min = getMin(values, length);
+ final long gcd = getGCD(values, length, min);
+ final long maxCompressed = getMax(values, length, min, gcd);
+
+ int zeroCount;
+ if (!isPossiblySparseCandidate(length, allowSparse, minTotalSparse) ||
+ !isSparseCandidate(values, length, true, minTotalSparse,
+ (zeroCount = countZeroes(values, length, min, gcd)), minZeroSparse, minZeroFractionSparse)) {
+ // TODO: Add abort-early if it becomes apparent that no space saving is possible
+ PackedInts.Mutable inner =
+ PackedInts.getMutable(length, PackedInts.bitsRequired(maxCompressed), PackedInts.DEFAULT);
+ for (int i = 0 ; i < length ; i++) {
+ inner.set(i, (values.get(i)-min)/gcd);
+ }
+ PackedInts.Reader comp = new CompressedReader(inner, min, gcd);
+ // Sanity check that compression worked and if not, return the original input
+ return comp.ramBytesUsed() < values.ramBytesUsed() ? comp : values;
+ }
+
+ // Sparsify
+ RankBitSet rank = new RankBitSet(length);
+ PackedInts.Mutable inner =
+ PackedInts.getMutable(values.size()-zeroCount, PackedInts.bitsRequired(maxCompressed), PackedInts.DEFAULT);
+ int valueIndex = 0;
+ for (int i = 0 ; i < length ; i++) {
+ long value = (values.get(i)-min)/gcd;
+ if (value != 0) {
+ rank.set(i);
+ inner.set(valueIndex++, value);
+ }
+ }
+ rank.buildRankCache();
+ PackedInts.Reader comp = new CompressedReader(inner, min, gcd, rank);
+ // Sanity check that compression worked and if not, return the original input
+ return comp.ramBytesUsed() < values.ramBytesUsed() ? comp : values;
+ }
+
+ // Fast check
+ private static boolean isPossiblySparseCandidate(int length, boolean allowSparse, int minTotalSparse) {
+ return allowSparse && minTotalSparse <= length;
+ }
+
+ // Also fast, but requires zeroCount which is slow to calculate
+ private static boolean isSparseCandidate(
+ PackedInts.Reader values, int length, boolean allowSparse, int minTotalSparse,
+ int zeroCount, int minZeroSparse, double minZeroFractionSparse) {
+ return allowSparse && minTotalSparse <= length &&
+ minZeroSparse < zeroCount && minZeroFractionSparse < 1.0 * zeroCount / length;
+ }
+
+ // Not very fast as is requires #length divisions.
+ private static int countZeroes(PackedInts.Reader values, int length, long min, final long gcd) {
+ int zeroCount = 0;
+ for (int i = 0 ; i < length ; i++) {
+ if ((values.get(i)-min)/gcd == 0) { // Hope the case where gcd==1 gets JITted. We could add a switch to be sure?
+ zeroCount++;
+ }
+ }
+ return zeroCount;
+ }
+
+ static class CompressedReader extends PackedInts.Reader {
+ private final PackedInts.Reader inner;
+ final long min;
+ final long gcd;
+ final RankBitSet rank;
+
+ CompressedReader(PackedInts.Reader inner, long min, long gcd) {
+ this(inner, min, gcd, null);
+ }
+
+ CompressedReader(PackedInts.Reader inner, long min, long gcd, RankBitSet rank) {
+ this.inner = inner;
+ this.min = min;
+ this.gcd = gcd;
+ this.rank = rank;
+ }
+
+ @Override
+ public int size() {
+ return rank == null ? inner.size() : rank.length();
+ }
+
+ @Override
+ public long get(int docID) {
+ // No rank: The value at the index
+ // Rank but no set bit: min*gcd
+ // Rank and set bit: (The value at the rank + min) * gcd
+ return (rank == null ? inner.get(docID) : rank.get(docID) ? inner.get(rank.rank(docID)) : 0) * gcd + min;
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return inner.ramBytesUsed() + (rank == null ? 0 : rank.ramBytesUsed());
+ }
+ }
+
+ private static long getMin(PackedInts.Reader values, int length) {
+ long min = Long.MAX_VALUE;
+ for (int i = 0 ; i < length ; i++) {
+ if (min > values.get(i)) {
+ min = values.get(i);
+ }
+ }
+ return min;
+ }
+
+ // GCD-code takes & adjusted from Lucene70DocValuesConsumer
+ private static long getGCD(final PackedInts.Reader values, final int length, final long min) {
+ long gcd = -1;
+
+ for (int i = 0 ; i < length ; i++) {
+ long value = values.get(i)-min;
+ if (value == 0) {
+ continue;
+ }
+ if (gcd == -1) {
+ gcd = value;
+ continue;
+ }
+
+ if (value < Long.MIN_VALUE / 2 || value > Long.MAX_VALUE / 2) {
+ // in that case v - minValue might overflow and make the GCD computation return
+ // wrong results. Since these extreme values are unlikely, we just discard
+ // GCD computation for them
+ gcd = 1;
+ } else { // minValue needs to be set first
+ gcd = MathUtil.gcd(gcd, value);
+ }
+
+ if (gcd == 1) {
+ break;
+ }
+ }
+ return gcd == -1 ? 1 : gcd;
+ }
+
+ private static long getMax(final PackedInts.Reader values, final int length, final long min, final long gcd) {
+ long rawMax = Long.MIN_VALUE;
+ for (int i = 0 ; i < length ; i++) {
+ long value = values.get(i);
+ if (value > rawMax) {
+ rawMax = value;
+ }
+ }
+ return (rawMax-min)/gcd;
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ad02762/lucene/core/src/java/org/apache/lucene/util/RankBitSet.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/util/RankBitSet.java b/lucene/core/src/java/org/apache/lucene/util/RankBitSet.java
new file mode 100644
index 0000000..3702c63
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/util/RankBitSet.java
@@ -0,0 +1,302 @@
+/*
+ * 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.lucene.util;
+
+import java.io.IOException;
+import java.util.Collection;
+
+import org.apache.lucene.search.DocIdSetIterator;
+
+/**
+ * Wrapper for OpenBitSet which creates and exposes a rank cache. The rank-cache scales to 2 billion bits.
+ *
+ * The rankCache has a long for every 2048 bits and thus has an overhead of 3.17% relative to the given bit set.
+ * Performance is O(1):
+ * 1 lookup in cache,
+ * a maximum of 3 sums,
+ * a maximum of 8 Long.bitCounts.
+ *
+ * Creation performance is equivalent to a full count of all set bits in the bit set O(n).
+ *
+ * Note: {@link #buildRankCache()} must be called once after the bit set has been created or changed and before
+ * calling {@link #rank(long)}.
+ *
+ * The design is based heavily on the article
+ * Space-Efficient, High-Performance Rank and Select Structures on Uncompressed Bit Sequences
+ * by Dong Zhou, David G. Andersen, Michael Kaminsky, Carnegie Mellon University, Intel Labs
+ * http://www.cs.cmu.edu/~dga/papers/zhou-sea2013.pdf
+ */
+// Note: If the total number of set bits is <= 65535, a faster rank cache would be a short for every 512 bits
+// This is not available in the current implementation.
+// Extending the rank beyond 2 billion bits could be done by dividing the bitmap into blocks of 2b bits and
+// introducing yet another table with a rank-origo for each 2b-block
+public class RankBitSet extends BitSet {
+ public static final int LOWER_BITS = 32; // Must be capable of addressing full Java array
+ public static final long LOWER_MASK = ~(~1L << (LOWER_BITS-1));
+ public static final int LOWER_OVER_BITS = 11;
+ public static final long LOWER_OVER_MASK = ~(~1L << (LOWER_OVER_BITS-1));
+ public static final int LOWER_OVER_SIZE = 2048; // Overflow bits handled by a lower block
+
+ public static final int BASIC_BITS = 10; // Needs to hold counts from 0-512 (513-1023 are never used)
+ public static final long BASIC_MASK = ~(~1L << (BASIC_BITS-1));
+ public static final int BASIC_OVER_BITS = 9;
+ public static final long BASIC_OVER_MASK = ~(~1L << (BASIC_OVER_BITS-1));
+ public static final int BASIC_OVER_SIZE = 512; // Overflow bits handled by a basic block
+ public static final int BASIC_WORDS = BASIC_OVER_SIZE /Long.SIZE; // word == long
+ /**
+ * Each entry is made up of 1 long<br/>
+ * Bits 63-32: 32 bit first-level absolute index.<br/>
+ * Bits 30+31 are unused. These could be used to signal all-set or all-unset for the block to spare a few cycles?
+ * Bits 29-0: 3 * 10 bit (0-1023) second-level relative index. Only numbers 0-512 are used.
+ */
+ private long[] rankCache = null;
+ private final FixedBitSet inner;
+ private final int wlen; // Number of words (longs with FixedBitSet) in inner
+
+ public RankBitSet(int numBits) {
+ this(new FixedBitSet(numBits));
+ }
+
+ public RankBitSet(FixedBitSet inner) {
+ this.inner = inner;
+ wlen = inner.getBits().length;
+ }
+
+ /**
+ * Must be called after bits has changed and before {@link #rank} is called.
+ */
+ public void buildRankCache() {
+ rankCache = new long[(length() >>> LOWER_OVER_BITS)+1];
+ long total = 0;
+ int lower = 0 ;
+ while (lower * LOWER_OVER_SIZE < length()) { // Full lower block processing
+ final int origoWordIndex = (lower * LOWER_OVER_SIZE) >>> 6;
+ // TODO: Some conditionals could be spared by checking once if all basic blocks are within size
+ final long basic1 = origoWordIndex + BASIC_WORDS <= wlen ?
+ BitUtil.pop_array(inner.getBits(), origoWordIndex, BASIC_WORDS) : 0;
+ final long basic2 = origoWordIndex + BASIC_WORDS*2 <= wlen ?
+ BitUtil.pop_array(inner.getBits(), origoWordIndex + BASIC_WORDS, BASIC_WORDS) : 0;
+ final long basic3 = origoWordIndex + BASIC_WORDS*3 <= wlen ?
+ BitUtil.pop_array(inner.getBits(), origoWordIndex + BASIC_WORDS *2, BASIC_WORDS) : 0;
+ final long basic4 = origoWordIndex + BASIC_WORDS*4 <= wlen ?
+ BitUtil.pop_array(inner.getBits(), origoWordIndex + BASIC_WORDS *3, BASIC_WORDS) : 0;
+ rankCache[lower] = total << (Long.SIZE-LOWER_BITS) |
+ basic1 << (BASIC_BITS *2) |
+ basic2 << BASIC_BITS |
+ basic3;
+ total += basic1 + basic2 + basic3 + basic4;
+ lower++;
+ }
+ }
+
+ /**
+ * Get the rank (number of set bits up to right before the index) for the given index in O(1).
+ * @param index offset in the originating bit set.
+ * @return the rank for the index.
+ */
+ public int rank(long index) {
+ final long cache = rankCache[((int) (index >>> LOWER_OVER_BITS))];
+ // lower cache (absolute)
+ long rank = cache >>> (Long.SIZE-LOWER_BITS);
+ int startBitIndex = (int) (index & ~LOWER_OVER_MASK);
+ // basic blocks (relative)
+ if (startBitIndex < index-BASIC_OVER_SIZE) {
+ rank += (cache >>> (BASIC_BITS*2)) & BASIC_MASK;
+ startBitIndex += BASIC_OVER_SIZE;
+ if (startBitIndex < index-BASIC_OVER_SIZE) {
+ rank += (cache >>> BASIC_BITS) & BASIC_MASK;
+ startBitIndex += BASIC_OVER_SIZE;
+ if (startBitIndex < index-BASIC_OVER_SIZE) {
+ rank += cache & BASIC_MASK;
+ startBitIndex += BASIC_OVER_SIZE;
+ }
+ }
+ }
+ // long.bitcount (relative)
+ while(startBitIndex < index-Long.SIZE) {
+ rank += Long.bitCount(inner.getBits()[startBitIndex >>> 6]);
+ startBitIndex += Long.SIZE;
+ }
+ // Single bits (relative)
+ if (startBitIndex < index) {
+/* System.out.println(String.format(Locale.ENGLISH,
+ "startBitIndex=%d, index=%d, getBits()[startBitIndex>>>6=%d]=%s, index-startBitIndex=%d, mask=%s",
+ startBitIndex, index, startBitIndex>>>6, Long.toBinaryString(getBits()[startBitIndex>>>6]),
+ index-startBitIndex, Long.toBinaryString(~(~1L << (index-startBitIndex-1)))));*/
+ rank += Long.bitCount(inner.getBits()[startBitIndex >>> 6] & ~(~1L << (index-startBitIndex-1)));
+ }
+// for (int i = startBitIndex ; i < index ; i++) {
+// rank += fastGet(i) ? 1 : 0;
+// }
+ return (int) rank;
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return RamUsageEstimator.alignObjectSize(RamUsageEstimator.NUM_BYTES_OBJECT_REF*2 +
+ Integer.BYTES + Long.BYTES) +
+ inner.ramBytesUsed() +
+ (rankCache == null ? 0 :
+ RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + Long.BYTES*rankCache.length);
+ }
+
+ /* Delegations to inner bit set below */
+
+ public static FixedBitSet ensureCapacity(FixedBitSet bits, int numBits) {
+ return FixedBitSet.ensureCapacity(bits, numBits);
+ }
+
+ public static int bits2words(int numBits) {
+ return FixedBitSet.bits2words(numBits);
+ }
+
+ public static long intersectionCount(FixedBitSet a, FixedBitSet b) {
+ return FixedBitSet.intersectionCount(a, b);
+ }
+
+ public static long unionCount(FixedBitSet a, FixedBitSet b) {
+ return FixedBitSet.unionCount(a, b);
+ }
+
+ public static long andNotCount(FixedBitSet a, FixedBitSet b) {
+ return FixedBitSet.andNotCount(a, b);
+ }
+
+ @Override
+ public int length() {
+ return inner.length();
+ }
+
+ public long[] getBits() {
+ return inner.getBits();
+ }
+
+ @Override
+ public int cardinality() {
+ return inner.cardinality();
+ }
+
+ @Override
+ public boolean get(int index) {
+ return inner.get(index);
+ }
+
+ @Override
+ public void set(int index) {
+ inner.set(index);
+ }
+
+ public boolean getAndSet(int index) {
+ return inner.getAndSet(index);
+ }
+
+ @Override
+ public void clear(int index) {
+ inner.clear(index);
+ }
+
+ public boolean getAndClear(int index) {
+ return inner.getAndClear(index);
+ }
+
+ @Override
+ public int nextSetBit(int index) {
+ return inner.nextSetBit(index);
+ }
+
+ @Override
+ public int prevSetBit(int index) {
+ return inner.prevSetBit(index);
+ }
+
+ @Override
+ public void or(DocIdSetIterator iter) throws IOException {
+ inner.or(iter);
+ }
+
+ public void or(FixedBitSet other) {
+ inner.or(other);
+ }
+
+ public void xor(FixedBitSet other) {
+ inner.xor(other);
+ }
+
+ public void xor(DocIdSetIterator iter) throws IOException {
+ inner.xor(iter);
+ }
+
+ public boolean intersects(FixedBitSet other) {
+ return inner.intersects(other);
+ }
+
+ public void and(FixedBitSet other) {
+ inner.and(other);
+ }
+
+ public void andNot(FixedBitSet other) {
+ inner.andNot(other);
+ }
+
+ public boolean scanIsEmpty() {
+ return inner.scanIsEmpty();
+ }
+
+ public void flip(int startIndex, int endIndex) {
+ inner.flip(startIndex, endIndex);
+ }
+
+ public void flip(int index) {
+ inner.flip(index);
+ }
+
+ public void set(int startIndex, int endIndex) {
+ inner.set(startIndex, endIndex);
+ }
+
+ @Override
+ public void clear(int startIndex, int endIndex) {
+ inner.clear(startIndex, endIndex);
+ }
+
+ @Override
+ public int hashCode() {
+ return inner.hashCode();
+ }
+
+ public static FixedBitSet copyOf(Bits bits) {
+ return FixedBitSet.copyOf(bits);
+ }
+
+ public Bits asReadOnlyBits() {
+ return inner.asReadOnlyBits();
+ }
+
+ public static BitSet of(DocIdSetIterator it, int maxDoc) throws IOException {
+ return BitSet.of(it, maxDoc);
+ }
+
+ @Override
+ public int approximateCardinality() {
+ return inner.approximateCardinality();
+ }
+
+ @Override
+ public Collection<Accountable> getChildResources() {
+ return inner.getChildResources();
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ad02762/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestLongCompressor.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestLongCompressor.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestLongCompressor.java
new file mode 100644
index 0000000..bb87dc4
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene70/TestLongCompressor.java
@@ -0,0 +1,87 @@
+/*
+ * 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.lucene.codecs.lucene70;
+
+import java.util.Locale;
+import java.util.Random;
+
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.packed.PackedInts;
+
+public class TestLongCompressor extends LuceneTestCase {
+
+ // Simple money test that builds a collection of random longs, compresses them with LongCompressor and
+ // checks if all values from the compressed version are equal to the source
+ public void testLongCompressorMonkey() {
+ final int RUNS = 10;
+ final int[] MAX_SIZES = new int[]{0, 1, 10, 1000, 100_000};
+ final int[] MAX_VALUE = new int[]{0, 1, 10, 1000, 100_000};
+ for (int run = 0 ; run < RUNS ; run++) {
+ for (int maxSize: MAX_SIZES) {
+ int size = maxSize == 0 ? 0 : random().nextInt(maxSize);
+ for (int maxValue: MAX_VALUE) {
+ int minValue = maxValue == 0 ? 0 : random().nextInt(maxValue);
+ double minChance = random().nextDouble();
+ longCompressorMonkeyTest(run, size, minValue, maxValue, minChance, random().nextLong());
+ }
+ }
+ }
+ }
+
+ public void testVerySparse() {
+ final int SIZE = 674932;
+ final int EVERY = SIZE/896;
+ PackedInts.Mutable ranks = PackedInts.getMutable(674932, 16, PackedInts.DEFAULT);
+ for (int i = 0 ; i < SIZE; i+=EVERY) {
+ ranks.set(i, random().nextInt(65535));
+ }
+ PackedInts.Reader sparsed = LongCompressor.compress(ranks);
+ assertFalse("The input and the sparsed should not be the same", ranks == sparsed);
+ }
+
+ private void longCompressorMonkeyTest(
+ int run, int size, int minValue, int maxValue, double minChance, long randomSeed) {
+ final String description = String.format(Locale.ENGLISH,
+ "run=%d, size=%d, minValue=%d, maxValue=%d, minChance=%1.2f, seed=%d",
+ run, size, minValue, maxValue, minChance, randomSeed);
+ Random innerRandom = new Random(randomSeed);
+ PackedInts.Mutable expected = PackedInts.getMutable(size, PackedInts.bitsRequired(maxValue), PackedInts.DEFAULT);
+ for (int i = 0 ; i < size ; i++) {
+ if (innerRandom.nextDouble() <= minChance) {
+ continue;
+ }
+ expected.set(i, maxValue-minValue == 0 ? minValue : innerRandom.nextInt(maxValue-minValue)+minValue);
+ }
+ assertSparseValid(description, expected);
+ }
+
+ private void assertSparseValid(String description, PackedInts.Reader values) {
+ try {
+ PackedInts.Reader sparsed = LongCompressor.compress(values, values.size());
+
+ for (int i = 0; i < values.size(); i++) {
+ assertEquals("The value at index " + i + " should be as expected for " + description,
+ values.get(i), sparsed.get(i));
+ }
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected Exception for " + description, e);
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ad02762/lucene/core/src/test/org/apache/lucene/util/TestRankBitSet.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestRankBitSet.java b/lucene/core/src/test/org/apache/lucene/util/TestRankBitSet.java
new file mode 100644
index 0000000..677cc22
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/util/TestRankBitSet.java
@@ -0,0 +1,107 @@
+/*
+ * 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.lucene.util;
+
+import java.util.Locale;
+import java.util.Random;
+
+public class TestRankBitSet extends LuceneTestCase {
+
+ public void testSingleWord() {
+ RankBitSet rank = new RankBitSet(60);
+ rank.set(20);
+ rank.buildRankCache();
+
+ assertEquals("The rank at index 20 should be correct", 0, rank.rank(20));
+ assertEquals("The rank at index 21 should be correct", 1, rank.rank(21));
+ }
+
+ public void testSecondWord() {
+ RankBitSet rank = new RankBitSet(100);
+ rank.set(70);
+ rank.buildRankCache();
+
+ assertEquals("The rank at index 70 should be correct", 0, rank.rank(70));
+ assertEquals("The rank at index 71 should be correct", 1, rank.rank(71));
+ }
+
+ public void testThirdWord() {
+ RankBitSet rank = new RankBitSet(200);
+ rank.set(130);
+ rank.buildRankCache();
+
+ assertEquals("The rank at index 130 should be correct", 0, rank.rank(130));
+ assertEquals("The rank at index 131 should be correct", 1, rank.rank(131));
+ }
+
+ public void testSecondLower() {
+ RankBitSet rank = new RankBitSet(3000);
+ rank.set(2500);
+ rank.buildRankCache();
+
+ assertEquals("The rank at index 2500 should be correct", 0, rank.rank(2500));
+ assertEquals("The rank at index 2500 should be correct", 1, rank.rank(2501));
+ }
+
+ public void testSpecific282() {
+ RankBitSet rank = new RankBitSet(448);
+ rank.set(282);
+ rank.buildRankCache();
+
+ assertEquals("The rank at index 288 should be correct", 1, rank.rank(288));
+ }
+
+ public void testSpecific1031() {
+ RankBitSet rank = new RankBitSet(1446);
+ rank.set(1031);
+ rank.buildRankCache();
+
+ assertEquals("The rank at index 1057 should be correct", 1, rank.rank(1057));
+ }
+
+ public void testMonkeys() {
+ monkey(20, 8000, 40);
+ }
+
+ @Slow
+ public void testManyMonkeys() {
+ monkey(20, 100000, 400);
+ }
+
+ public void monkey(int runs, int sizeMax, int setMax) {
+ Random random = random();
+ //Random random = new Random(87);
+ for (int run = 0 ; run < runs ; run++) {
+ final int size = random.nextInt(sizeMax-1)+1;
+ RankBitSet rank = new RankBitSet(size);
+ int doSet = random.nextInt(setMax);
+ for (int s = 0 ; s < doSet ; s++) {
+ int index = random.nextInt(size);
+ rank.set(index);
+ }
+ rank.buildRankCache();
+ int setbits = 0;
+ for (int i = 0 ; i < size ; i++) {
+ assertEquals(String.format(Locale.ENGLISH, "run=%d, index=%d/%d, setbits=%d", run, i, size, setbits),
+ setbits, rank.rank(i));
+ if (rank.get(i)) {
+ setbits++;
+ }
+ }
+ }
+ }
+}
[21/37] lucene-solr:jira/http2: LUCENE-8564: Add GraphTokenFilter
Posted by da...@apache.org.
LUCENE-8564: Add GraphTokenFilter
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/f5867a14
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/f5867a14
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/f5867a14
Branch: refs/heads/jira/http2
Commit: f5867a1413189675cf69ea88412237e32429786e
Parents: 6c11161
Author: Alan Woodward <ro...@apache.org>
Authored: Mon Dec 3 12:17:58 2018 +0000
Committer: Alan Woodward <ro...@apache.org>
Committed: Tue Dec 4 09:47:42 2018 +0000
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 +
.../analysis/shingle/FixedShingleFilter.java | 269 ++++--------------
.../shingle/FixedShingleFilterTest.java | 19 +-
.../lucene/analysis/GraphTokenFilter.java | 284 +++++++++++++++++++
.../lucene/analysis/TestGraphTokenFilter.java | 236 +++++++++++++++
.../lucene/analysis/TestGraphTokenizers.java | 2 +-
.../java/org/apache/lucene/analysis/Token.java | 7 +
7 files changed, 591 insertions(+), 230 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f5867a14/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 349d64d..fc609a5 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -155,6 +155,10 @@ New Features
* LUCENE-8216: Added a new BM25FQuery in sandbox to blend statistics across several fields
using the BM25F formula. (Adrien Grand, Jim Ferenczi)
+* LUCENE-8564: GraphTokenFilter is an abstract class useful for token filters that need
+ to read-ahead in the token stream and take into account graph structures. This
+ also changes FixedShingleFilter to extend GraphTokenFilter (Alan Woodward)
+
Improvements
* LUCENE-7997: Add BaseSimilarityTestCase to sanity check similarities.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f5867a14/lucene/analysis/common/src/java/org/apache/lucene/analysis/shingle/FixedShingleFilter.java
----------------------------------------------------------------------
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/shingle/FixedShingleFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/shingle/FixedShingleFilter.java
index cf82363..8f7eb95 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/shingle/FixedShingleFilter.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/shingle/FixedShingleFilter.java
@@ -18,16 +18,14 @@
package org.apache.lucene.analysis.shingle;
import java.io.IOException;
-import java.util.ArrayDeque;
-import java.util.Deque;
-import org.apache.lucene.analysis.TokenFilter;
+import org.apache.lucene.analysis.GraphTokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
+import org.apache.lucene.analysis.tokenattributes.CharTermAttributeImpl;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
-import org.apache.lucene.util.AttributeSource;
/**
* A FixedShingleFilter constructs shingles (token n-grams) from a token stream.
@@ -47,27 +45,20 @@ import org.apache.lucene.util.AttributeSource;
*
* @lucene.experimental
*/
-public final class FixedShingleFilter extends TokenFilter {
+public final class FixedShingleFilter extends GraphTokenFilter {
- private final Deque<Token> tokenPool = new ArrayDeque<>();
-
- private static final int MAX_SHINGLE_STACK_SIZE = 1000;
private static final int MAX_SHINGLE_SIZE = 4;
private final int shingleSize;
private final String tokenSeparator;
-
- private final Token gapToken = new Token(new AttributeSource());
- private final Token endToken = new Token(new AttributeSource());
+ private final String fillerToken;
private final PositionIncrementAttribute incAtt = addAttribute(PositionIncrementAttribute.class);
private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
- private Token[] currentShingleTokens;
- private int currentShingleStackSize;
- private boolean inputStreamExhausted = false;
+ private final CharTermAttribute buffer = new CharTermAttributeImpl();
/**
* Creates a FixedShingleFilter over an input token stream
@@ -89,228 +80,82 @@ public final class FixedShingleFilter extends TokenFilter {
*/
public FixedShingleFilter(TokenStream input, int shingleSize, String tokenSeparator, String fillerToken) {
super(input);
+
if (shingleSize <= 1 || shingleSize > MAX_SHINGLE_SIZE) {
throw new IllegalArgumentException("Shingle size must be between 2 and " + MAX_SHINGLE_SIZE + ", got " + shingleSize);
}
this.shingleSize = shingleSize;
this.tokenSeparator = tokenSeparator;
- this.gapToken.termAtt.setEmpty().append(fillerToken);
- this.currentShingleTokens = new Token[shingleSize];
+ this.fillerToken = fillerToken;
}
@Override
public boolean incrementToken() throws IOException {
- int posInc = 0;
- if (nextShingle() == false) {
- Token nextRoot = nextTokenInStream(currentShingleTokens[0]);
- if (nextRoot == endToken)
- return false;
- recycleToken(currentShingleTokens[0]);
- if (resetShingleRoot(nextRoot) == false) {
+
+ int shinglePosInc;
+ if (incrementGraph() == false) {
+ if (incrementBaseToken() == false) {
return false;
}
- posInc = currentShingleTokens[0].posInc();
+ // starting a shingle at a new base position, use base position increment
+ shinglePosInc = incAtt.getPositionIncrement();
}
- clearAttributes();
- incAtt.setPositionIncrement(posInc);
- offsetAtt.setOffset(currentShingleTokens[0].startOffset(), lastTokenInShingle().endOffset());
- termAtt.setEmpty();
- termAtt.append(currentShingleTokens[0].term());
- typeAtt.setType("shingle");
- for (int i = 1; i < shingleSize; i++) {
- termAtt.append(tokenSeparator).append(currentShingleTokens[i].term());
- }
- return true;
- }
-
- @Override
- public void reset() throws IOException {
- super.reset();
- this.tokenPool.clear();
- this.currentShingleTokens[0] = null;
- this.inputStreamExhausted = false;
- this.currentShingleStackSize = 0;
- }
-
- @Override
- public void end() throws IOException {
- if (inputStreamExhausted == false) {
- finishInnerStream();
+ else {
+ // starting a new shingle at the same base with a different graph, use a 0
+ // position increment
+ shinglePosInc = 0;
}
- clearAttributes();
- this.offsetAtt.setOffset(0, endToken.endOffset());
- this.incAtt.setPositionIncrement(endToken.posInc());
- }
-
- private void finishInnerStream() throws IOException {
- input.end();
- inputStreamExhausted = true;
- // check for gaps at the end of the tokenstream
- endToken.posIncAtt.setPositionIncrement(this.incAtt.getPositionIncrement());
- OffsetAttribute inputOffsets = input.getAttribute(OffsetAttribute.class);
- endToken.offsetAtt.setOffset(inputOffsets.startOffset(), inputOffsets.endOffset());
- }
- private Token lastTokenInShingle() {
- int lastTokenIndex = shingleSize - 1;
- while (currentShingleTokens[lastTokenIndex] == gapToken) {
- lastTokenIndex--;
- }
- return currentShingleTokens[lastTokenIndex];
- }
+ final int startOffset = offsetAtt.startOffset();
+ int endOffset = offsetAtt.endOffset();
+ this.buffer.setEmpty();
+ this.buffer.append(termAtt);
- private boolean resetShingleRoot(Token token) throws IOException {
- this.currentShingleTokens[0] = token;
+ // build the shingle by iterating over the current graph, adding
+ // filler tokens if we encounter gaps
for (int i = 1; i < shingleSize; i++) {
- Token current = nextTokenInGraph(this.currentShingleTokens[i - 1]);
- if (current == endToken) {
- if (endToken.posInc() + i >= shingleSize) {
- // end tokens are a special case, because their posIncs are always
- // due to stopwords. Therefore, we can happily append gap tokens
- // to the end of the current shingle
- for (int j = i; j < shingleSize; j++) {
- this.currentShingleTokens[i] = gapToken;
- i++;
- }
- return true;
+ if (incrementGraphToken() == false) {
+ // we've reached the end of the token stream, check for trailing
+ // positions and add fillers if necessary
+ int trailingPositions = getTrailingPositions();
+ if (i + trailingPositions < shingleSize) {
+ // not enough trailing positions to make a full shingle
+ return false;
}
- return false;
- }
- if (current.posInc() > 1) {
- // insert gaps into the shingle list
- for (int j = 1; j < current.posInc(); j++) {
- this.currentShingleTokens[i] = gapToken;
+ while (i < shingleSize) {
+ this.buffer.append(tokenSeparator).append(fillerToken);
i++;
- if (i >= shingleSize)
- return true;
}
+ break;
}
- this.currentShingleTokens[i] = current;
- }
- return true;
- }
-
- private boolean nextShingle() throws IOException {
- return currentShingleTokens[0] != null && advanceStack();
- }
-
- // check if the next token in the tokenstream is at the same position as this one
- private boolean lastInStack(Token token) throws IOException {
- Token next = nextTokenInStream(token);
- return next == endToken || next.posInc() != 0;
- }
-
- private boolean advanceStack() throws IOException {
- for (int i = shingleSize - 1; i >= 1; i--) {
- if (currentShingleTokens[i] != gapToken && lastInStack(currentShingleTokens[i]) == false) {
- currentShingleTokens[i] = nextTokenInStream(currentShingleTokens[i]);
- for (int j = i + 1; j < shingleSize; j++) {
- currentShingleTokens[j] = nextTokenInGraph(currentShingleTokens[j - 1]);
+ int posInc = incAtt.getPositionIncrement();
+ if (posInc > 1) {
+ // if we have a posInc > 1, we need to fill in the gaps
+ if (i + posInc > shingleSize) {
+ // if the posInc is greater than the shingle size, we need to add fillers
+ // up to the shingle size but no further
+ while (i < shingleSize) {
+ this.buffer.append(tokenSeparator).append(fillerToken);
+ i++;
+ }
+ break;
}
- if (currentShingleStackSize++ > MAX_SHINGLE_STACK_SIZE) {
- throw new IllegalStateException("Too many shingles (> " + MAX_SHINGLE_STACK_SIZE + ") at term [" + currentShingleTokens[0].term() + "]");
+ // otherwise just add them in as far as we need
+ while (posInc > 1) {
+ this.buffer.append(tokenSeparator).append(fillerToken);
+ posInc--;
+ i++;
}
- return true;
}
+ this.buffer.append(tokenSeparator).append(termAtt);
+ endOffset = offsetAtt.endOffset();
}
- currentShingleStackSize = 0;
- return false;
- }
-
- private Token newToken() {
- Token token = tokenPool.size() == 0 ? new Token(this.cloneAttributes()) : tokenPool.removeFirst();
- token.reset(this);
- return token;
- }
-
- private void recycleToken(Token token) {
- if (token == null)
- return;
- token.nextToken = null;
- tokenPool.add(token);
- }
-
- // for testing
- int instantiatedTokenCount() {
- int tokenCount = tokenPool.size() + 1;
- if (currentShingleTokens[0] == endToken || currentShingleTokens[0] == null)
- return tokenCount;
- for (Token t = currentShingleTokens[0]; t != endToken && t != null; t = t.nextToken) {
- tokenCount++;
- }
- return tokenCount;
- }
-
- private Token nextTokenInGraph(Token token) throws IOException {
- do {
- token = nextTokenInStream(token);
- if (token == endToken) {
- return endToken;
- }
- } while (token.posInc() == 0);
- return token;
- }
-
- private Token nextTokenInStream(Token token) throws IOException {
- if (token != null && token.nextToken != null) {
- return token.nextToken;
- }
- if (input.incrementToken() == false) {
- finishInnerStream();
- if (token == null) {
- return endToken;
- } else {
- token.nextToken = endToken;
- return endToken;
- }
- }
- if (token == null) {
- return newToken();
- }
- token.nextToken = newToken();
- return token.nextToken;
- }
-
- private static class Token {
- final AttributeSource attSource;
- final PositionIncrementAttribute posIncAtt;
- final CharTermAttribute termAtt;
- final OffsetAttribute offsetAtt;
-
- Token nextToken;
-
- Token(AttributeSource attSource) {
- this.attSource = attSource;
- this.posIncAtt = attSource.addAttribute(PositionIncrementAttribute.class);
- this.termAtt = attSource.addAttribute(CharTermAttribute.class);
- this.offsetAtt = attSource.addAttribute(OffsetAttribute.class);
- }
-
- int posInc() {
- return this.posIncAtt.getPositionIncrement();
- }
-
- CharSequence term() {
- return this.termAtt;
- }
-
- int startOffset() {
- return this.offsetAtt.startOffset();
- }
-
- int endOffset() {
- return this.offsetAtt.endOffset();
- }
-
- void reset(AttributeSource attSource) {
- attSource.copyTo(this.attSource);
- this.nextToken = null;
- }
-
- @Override
- public String toString() {
- return term() + "(" + startOffset() + "," + endOffset() + ") " + posInc();
- }
+ clearAttributes();
+ this.offsetAtt.setOffset(startOffset, endOffset);
+ this.incAtt.setPositionIncrement(shinglePosInc);
+ this.termAtt.setEmpty().append(buffer);
+ this.typeAtt.setType("shingle");
+ return true;
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f5867a14/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/FixedShingleFilterTest.java
----------------------------------------------------------------------
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/FixedShingleFilterTest.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/FixedShingleFilterTest.java
index f5031b3..85c7dc6 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/FixedShingleFilterTest.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/FixedShingleFilterTest.java
@@ -163,6 +163,8 @@ public class FixedShingleFilterTest extends BaseTokenStreamTestCase {
public void testIncomingGraphs() throws IOException {
+ // b/a c b/a d
+
TokenStream ts = new CannedTokenStream(
new Token("b", 0, 1),
new Token("a", 0, 0, 1),
@@ -208,21 +210,4 @@ public class FixedShingleFilterTest extends BaseTokenStreamTestCase {
assertEquals("Shingle size must be between 2 and 4, got 5", e2.getMessage());
}
- public void testShingleCountLimits() {
-
- Token[] tokens = new Token[5000];
- tokens[0] = new Token("term", 1, 0, 1);
- tokens[1] = new Token("term1", 1, 2, 3);
- for (int i = 2; i < 5000; i++) {
- tokens[i] = new Token("term" + i, 0, 2, 3);
- }
-
- Exception e = expectThrows(IllegalStateException.class, () -> {
- TokenStream ts = new FixedShingleFilter(new CannedTokenStream(tokens), 2);
- ts.reset();
- while (ts.incrementToken()) {}
- });
- assertEquals("Too many shingles (> 1000) at term [term]", e.getMessage());
- }
-
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f5867a14/lucene/core/src/java/org/apache/lucene/analysis/GraphTokenFilter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/GraphTokenFilter.java b/lucene/core/src/java/org/apache/lucene/analysis/GraphTokenFilter.java
new file mode 100644
index 0000000..9c1e02e
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/analysis/GraphTokenFilter.java
@@ -0,0 +1,284 @@
+/*
+ * 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.lucene.analysis;
+
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+
+import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
+import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
+import org.apache.lucene.analysis.tokenattributes.PositionLengthAttribute;
+import org.apache.lucene.util.AttributeSource;
+
+/**
+ * An abstract TokenFilter that exposes its input stream as a graph
+ *
+ * Call {@link #incrementBaseToken()} to move the root of the graph to the next
+ * position in the TokenStream, {@link #incrementGraphToken()} to move along
+ * the current graph, and {@link #incrementGraph()} to reset to the next graph
+ * based at the current root.
+ *
+ * For example, given the stream 'a b/c:2 d e`, then with the base token at
+ * 'a', incrementGraphToken() will produce the stream 'a b d e', and then
+ * after calling incrementGraph() will produce the stream 'a c e'.
+ */
+public abstract class GraphTokenFilter extends TokenFilter {
+
+ private final Deque<Token> tokenPool = new ArrayDeque<>();
+ private final List<Token> currentGraph = new ArrayList<>();
+
+ /**
+ * The maximum permitted number of routes through a graph
+ */
+ public static final int MAX_GRAPH_STACK_SIZE = 1000;
+
+ /**
+ * The maximum permitted read-ahead in the token stream
+ */
+ public static final int MAX_TOKEN_CACHE_SIZE = 100;
+
+ private Token baseToken;
+ private int graphDepth;
+ private int graphPos;
+ private int trailingPositions = -1;
+ private int finalOffsets = -1;
+
+ private int stackSize;
+ private int cacheSize;
+
+ private final PositionIncrementAttribute posIncAtt;
+ private final OffsetAttribute offsetAtt;
+
+ /**
+ * Create a new GraphTokenFilter
+ */
+ public GraphTokenFilter(TokenStream input) {
+ super(input);
+ this.posIncAtt = input.addAttribute(PositionIncrementAttribute.class);
+ this.offsetAtt = input.addAttribute(OffsetAttribute.class);
+ }
+
+ /**
+ * Move the root of the graph to the next token in the wrapped TokenStream
+ *
+ * @return {@code false} if the underlying stream is exhausted
+ */
+ protected final boolean incrementBaseToken() throws IOException {
+ stackSize = 0;
+ graphDepth = 0;
+ graphPos = 0;
+ Token oldBase = baseToken;
+ baseToken = nextTokenInStream(baseToken);
+ if (baseToken == null) {
+ return false;
+ }
+ currentGraph.clear();
+ currentGraph.add(baseToken);
+ baseToken.attSource.copyTo(this);
+ recycleToken(oldBase);
+ return true;
+ }
+
+ /**
+ * Move to the next token in the current route through the graph
+ *
+ * @return {@code false} if there are not more tokens in the current graph
+ */
+ protected final boolean incrementGraphToken() throws IOException {
+ if (graphPos < graphDepth) {
+ graphPos++;
+ currentGraph.get(graphPos).attSource.copyTo(this);
+ return true;
+ }
+ Token token = nextTokenInGraph(currentGraph.get(graphDepth));
+ if (token == null) {
+ return false;
+ }
+ graphDepth++;
+ graphPos++;
+ currentGraph.add(graphDepth, token);
+ token.attSource.copyTo(this);
+ return true;
+ }
+
+ /**
+ * Reset to the root token again, and move down the next route through the graph
+ *
+ * @return false if there are no more routes through the graph
+ */
+ protected final boolean incrementGraph() throws IOException {
+ if (baseToken == null) {
+ return false;
+ }
+ graphPos = 0;
+ for (int i = graphDepth; i >= 1; i--) {
+ if (lastInStack(currentGraph.get(i)) == false) {
+ currentGraph.set(i, nextTokenInStream(currentGraph.get(i)));
+ for (int j = i + 1; j < graphDepth; j++) {
+ currentGraph.set(j, nextTokenInGraph(currentGraph.get(j)));
+ }
+ if (stackSize++ > MAX_GRAPH_STACK_SIZE) {
+ throw new IllegalStateException("Too many graph paths (> " + MAX_GRAPH_STACK_SIZE + ")");
+ }
+ currentGraph.get(0).attSource.copyTo(this);
+ graphDepth = i;
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return the number of trailing positions at the end of the graph
+ *
+ * NB this should only be called after {@link #incrementGraphToken()} has returned {@code false}
+ */
+ public int getTrailingPositions() {
+ return trailingPositions;
+ }
+
+ @Override
+ public void end() throws IOException {
+ if (trailingPositions == -1) {
+ input.end();
+ trailingPositions = posIncAtt.getPositionIncrement();
+ finalOffsets = offsetAtt.endOffset();
+ }
+ else {
+ endAttributes();
+ this.posIncAtt.setPositionIncrement(trailingPositions);
+ this.offsetAtt.setOffset(finalOffsets, finalOffsets);
+ }
+ }
+
+ @Override
+ public void reset() throws IOException {
+ input.reset();
+ // new attributes can be added between reset() calls, so we can't reuse
+ // token objects from a previous run
+ tokenPool.clear();
+ cacheSize = 0;
+ graphDepth = 0;
+ trailingPositions = -1;
+ finalOffsets = -1;
+ baseToken = null;
+ }
+
+ int cachedTokenCount() {
+ return cacheSize;
+ }
+
+ private Token newToken() {
+ if (tokenPool.size() == 0) {
+ cacheSize++;
+ if (cacheSize > MAX_TOKEN_CACHE_SIZE) {
+ throw new IllegalStateException("Too many cached tokens (> " + MAX_TOKEN_CACHE_SIZE + ")");
+ }
+ return new Token(this.cloneAttributes());
+ }
+ Token token = tokenPool.removeFirst();
+ token.reset(input);
+ return token;
+ }
+
+ private void recycleToken(Token token) {
+ if (token == null)
+ return;
+ token.nextToken = null;
+ tokenPool.add(token);
+ }
+
+ private Token nextTokenInGraph(Token token) throws IOException {
+ int remaining = token.length();
+ do {
+ token = nextTokenInStream(token);
+ if (token == null) {
+ return null;
+ }
+ remaining -= token.posInc();
+ } while (remaining > 0);
+ return token;
+ }
+
+ // check if the next token in the tokenstream is at the same position as this one
+ private boolean lastInStack(Token token) throws IOException {
+ Token next = nextTokenInStream(token);
+ return next == null || next.posInc() != 0;
+ }
+
+ private Token nextTokenInStream(Token token) throws IOException {
+ if (token != null && token.nextToken != null) {
+ return token.nextToken;
+ }
+ if (this.trailingPositions != -1) {
+ // already hit the end
+ return null;
+ }
+ if (input.incrementToken() == false) {
+ input.end();
+ trailingPositions = posIncAtt.getPositionIncrement();
+ finalOffsets = offsetAtt.endOffset();
+ return null;
+ }
+ if (token == null) {
+ return newToken();
+ }
+ token.nextToken = newToken();
+ return token.nextToken;
+ }
+
+ private static class Token {
+
+ final AttributeSource attSource;
+ final PositionIncrementAttribute posIncAtt;
+ final PositionLengthAttribute lengthAtt;
+ Token nextToken;
+
+ Token(AttributeSource attSource) {
+ this.attSource = attSource;
+ this.posIncAtt = attSource.addAttribute(PositionIncrementAttribute.class);
+ boolean hasLengthAtt = attSource.hasAttribute(PositionLengthAttribute.class);
+ this.lengthAtt = hasLengthAtt ? attSource.addAttribute(PositionLengthAttribute.class) : null;
+ }
+
+ int posInc() {
+ return this.posIncAtt.getPositionIncrement();
+ }
+
+ int length() {
+ if (this.lengthAtt == null) {
+ return 1;
+ }
+ return this.lengthAtt.getPositionLength();
+ }
+
+ void reset(AttributeSource attSource) {
+ attSource.copyTo(this.attSource);
+ this.nextToken = null;
+ }
+
+ @Override
+ public String toString() {
+ return attSource.toString();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f5867a14/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenFilter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenFilter.java b/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenFilter.java
new file mode 100644
index 0000000..d3a476f
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenFilter.java
@@ -0,0 +1,236 @@
+/*
+ * 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.lucene.analysis;
+
+import java.io.IOException;
+import java.io.StringReader;
+
+import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
+import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
+
+public class TestGraphTokenFilter extends BaseTokenStreamTestCase {
+
+ static class TestFilter extends GraphTokenFilter {
+
+ public TestFilter(TokenStream input) {
+ super(input);
+ }
+
+ @Override
+ public final boolean incrementToken() throws IOException {
+ return incrementBaseToken();
+ }
+ }
+
+ public void testGraphTokenStream() throws IOException {
+
+ TestGraphTokenizers.GraphTokenizer tok = new TestGraphTokenizers.GraphTokenizer();
+ GraphTokenFilter graph = new TestFilter(tok);
+
+ CharTermAttribute termAtt = graph.addAttribute(CharTermAttribute.class);
+ PositionIncrementAttribute posIncAtt = graph.addAttribute(PositionIncrementAttribute.class);
+
+ tok.setReader(new StringReader("a b/c d e/f:3 g/h i j k"));
+ tok.reset();
+
+ assertFalse(graph.incrementGraph());
+ assertEquals(0, graph.cachedTokenCount());
+
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("a", termAtt.toString());
+ assertEquals(1, posIncAtt.getPositionIncrement());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("b", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("d", termAtt.toString());
+ assertTrue(graph.incrementGraph());
+ assertEquals("a", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("c", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("d", termAtt.toString());
+ assertFalse(graph.incrementGraph());
+ assertEquals(5, graph.cachedTokenCount());
+
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("b", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("d", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("e", termAtt.toString());
+ assertTrue(graph.incrementGraph());
+ assertEquals("b", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("d", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("f", termAtt.toString());
+ assertFalse(graph.incrementGraph());
+ assertEquals(6, graph.cachedTokenCount());
+
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("c", termAtt.toString());
+ assertEquals(0, posIncAtt.getPositionIncrement());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("d", termAtt.toString());
+ assertFalse(graph.incrementGraph());
+ assertEquals(6, graph.cachedTokenCount());
+
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("d", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("e", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("g", termAtt.toString());
+ assertTrue(graph.incrementGraph());
+ assertEquals("d", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("e", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("h", termAtt.toString());
+ assertTrue(graph.incrementGraph());
+ assertEquals("d", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("f", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("j", termAtt.toString());
+ assertFalse(graph.incrementGraph());
+ assertEquals(8, graph.cachedTokenCount());
+
+ //tok.setReader(new StringReader("a b/c d e/f:3 g/h i j k"));
+
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("e", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("g", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("i", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("j", termAtt.toString());
+ assertTrue(graph.incrementGraph());
+ assertEquals("e", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("h", termAtt.toString());
+ assertFalse(graph.incrementGraph());
+ assertEquals(8, graph.cachedTokenCount());
+
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("f", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("j", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("k", termAtt.toString());
+ assertFalse(graph.incrementGraphToken());
+ assertFalse(graph.incrementGraph());
+ assertEquals(8, graph.cachedTokenCount());
+
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("g", termAtt.toString());
+ assertTrue(graph.incrementGraphToken());
+ assertEquals("i", termAtt.toString());
+ assertFalse(graph.incrementGraph());
+ assertEquals(8, graph.cachedTokenCount());
+
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("h", termAtt.toString());
+ assertFalse(graph.incrementGraph());
+ assertEquals(8, graph.cachedTokenCount());
+
+ assertTrue(graph.incrementBaseToken());
+ assertTrue(graph.incrementBaseToken());
+ assertTrue(graph.incrementBaseToken());
+ assertEquals("k", termAtt.toString());
+ assertFalse(graph.incrementGraphToken());
+ assertEquals(0, graph.getTrailingPositions());
+ assertFalse(graph.incrementGraph());
+ assertFalse(graph.incrementBaseToken());
+ assertEquals(8, graph.cachedTokenCount());
+
+ }
+
+ public void testTrailingPositions() throws IOException {
+
+ // a/b:2 c _
+ CannedTokenStream cts = new CannedTokenStream(1, 5,
+ new Token("a", 0, 1),
+ new Token("b", 0, 0, 1, 2),
+ new Token("c", 1, 2, 3)
+ );
+
+ GraphTokenFilter gts = new TestFilter(cts);
+ assertFalse(gts.incrementGraph());
+ assertTrue(gts.incrementBaseToken());
+ assertTrue(gts.incrementGraphToken());
+ assertFalse(gts.incrementGraphToken());
+ assertEquals(1, gts.getTrailingPositions());
+ assertFalse(gts.incrementGraph());
+ assertTrue(gts.incrementBaseToken());
+ assertFalse(gts.incrementGraphToken());
+ assertEquals(1, gts.getTrailingPositions());
+ assertFalse(gts.incrementGraph());
+ }
+
+ public void testMaximumGraphCacheSize() throws IOException {
+
+ Token[] tokens = new Token[GraphTokenFilter.MAX_TOKEN_CACHE_SIZE + 5];
+ for (int i = 0; i < GraphTokenFilter.MAX_TOKEN_CACHE_SIZE + 5; i++) {
+ tokens[i] = new Token("a", 1, i * 2, i * 2 + 1);
+ }
+
+ GraphTokenFilter gts = new TestFilter(new CannedTokenStream(tokens));
+ Exception e = expectThrows(IllegalStateException.class, () -> {
+ gts.reset();
+ gts.incrementBaseToken();
+ while (true) {
+ gts.incrementGraphToken();
+ }
+ });
+ assertEquals("Too many cached tokens (> 100)", e.getMessage());
+
+ gts.reset();
+ // after reset, the cache should be cleared and so we can read ahead once more
+ gts.incrementBaseToken();
+ gts.incrementGraphToken();
+
+ }
+
+ public void testGraphPathCountLimits() {
+
+ Token[] tokens = new Token[50];
+ tokens[0] = new Token("term", 1, 0, 1);
+ tokens[1] = new Token("term1", 1, 2, 3);
+ for (int i = 2; i < 50; i++) {
+ tokens[i] = new Token("term" + i, i % 2, 2, 3);
+ }
+
+ Exception e = expectThrows(IllegalStateException.class, () -> {
+ GraphTokenFilter graph = new TestFilter(new CannedTokenStream(tokens));
+ graph.reset();
+ graph.incrementBaseToken();
+ for (int i = 0; i < 10; i++) {
+ graph.incrementGraphToken();
+ }
+ while (graph.incrementGraph()) {
+ for (int i = 0; i < 10; i++) {
+ graph.incrementGraphToken();
+ }
+ }
+ });
+ assertEquals("Too many graph paths (> 1000)", e.getMessage());
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f5867a14/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenizers.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenizers.java b/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenizers.java
index 7e98662..8d3b8e1 100644
--- a/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenizers.java
+++ b/lucene/core/src/test/org/apache/lucene/analysis/TestGraphTokenizers.java
@@ -56,7 +56,7 @@ public class TestGraphTokenizers extends BaseTokenStreamTestCase {
// you cannot turn on MockCharFilter when random
// testing...
- private static class GraphTokenizer extends Tokenizer {
+ public static final class GraphTokenizer extends Tokenizer {
private List<Token> tokens;
private int upto;
private int inputLength;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/f5867a14/lucene/test-framework/src/java/org/apache/lucene/analysis/Token.java
----------------------------------------------------------------------
diff --git a/lucene/test-framework/src/java/org/apache/lucene/analysis/Token.java b/lucene/test-framework/src/java/org/apache/lucene/analysis/Token.java
index 9994175..18b6b8b 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/analysis/Token.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/analysis/Token.java
@@ -82,6 +82,13 @@ public class Token extends PackedTokenAttributeImpl implements FlagsAttribute, P
setPositionIncrement(posInc);
}
+ public Token(CharSequence text, int posInc, int start, int end, int posLength) {
+ append(text);
+ setOffset(start, end);
+ setPositionIncrement(posInc);
+ setPositionLength(posLength);
+ }
+
/**
* {@inheritDoc}
* @see FlagsAttribute