You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by ho...@apache.org on 2016/12/14 22:14:54 UTC
[01/32] lucene-solr:jira/solr-5944: SOLR-5043: New
solr.dns.prevent.reverse.lookup system property that can be used to prevent
long core (re)load delays on systems with missconfigured hostname/DNS
Repository: lucene-solr
Updated Branches:
refs/heads/jira/solr-5944 6642fd7e1 -> 5d229fee1
SOLR-5043: New solr.dns.prevent.reverse.lookup system property that can be used to prevent long core (re)load delays on systems with missconfigured hostname/DNS
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/8b98b158
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/8b98b158
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/8b98b158
Branch: refs/heads/jira/solr-5944
Commit: 8b98b158ff9cc2a71216e12c894ca14352d31f0e
Parents: c164f7e
Author: Chris Hostetter <ho...@apache.org>
Authored: Tue Dec 6 14:47:03 2016 -0700
Committer: Chris Hostetter <ho...@apache.org>
Committed: Tue Dec 6 14:47:03 2016 -0700
----------------------------------------------------------------------
solr/CHANGES.txt | 3 ++
.../solr/handler/admin/SystemInfoHandler.java | 51 +++++++++++++++++---
2 files changed, 46 insertions(+), 8 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8b98b158/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 4f7377c..14dd2fa 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -152,6 +152,9 @@ New Features
* SOLR-9728: Ability to specify Key Store type in solr.in.sh file for SSL (Michael Suzuki, Kevin Risden)
+* SOLR-5043: New solr.dns.prevent.reverse.lookup system property that can be used to prevent long core
+ (re)load delays on systems with missconfigured hostname/DNS (hossman)
+
Optimizations
----------------------
* SOLR-9704: Facet Module / JSON Facet API: Optimize blockChildren facets that have
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8b98b158/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.java
index 35ef906..a873c09 100644
--- a/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.java
@@ -31,7 +31,6 @@ import java.lang.management.PlatformManagedObject;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
-import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
@@ -50,6 +49,8 @@ import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.IndexSchema;
+import org.apache.solr.util.RTimer;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -64,8 +65,22 @@ import static org.apache.solr.common.params.CommonParams.NAME;
public class SystemInfoHandler extends RequestHandlerBase
{
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
-
+ /**
+ * <p>
+ * Undocumented expert level system property to prevent doing a reverse lookup of our hostname.
+ * This property ill be logged as a suggested workaround if any probems are noticed when doing reverse
+ * lookup.
+ * </p>
+ *
+ * <p>
+ * TODO: should we refactor this (and the associated logic) into a helper method for any other places
+ * where DNS is used?
+ * </p>
+ * @see #initHostname
+ */
+ private static final String PREVENT_REVERSE_DNS_OF_LOCALHOST_SYSPROP = "solr.dns.prevent.reverse.lookup";
+
// on some platforms, resolving canonical hostname can cause the thread
// to block for several seconds if nameservices aren't available
// so resolve this once per handler instance
@@ -75,22 +90,42 @@ public class SystemInfoHandler extends RequestHandlerBase
private CoreContainer cc;
public SystemInfoHandler() {
- super();
- init();
+ this(null);
}
public SystemInfoHandler(CoreContainer cc) {
super();
this.cc = cc;
- init();
+ initHostname();
}
- private void init() {
+ private void initHostname() {
+ if (null != System.getProperty(PREVENT_REVERSE_DNS_OF_LOCALHOST_SYSPROP, null)) {
+ log.info("Resolving canonical hostname for local host prevented due to '{}' sysprop",
+ PREVENT_REVERSE_DNS_OF_LOCALHOST_SYSPROP);
+ hostname = null;
+ return;
+ }
+
+ RTimer timer = new RTimer();
try {
InetAddress addr = InetAddress.getLocalHost();
hostname = addr.getCanonicalHostName();
- } catch (UnknownHostException e) {
- //default to null
+ } catch (Exception e) {
+ log.warn("Unable to resolve canonical hostname for local host, possible DNS misconfiguration. " +
+ "Set the '"+PREVENT_REVERSE_DNS_OF_LOCALHOST_SYSPROP+"' sysprop to true on startup to " +
+ "prevent future lookups if DNS can not be fixed.", e);
+ hostname = null;
+ return;
+ }
+ timer.stop();
+
+ if (15000D < timer.getTime()) {
+ String readableTime = String.format(Locale.ROOT, "%.3f", (timer.getTime() / 1000));
+ log.warn("Resolving canonical hostname for local host took {} seconds, possible DNS misconfiguration. " +
+ "Set the '{}' sysprop to true on startup to prevent future lookups if DNS can not be fixed.",
+ readableTime, PREVENT_REVERSE_DNS_OF_LOCALHOST_SYSPROP);
+
}
}
[07/32] lucene-solr:jira/solr-5944: fix java warning in SolrQueryTest
Posted by ho...@apache.org.
fix java warning in SolrQueryTest
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/cacabc9a
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/cacabc9a
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/cacabc9a
Branch: refs/heads/jira/solr-5944
Commit: cacabc9a4edf299f1dd2e5d08cc66845bc52fe98
Parents: bfc3690
Author: Christine Poerschke <cp...@apache.org>
Authored: Wed Dec 7 21:16:42 2016 +0000
Committer: Christine Poerschke <cp...@apache.org>
Committed: Wed Dec 7 21:16:42 2016 +0000
----------------------------------------------------------------------
.../solrj/src/test/org/apache/solr/client/solrj/SolrQueryTest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/cacabc9a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrQueryTest.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrQueryTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrQueryTest.java
index d27847f..1c86c93 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrQueryTest.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrQueryTest.java
@@ -441,7 +441,7 @@ public class SolrQueryTest extends LuceneTestCase {
solrQuery.addMoreLikeThisField("mlt3");
solrQuery.addMoreLikeThisField("mlt4");
assertEquals(4, solrQuery.getMoreLikeThisFields().length);
- solrQuery.setMoreLikeThisFields(null);
+ solrQuery.setMoreLikeThisFields((String[])null);
assertTrue(null == solrQuery.getMoreLikeThisFields());
assertFalse(solrQuery.getMoreLikeThis());
[04/32] lucene-solr:jira/solr-5944: SOLR-9822: speed up single-valued
string fieldcache counting in dv facet processor
Posted by ho...@apache.org.
SOLR-9822: speed up single-valued string fieldcache counting in dv facet processor
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/ca5e736d
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/ca5e736d
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/ca5e736d
Branch: refs/heads/jira/solr-5944
Commit: ca5e736db1df0cdf35f1b039350bfd5a9cdfa102
Parents: 10500c8
Author: yonik <yo...@apache.org>
Authored: Wed Dec 7 11:08:33 2016 -0500
Committer: yonik <yo...@apache.org>
Committed: Wed Dec 7 11:09:55 2016 -0500
----------------------------------------------------------------------
solr/CHANGES.txt | 5 +
.../facet/FacetFieldProcessorByArrayDV.java | 49 ++++++-
.../org/apache/solr/search/facet/FieldUtil.java | 147 +++++++++++++++++++
.../org/apache/solr/uninverting/FieldCache.java | 2 +-
.../apache/solr/uninverting/FieldCacheImpl.java | 130 ++++++++--------
5 files changed, 264 insertions(+), 69 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ca5e736d/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 14dd2fa..8dee837 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -62,6 +62,11 @@ Optimizations
* SOLR-9579: Make Solr's SchemaField implement Lucene's IndexableFieldType, removing the
creation of a Lucene FieldType every time a field is indexed. (John Call, yonik)
+* SOLR-9822: JSON Facet API: Recover performance lost due to the DocValues transition to
+ an iterator API (LUCENE-7407). This only fixes calculating counts for single-valued
+ string fields from the FieldCache, resulting in up to 56% better throughput for those cases.
+ (yonik)
+
================== 6.4.0 ==================
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ca5e736d/solr/core/src/java/org/apache/solr/search/facet/FacetFieldProcessorByArrayDV.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/facet/FacetFieldProcessorByArrayDV.java b/solr/core/src/java/org/apache/solr/search/facet/FacetFieldProcessorByArrayDV.java
index 88adf67..1481f18 100644
--- a/solr/core/src/java/org/apache/solr/search/facet/FacetFieldProcessorByArrayDV.java
+++ b/solr/core/src/java/org/apache/solr/search/facet/FacetFieldProcessorByArrayDV.java
@@ -33,6 +33,7 @@ import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.common.SolrException;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.Filter;
+import org.apache.solr.uninverting.FieldCacheImpl;
/**
* Grabs values from {@link DocValues}.
@@ -184,15 +185,33 @@ class FacetFieldProcessorByArrayDV extends FacetFieldProcessorByArray {
int segMax = singleDv.getValueCount() + 1;
final int[] counts = getCountArr( segMax );
+ /** alternate trial implementations
+ // ord
+ // FieldUtil.visitOrds(singleDv, disi, (doc,ord)->{counts[ord+1]++;} );
+
+ FieldUtil.OrdValues ordValues = FieldUtil.getOrdValues(singleDv, disi);
+ while (ordValues.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
+ counts[ ordValues.getOrd() + 1]++;
+ }
+ **/
+
+
+ // calculate segment-local counts
int doc;
- while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
- if (singleDv.advanceExact(doc)) {
- counts[ singleDv.ordValue() + 1 ]++;
- } else {
- counts[ 0 ]++;
+ if (singleDv instanceof FieldCacheImpl.SortedDocValuesImpl.Iter) {
+ FieldCacheImpl.SortedDocValuesImpl.Iter fc = (FieldCacheImpl.SortedDocValuesImpl.Iter) singleDv;
+ while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ counts[fc.getOrd(doc) + 1]++;
+ }
+ } else {
+ while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ if (singleDv.advanceExact(doc)) {
+ counts[singleDv.ordValue() + 1]++;
+ }
}
}
+ // convert segment-local counts to global counts
for (int i=1; i<segMax; i++) {
int segCount = counts[i];
if (segCount > 0) {
@@ -250,12 +269,26 @@ class FacetFieldProcessorByArrayDV extends FacetFieldProcessorByArray {
private void collectCounts(SortedDocValues singleDv, DocIdSetIterator disi, LongValues toGlobal) throws IOException {
int doc;
- while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
- if (singleDv.advanceExact(doc)) {
- int segOrd = singleDv.ordValue();
+ if (singleDv instanceof FieldCacheImpl.SortedDocValuesImpl.Iter) {
+
+ FieldCacheImpl.SortedDocValuesImpl.Iter fc = (FieldCacheImpl.SortedDocValuesImpl.Iter)singleDv;
+ while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ int segOrd = fc.getOrd(doc);
+ if (segOrd < 0) continue;
int ord = (int)toGlobal.get(segOrd);
countAcc.incrementCount(ord, 1);
}
+
+ } else {
+
+ while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ if (singleDv.advanceExact(doc)) {
+ int segOrd = singleDv.ordValue();
+ int ord = (int) toGlobal.get(segOrd);
+ countAcc.incrementCount(ord, 1);
+ }
+ }
+
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ca5e736d/solr/core/src/java/org/apache/solr/search/facet/FieldUtil.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/facet/FieldUtil.java b/solr/core/src/java/org/apache/solr/search/facet/FieldUtil.java
index 84255b9..389b6d7 100644
--- a/solr/core/src/java/org/apache/solr/search/facet/FieldUtil.java
+++ b/solr/core/src/java/org/apache/solr/search/facet/FieldUtil.java
@@ -21,10 +21,13 @@ import java.io.IOException;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.SortedSetDocValues;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.util.BytesRef;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.QParser;
import org.apache.solr.search.QueryContext;
import org.apache.solr.search.SolrIndexSearcher;
+import org.apache.solr.uninverting.FieldCacheImpl;
/** @lucene.internal
* Porting helper... may be removed if it offers no value in the future.
@@ -52,4 +55,148 @@ public class FieldUtil {
return si == null ? DocValues.emptySortedSet() : si;
}
+
+ /** The following ord visitors and wrappers are a work in progress and experimental
+ * @lucene.experimental */
+ @FunctionalInterface
+ public interface OrdFunc {
+ void handleOrd(int docid, int ord); // TODO: throw exception?
+ }
+
+ public static boolean isFieldCache(SortedDocValues singleDv) {
+ return singleDv instanceof FieldCacheImpl.SortedDocValuesImpl.Iter;
+ }
+
+ public static void visitOrds(SortedDocValues singleDv, DocIdSetIterator disi, OrdFunc ordFunc) throws IOException {
+ int doc;
+ if (singleDv instanceof FieldCacheImpl.SortedDocValuesImpl.Iter) {
+ FieldCacheImpl.SortedDocValuesImpl.Iter fc = (FieldCacheImpl.SortedDocValuesImpl.Iter) singleDv;
+ while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ ordFunc.handleOrd(doc, fc.getOrd(doc));
+ }
+ } else {
+ while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ if (singleDv.advanceExact(doc)) {
+ ordFunc.handleOrd(doc, singleDv.ordValue());
+ } else {
+ // TODO: optionally pass in missingOrd?
+ }
+ }
+ }
+ }
+
+ public static OrdValues getOrdValues(SortedDocValues singleDv, DocIdSetIterator disi) {
+ if (singleDv instanceof FieldCacheImpl.SortedDocValuesImpl.Iter) {
+ FieldCacheImpl.SortedDocValuesImpl.Iter fc = (FieldCacheImpl.SortedDocValuesImpl.Iter) singleDv;
+ return new FCOrdValues(fc, disi);
+ }
+ return new DVOrdValues(singleDv, disi);
+ }
+
+
+ public static abstract class OrdValues extends SortedDocValues {
+ int doc;
+ int ord;
+
+ public int getOrd() {
+ return ord;
+ }
+
+ @Override
+ public int docID() {
+ return doc;
+ }
+
+ @Override
+ public abstract int nextDoc() throws IOException;
+
+ @Override
+ public int advance(int target) throws IOException {
+ return 0; // TODO
+ }
+
+ @Override
+ public long cost() {
+ return 0;
+ }
+
+ @Override
+ public int getValueCount() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+
+ public static class FCOrdValues extends OrdValues {
+ FieldCacheImpl.SortedDocValuesImpl.Iter vals;
+ DocIdSetIterator disi;
+
+ public FCOrdValues(FieldCacheImpl.SortedDocValuesImpl.Iter iter, DocIdSetIterator disi) {
+ this.vals = iter;
+ this.disi = disi;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ doc = disi.nextDoc();
+ if (doc == NO_MORE_DOCS) return NO_MORE_DOCS;
+ ord = vals.getOrd(doc); // todo: loop until a hit?
+ return doc;
+ }
+
+ @Override
+ public boolean advanceExact(int target) throws IOException {
+ return false;
+ }
+
+ @Override
+ public int ordValue() {
+ return 0;
+ }
+
+ @Override
+ public BytesRef lookupOrd(int ord) throws IOException {
+ return null;
+ }
+ }
+
+ public static class DVOrdValues extends OrdValues {
+ SortedDocValues vals;
+ DocIdSetIterator disi;
+ int valDoc;
+
+ public DVOrdValues(SortedDocValues vals, DocIdSetIterator disi) {
+ this.vals = vals;
+ this.disi = disi;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ for (;;) {
+ // todo - use skipping when appropriate
+ doc = disi.nextDoc();
+ if (doc == NO_MORE_DOCS) return NO_MORE_DOCS;
+ boolean match = vals.advanceExact(doc);
+ if (match) {
+ ord = vals.ordValue();
+ return doc;
+ }
+ }
+ }
+
+ @Override
+ public boolean advanceExact(int target) throws IOException {
+ return false;
+ }
+
+ @Override
+ public int ordValue() {
+ return 0;
+ }
+
+ @Override
+ public BytesRef lookupOrd(int ord) throws IOException {
+ return null;
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ca5e736d/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java b/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java
index ea8f6ea..32f5615 100644
--- a/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java
+++ b/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java
@@ -45,7 +45,7 @@ import org.apache.lucene.util.RamUsageEstimator;
*
* @lucene.internal
*/
-interface FieldCache {
+public interface FieldCache {
/**
* Placeholder indicating creation of this cache is currently in-progress.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ca5e736d/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java b/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java
index 2224010..0ca687f 100644
--- a/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java
+++ b/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java
@@ -58,9 +58,9 @@ import org.apache.lucene.util.packed.PackedLongValues;
* Expert: The default cache implementation, storing all values in memory.
* A WeakHashMap is used for storage.
*
- * @since lucene 1.4
+ * @lucene.internal
*/
-class FieldCacheImpl implements FieldCache {
+public class FieldCacheImpl implements FieldCache {
private Map<Class<?>,Cache> caches;
FieldCacheImpl() {
@@ -786,79 +786,89 @@ class FieldCacheImpl implements FieldCache {
this.termOrdToBytesOffset = termOrdToBytesOffset;
this.numOrd = numOrd;
}
-
+
public SortedDocValues iterator() {
- final BytesRef term = new BytesRef();
- return new SortedDocValues() {
- private int docID = -1;
+ return new Iter();
+ }
- @Override
- public int docID() {
- return docID;
- }
+ public class Iter extends SortedDocValues {
+ private int docID = -1;
+ private final BytesRef term = new BytesRef();
- @Override
- public int nextDoc() {
- while (true) {
- docID++;
- if (docID >= docToTermOrd.size()) {
- docID = NO_MORE_DOCS;
- return docID;
- }
- if (docToTermOrd.get(docID) != 0) {
- return docID;
- }
- }
- }
+ /** @lucene.internal Specific to this implementation and subject to change. For internal optimization only. */
+ public int getOrd(int docID) {
+ // Subtract 1, matching the 1+ord we did when
+ // storing, so that missing values, which are 0 in the
+ // packed ints, are returned as -1 ord:
+ return (int) docToTermOrd.get(docID)-1;
+ }
- @Override
- public int advance(int target) {
- if (target < docToTermOrd.size()) {
- docID = target;
- if (docToTermOrd.get(docID) != 0) {
- return docID;
- } else{
- return nextDoc();
- }
- } else {
+ @Override
+ public int docID() {
+ return docID;
+ }
+
+ @Override
+ public int nextDoc() {
+ while (true) {
+ docID++;
+ if (docID >= docToTermOrd.size()) {
docID = NO_MORE_DOCS;
return docID;
}
+ if (docToTermOrd.get(docID) != 0) {
+ return docID;
+ }
}
+ }
- @Override
- public boolean advanceExact(int target) throws IOException {
+ @Override
+ public int advance(int target) {
+ if (target < docToTermOrd.size()) {
docID = target;
- return docToTermOrd.get(docID) != 0;
+ if (docToTermOrd.get(docID) != 0) {
+ return docID;
+ } else{
+ return nextDoc();
+ }
+ } else {
+ docID = NO_MORE_DOCS;
+ return docID;
}
+ }
- @Override
- public long cost() {
- return 0;
- }
-
- @Override
- public int ordValue() {
- // Subtract 1, matching the 1+ord we did when
- // storing, so that missing values, which are 0 in the
- // packed ints, are returned as -1 ord:
- return (int) docToTermOrd.get(docID)-1;
- }
+ @Override
+ public boolean advanceExact(int target) throws IOException {
+ docID = target;
+ return docToTermOrd.get(docID) != 0;
+ }
- @Override
- public int getValueCount() {
- return numOrd;
- }
+ @Override
+ public long cost() {
+ return 0;
+ }
- @Override
- public BytesRef lookupOrd(int ord) {
- if (ord < 0) {
- throw new IllegalArgumentException("ord must be >=0 (got ord=" + ord + ")");
- }
- bytes.fill(term, termOrdToBytesOffset.get(ord));
- return term;
+ @Override
+ public int ordValue() {
+ // Subtract 1, matching the 1+ord we did when
+ // storing, so that missing values, which are 0 in the
+ // packed ints, are returned as -1 ord:
+ return (int) docToTermOrd.get(docID)-1;
+ }
+
+ @Override
+ public int getValueCount() {
+ return numOrd;
+ }
+
+ @Override
+ public BytesRef lookupOrd(int ord) {
+ if (ord < 0) {
+ throw new IllegalArgumentException("ord must be >=0 (got ord=" + ord + ")");
}
- };
+ bytes.fill(term, termOrdToBytesOffset.get(ord));
+ return term;
+ }
}
@Override
[11/32] lucene-solr:jira/solr-5944: SOLR-9837: fix redundant
calculation of docsWithField for numeric fields in field cache
Posted by ho...@apache.org.
SOLR-9837: fix redundant calculation of docsWithField for numeric fields in field cache
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/1d2e440a
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/1d2e440a
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/1d2e440a
Branch: refs/heads/jira/solr-5944
Commit: 1d2e440a8fe3df8d3207a7428841f79f63381e4f
Parents: 93c1146
Author: yonik <yo...@apache.org>
Authored: Thu Dec 8 18:29:07 2016 -0500
Committer: yonik <yo...@apache.org>
Committed: Thu Dec 8 18:29:07 2016 -0500
----------------------------------------------------------------------
solr/CHANGES.txt | 4 ++
.../apache/solr/uninverting/FieldCacheImpl.java | 52 +++++++++++---------
2 files changed, 32 insertions(+), 24 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1d2e440a/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index abd9997..78f7f55 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -50,6 +50,10 @@ Bug Fixes
* SOLR-9262: Connection and read timeouts are being ignored by UpdateShardHandler after SOLR-4509.
(Mark Miller, shalin)
+* SOLR-9837: Fix 55% performance regression of FieldCache uninvert time of
+ numeric fields. (yonik)
+
+
Optimizations
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/1d2e440a/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java b/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java
index 0ca687f..90be400 100644
--- a/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java
+++ b/solr/core/src/java/org/apache/solr/uninverting/FieldCacheImpl.java
@@ -365,8 +365,6 @@ public class FieldCacheImpl implements FieldCache {
}
}
- /** @deprecated remove this when legacy numerics are removed */
- @Deprecated
protected abstract TermsEnum termsEnum(Terms terms) throws IOException;
protected abstract void visitTerm(BytesRef term);
protected abstract void visitDoc(int docID);
@@ -632,20 +630,21 @@ public class FieldCacheImpl implements FieldCache {
}
}
- Bits docsWithField = getDocsWithField(reader, field, parser);
- return ((LongsFromArray) caches.get(Long.TYPE).get(reader, new CacheKey(field, parser))).iterator(docsWithField);
+ return ((LongsFromArray) caches.get(Long.TYPE).get(reader, new CacheKey(field, parser))).iterator();
}
}
- static class LongsFromArray implements Accountable {
+ public static class LongsFromArray implements Accountable {
private final PackedInts.Reader values;
private final long minValue;
+ private final Bits docsWithField;
private final String field;
- public LongsFromArray(String field, PackedInts.Reader values, long minValue) {
+ public LongsFromArray(String field, PackedInts.Reader values, long minValue, Bits docsWithField) { // TODO: accept null docsWithField?
this.field = field;
this.values = values;
this.minValue = minValue;
+ this.docsWithField = docsWithField;
}
@Override
@@ -653,7 +652,7 @@ public class FieldCacheImpl implements FieldCache {
return values.ramBytesUsed() + RamUsageEstimator.NUM_BYTES_OBJECT_REF + Long.BYTES;
}
- public NumericDocValues iterator(final Bits docsWithField) {
+ public NumericDocValues iterator() {
return new NumericDocValues() {
int docID = -1;
@@ -767,10 +766,11 @@ public class FieldCacheImpl implements FieldCache {
u.uninvert(reader, key.field);
wrapper.setDocsWithField(reader, key.field, u.docsWithField, parser);
GrowableWriterAndMinValue values = valuesRef.get();
+ Bits docsWithField = u.docsWithField == null ? new Bits.MatchNoBits(reader.maxDoc()) : u.docsWithField;
if (values == null) {
- return new LongsFromArray(key.field, new PackedInts.NullReader(reader.maxDoc()), 0L);
+ return new LongsFromArray(key.field, new PackedInts.NullReader(reader.maxDoc()), 0L, docsWithField);
}
- return new LongsFromArray(key.field, values.writer.getMutable(), values.minValue);
+ return new LongsFromArray(key.field, values.writer.getMutable(), values.minValue, docsWithField);
}
}
@@ -993,16 +993,18 @@ public class FieldCacheImpl implements FieldCache {
}
}
- private static class BinaryDocValuesImpl implements Accountable {
+ public static class BinaryDocValuesImpl implements Accountable {
private final PagedBytes.Reader bytes;
private final PackedInts.Reader docToOffset;
+ private final Bits docsWithField;
- public BinaryDocValuesImpl(PagedBytes.Reader bytes, PackedInts.Reader docToOffset) {
+ public BinaryDocValuesImpl(PagedBytes.Reader bytes, PackedInts.Reader docToOffset, Bits docsWithField) {
this.bytes = bytes;
this.docToOffset = docToOffset;
+ this.docsWithField = docsWithField;
}
- public BinaryDocValues iterator(Bits docsWithField) {
+ public BinaryDocValues iterator() {
return new BinaryDocValues() {
final BytesRef term = new BytesRef();
@@ -1109,7 +1111,7 @@ public class FieldCacheImpl implements FieldCache {
}
BinaryDocValuesImpl impl = (BinaryDocValuesImpl) caches.get(BinaryDocValues.class).get(reader, new CacheKey(field, acceptableOverheadRatio));
- return impl.iterator(getDocsWithField(reader, field, null));
+ return impl.iterator();
}
static final class BinaryDocValuesCache extends Cache {
@@ -1188,19 +1190,21 @@ public class FieldCacheImpl implements FieldCache {
}
final PackedInts.Reader offsetReader = docToOffset.getMutable();
- wrapper.setDocsWithField(reader, key.field, new Bits() {
- @Override
- public boolean get(int index) {
- return offsetReader.get(index) != 0;
- }
+ Bits docsWithField = new Bits() {
+ @Override
+ public boolean get(int index) {
+ return offsetReader.get(index) != 0;
+ }
- @Override
- public int length() {
- return maxDoc;
- }
- }, null);
+ @Override
+ public int length() {
+ return maxDoc;
+ }
+ };
+
+ wrapper.setDocsWithField(reader, key.field, docsWithField, null);
// maybe an int-only impl?
- return new BinaryDocValuesImpl(bytes.freeze(true), offsetReader);
+ return new BinaryDocValuesImpl(bytes.freeze(true), offsetReader, docsWithField);
}
}
[19/32] lucene-solr:jira/solr-5944: LUCENE-7591 - approximate to no.
of terms when DVs are not available
Posted by ho...@apache.org.
LUCENE-7591 - approximate to no. of terms when DVs are not available
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/87d8b545
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/87d8b545
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/87d8b545
Branch: refs/heads/jira/solr-5944
Commit: 87d8b5450a6d75fdd4b724b24a3722054b6d00f8
Parents: 25c7855
Author: Tommaso Teofili <to...@apache.org>
Authored: Mon Dec 12 10:00:21 2016 +0100
Committer: Tommaso Teofili <to...@apache.org>
Committed: Mon Dec 12 10:00:21 2016 +0100
----------------------------------------------------------------------
.../org/apache/lucene/classification/utils/DatasetSplitter.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/87d8b545/lucene/classification/src/java/org/apache/lucene/classification/utils/DatasetSplitter.java
----------------------------------------------------------------------
diff --git a/lucene/classification/src/java/org/apache/lucene/classification/utils/DatasetSplitter.java b/lucene/classification/src/java/org/apache/lucene/classification/utils/DatasetSplitter.java
index 8bb0b1d..7ab674e 100644
--- a/lucene/classification/src/java/org/apache/lucene/classification/utils/DatasetSplitter.java
+++ b/lucene/classification/src/java/org/apache/lucene/classification/utils/DatasetSplitter.java
@@ -94,7 +94,8 @@ public class DatasetSplitter {
}
}
if (classValues == null) {
- throw new IllegalStateException("field \"" + classFieldName + "\" must have sorted (set) doc values");
+ // approximate with no. of terms
+ noOfClasses += leave.reader().terms(classFieldName).size();
}
noOfClasses += valueCount;
}
[32/32] lucene-solr:jira/solr-5944: Merge branch 'master' into
jira/solr-5944
Posted by ho...@apache.org.
Merge branch 'master' into jira/solr-5944
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/5d229fee
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/5d229fee
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/5d229fee
Branch: refs/heads/jira/solr-5944
Commit: 5d229fee1f2d07ec7db4201b42f4273824b5b4ee
Parents: 6642fd7 6525bb5
Author: Chris Hostetter <ho...@apache.org>
Authored: Wed Dec 14 14:46:29 2016 -0700
Committer: Chris Hostetter <ho...@apache.org>
Committed: Wed Dec 14 14:46:29 2016 -0700
----------------------------------------------------------------------
.gitignore | 1 +
lucene/CHANGES.txt | 17 ++
.../classification/utils/DatasetSplitter.java | 3 +-
.../simpletext/SimpleTextPointsWriter.java | 2 +-
.../CompressingStoredFieldsWriter.java | 19 +-
.../CompressingTermVectorsWriter.java | 11 +-
.../GrowableByteArrayDataOutput.java | 83 ---------
.../org/apache/lucene/index/IndexWriter.java | 32 +++-
.../apache/lucene/index/IndexWriterConfig.java | 3 +
.../org/apache/lucene/index/LeafReader.java | 2 +-
.../lucene/index/LiveIndexWriterConfig.java | 13 ++
.../apache/lucene/index/SegmentCoreReaders.java | 8 +
.../store/GrowableByteArrayDataOutput.java | 103 +++++++++++
.../org/apache/lucene/store/MMapDirectory.java | 4 +-
.../org/apache/lucene/util/bkd/BKDWriter.java | 85 +++++----
.../apache/lucene/util/bkd/DocIdsWriter.java | 4 +-
.../TestGrowableByteArrayDataOutput.java | 80 --------
.../apache/lucene/index/TestIndexSorting.java | 30 ++-
.../index/TestTragicIndexWriterDeadlock.java | 69 ++++++-
.../store/TestGrowableByteArrayDataOutput.java | 80 ++++++++
.../apache/lucene/search/DocValuesStats.java | 165 +++++++++++++++++
.../lucene/search/DocValuesStatsCollector.java | 64 +++++++
.../search/TestDocValuesStatsCollector.java | 166 +++++++++++++++++
.../apache/lucene/document/RangeFieldQuery.java | 1 +
.../search/BaseRangeFieldQueryTestCase.java | 2 +-
solr/CHANGES.txt | 30 +++
.../TestPlainTextEntityProcessor.java | 106 +++++++++++
solr/contrib/ltr/README.md | 6 +-
.../java/org/apache/solr/ltr/FeatureLogger.java | 10 +-
.../org/apache/solr/ltr/LTRScoringQuery.java | 22 +--
.../org/apache/solr/ltr/LTRThreadModule.java | 29 +++
.../org/apache/solr/ltr/feature/Feature.java | 3 +-
.../solr/ltr/feature/FieldValueFeature.java | 18 +-
.../solr/ltr/feature/OriginalScoreFeature.java | 12 +-
.../apache/solr/ltr/feature/SolrFeature.java | 17 +-
.../ltr/store/rest/ManagedFeatureStore.java | 1 -
.../solr/ltr/store/rest/ManagedModelStore.java | 32 ++--
.../test-files/solr/collection1/conf/schema.xml | 2 +
.../solr/ltr/feature/TestFieldValueFeature.java | 48 ++++-
.../ltr/feature/TestOriginalScoreScorer.java | 47 +++++
.../model/TestMultipleAdditiveTreesModel.java | 44 +++--
.../solr/cloud/CloudConfigSetService.java | 24 ++-
.../org/apache/solr/cloud/CloudDescriptor.java | 2 +-
.../apache/solr/cloud/CreateCollectionCmd.java | 146 ++++++++++++++-
.../org/apache/solr/cloud/ElectionContext.java | 20 +-
.../org/apache/solr/cloud/LeaderElector.java | 9 +-
.../OverseerAutoReplicaFailoverThread.java | 9 +-
.../org/apache/solr/cloud/ZkController.java | 128 +------------
.../apache/solr/cloud/ZkSolrResourceLoader.java | 2 +-
.../org/apache/solr/core/ConfigSetService.java | 7 +-
.../org/apache/solr/core/CoreContainer.java | 2 +-
.../solr/handler/admin/CollectionsHandler.java | 2 +
.../solr/handler/admin/SystemInfoHandler.java | 51 +++++-
.../java/org/apache/solr/schema/BoolField.java | 4 +-
.../apache/solr/search/SolrFieldCacheMBean.java | 4 +-
.../facet/FacetFieldProcessorByArrayDV.java | 49 ++++-
.../org/apache/solr/search/facet/FieldUtil.java | 147 +++++++++++++++
.../apache/solr/servlet/SolrDispatchFilter.java | 15 ++
.../apache/solr/servlet/SolrRequestParsers.java | 31 ++--
.../org/apache/solr/uninverting/FieldCache.java | 16 +-
.../apache/solr/uninverting/FieldCacheImpl.java | 182 ++++++++++---------
.../uninverting/FieldCacheSanityChecker.java | 3 +-
.../solr/uninverting/UninvertingReader.java | 23 ++-
.../processor/DistributedUpdateProcessor.java | 8 +-
.../solr/util/SolrFileCleaningTracker.java | 147 +++++++++++++++
.../solr/cloud/DocValuesNotIndexedTest.java | 64 ++++---
.../apache/solr/cloud/LeaderElectionTest.java | 2 +
...verseerCollectionConfigSetProcessorTest.java | 33 +++-
.../cloud/SegmentTerminateEarlyTestState.java | 12 +-
.../solr/cloud/TestMiniSolrCloudCluster.java | 50 -----
.../apache/solr/cloud/TestSegmentSorting.java | 133 ++++++++++++++
.../org/apache/solr/cloud/ZkSolrClientTest.java | 54 ++++++
.../solr/search/TestSolrFieldCacheMBean.java | 2 +
.../apache/solr/common/cloud/SolrZkClient.java | 29 ++-
.../apache/solr/common/cloud/ZkCmdExecutor.java | 15 +-
.../apache/solr/client/solrj/SolrQueryTest.java | 2 +-
76 files changed, 2199 insertions(+), 702 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/5d229fee/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
----------------------------------------------------------------------
diff --cc lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
index 331da1f,4789505..159f86b
--- a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
@@@ -1617,9 -1617,11 +1617,12 @@@ public class IndexWriter implements Clo
public long updateNumericDocValue(Term term, String field, long value) throws IOException {
ensureOpen();
if (!globalFieldNumberMap.contains(field, DocValuesType.NUMERIC)) {
- throw new IllegalArgumentException("can only update existing numeric-docvalues fields!");
+ throw new IllegalArgumentException("can only update existing numeric-docvalues fields! Attempted"
+ + " to update field: " + field + "=" + value);
}
+ if (config.getIndexSortFields().contains(field)) {
+ throw new IllegalArgumentException("cannot update docvalues field involved in the index sort, field=" + field + ", sort=" + config.getIndexSort());
+ }
try {
long seqNo = docWriter.updateDocValues(new NumericDocValuesUpdate(term, field, value));
if (seqNo < 0) {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/5d229fee/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
----------------------------------------------------------------------
[13/32] lucene-solr:jira/solr-5944: LUCENE-6989: Fix Exception
handling in MMapDirectory's unmap hack support code to work with Java 9's new
InaccessibleObjectException that does not extend ReflectiveAccessException in
Java 9.
Posted by ho...@apache.org.
LUCENE-6989: Fix Exception handling in MMapDirectory's unmap hack support code to work with Java 9's new InaccessibleObjectException that does not extend ReflectiveAccessException in Java 9.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/22d04a7c
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/22d04a7c
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/22d04a7c
Branch: refs/heads/jira/solr-5944
Commit: 22d04a7c1149c1af42dc2890a416fc45e4d0aa5e
Parents: c185617
Author: Uwe Schindler <us...@apache.org>
Authored: Fri Dec 9 18:36:37 2016 +0100
Committer: Uwe Schindler <us...@apache.org>
Committed: Fri Dec 9 18:36:37 2016 +0100
----------------------------------------------------------------------
lucene/CHANGES.txt | 5 +++++
lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java | 4 ++--
2 files changed, 7 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/22d04a7c/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 26a9dec..b9deb7e 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -85,6 +85,11 @@ Bug Fixes
the incoming automaton is a special case and throw a clearer
exception than NullPointerException (Tom Mortimer via Mike McCandless)
+* LUCENE-6989: Fix Exception handling in MMapDirectory's unmap hack
+ support code to work with Java 9's new InaccessibleObjectException
+ that does not extend ReflectiveAccessException in Java 9.
+ (Uwe Schindler)
+
Improvements
* LUCENE-6824: TermAutomatonQuery now rewrites to TermQuery,
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/22d04a7c/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java b/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java
index c0e3519..be08a16 100644
--- a/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java
+++ b/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java
@@ -385,13 +385,13 @@ public class MMapDirectory extends FSDirectory {
}
}
};
- } catch (ReflectiveOperationException e) {
- return "Unmapping is not supported on this platform, because internal Java APIs are not compatible to this Lucene version: " + e;
} catch (SecurityException e) {
return "Unmapping is not supported, because not all required permissions are given to the Lucene JAR file: " + e +
" [Please grant at least the following permissions: RuntimePermission(\"accessClassInPackage.sun.misc\"), " +
"RuntimePermission(\"accessClassInPackage.jdk.internal.ref\"), and " +
"ReflectPermission(\"suppressAccessChecks\")]";
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ return "Unmapping is not supported on this platform, because internal Java APIs are not compatible to this Lucene version: " + e;
}
}
[10/32] lucene-solr:jira/solr-5944: fix stale comment
Posted by ho...@apache.org.
fix stale 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/93c11462
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/93c11462
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/93c11462
Branch: refs/heads/jira/solr-5944
Commit: 93c11462bbe2c442f20a6d090911c5a1a4546564
Parents: 1055209
Author: Mike McCandless <mi...@apache.org>
Authored: Thu Dec 8 18:17:25 2016 -0500
Committer: Mike McCandless <mi...@apache.org>
Committed: Thu Dec 8 18:17:25 2016 -0500
----------------------------------------------------------------------
.../apache/lucene/codecs/simpletext/SimpleTextPointsWriter.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/93c11462/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPointsWriter.java
----------------------------------------------------------------------
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPointsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPointsWriter.java
index 9d2db89..c3217f3 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPointsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPointsWriter.java
@@ -72,7 +72,7 @@ class SimpleTextPointsWriter extends PointsWriter {
PointValues values = reader.getValues(fieldInfo.name);
boolean singleValuePerDoc = values.size() == values.getDocCount();
- // We use the normal BKDWriter, but subclass to customize how it writes the index and blocks to disk:
+ // We use our own fork of the BKDWriter to customize how it writes the index and blocks to disk:
try (SimpleTextBKDWriter writer = new SimpleTextBKDWriter(writeState.segmentInfo.maxDoc(),
writeState.directory,
writeState.segmentInfo.name,
[30/32] lucene-solr:jira/solr-5944: SOLR-9844: Display fc total size
only when field entries asked for
Posted by ho...@apache.org.
SOLR-9844: Display fc total size only when field entries asked for
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/51237438
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/51237438
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/51237438
Branch: refs/heads/jira/solr-5944
Commit: 512374384a8984c56c91f47dcac4aaf0490eda54
Parents: 7dec783
Author: Varun Thacker <va...@apache.org>
Authored: Tue Dec 13 15:52:17 2016 -0800
Committer: Varun Thacker <va...@apache.org>
Committed: Wed Dec 14 10:52:26 2016 -0800
----------------------------------------------------------------------
.../apache/solr/search/SolrFieldCacheMBean.java | 6 ++---
.../solr/uninverting/UninvertingReader.java | 25 +++++++++++++-------
.../solr/search/TestSolrFieldCacheMBean.java | 3 ++-
3 files changed, 22 insertions(+), 12 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/51237438/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java b/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java
index 70781e9..642b708 100644
--- a/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java
+++ b/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java
@@ -62,15 +62,15 @@ public class SolrFieldCacheMBean implements JmxAugmentedSolrInfoMBean {
private NamedList getStats(boolean listEntries) {
NamedList stats = new SimpleOrderedMap();
if (listEntries) {
- String[] entries = UninvertingReader.getUninvertedStats();
+ UninvertingReader.FieldCacheStats fieldCacheStats = UninvertingReader.getUninvertedStats();
+ String[] entries = fieldCacheStats.info;
stats.add("entries_count", entries.length);
- stats.add("total_size", UninvertingReader.getTotalSize());
+ stats.add("total_size", fieldCacheStats.totalSize);
for (int i = 0; i < entries.length; i++) {
stats.add("entry#" + i, entries[i]);
}
} else {
stats.add("entries_count", UninvertingReader.getUninvertedStatsSize());
- stats.add("total_size", UninvertingReader.getTotalSize());
}
return stats;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/51237438/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java b/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java
index 87fb7a6..5276ca9 100644
--- a/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java
+++ b/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java
@@ -375,25 +375,34 @@ public class UninvertingReader extends FilterLeafReader {
* Return information about the backing cache
* @lucene.internal
*/
- public static String[] getUninvertedStats() {
+ public static FieldCacheStats getUninvertedStats() {
CacheEntry[] entries = FieldCache.DEFAULT.getCacheEntries();
+ long totalBytesUsed = 0;
String[] info = new String[entries.length];
for (int i = 0; i < entries.length; i++) {
info[i] = entries[i].toString();
+ totalBytesUsed += entries[i].getValue().ramBytesUsed();
}
- return info;
+ String totalSize = RamUsageEstimator.humanReadableUnits(totalBytesUsed);
+ return new FieldCacheStats(totalSize, info);
}
public static int getUninvertedStatsSize() {
return FieldCache.DEFAULT.getCacheEntries().length;
}
- public static String getTotalSize() {
- CacheEntry[] entries = FieldCache.DEFAULT.getCacheEntries();
- long totalBytesUsed = 0;
- for (int i = 0; i < entries.length; i++) {
- totalBytesUsed += entries[i].getValue().ramBytesUsed();
+ /**
+ * Return information about the backing cache
+ * @lucene.internal
+ */
+ public static class FieldCacheStats {
+ public String totalSize;
+ public String[] info;
+
+ public FieldCacheStats(String totalSize, String[] info) {
+ this.totalSize = totalSize;
+ this.info = info;
}
- return RamUsageEstimator.humanReadableUnits(totalBytesUsed);
+
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/51237438/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java b/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java
index a705e1e..35bdec6 100644
--- a/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java
+++ b/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java
@@ -69,6 +69,7 @@ public class TestSolrFieldCacheMBean extends SolrTestCaseJ4 {
SolrFieldCacheMBean mbean = new SolrFieldCacheMBean();
NamedList stats = checkJmx ? mbean.getStatisticsForJmx() : mbean.getStatistics();
assert(new Integer(stats.get("entries_count").toString()) > 0);
+ assertNotNull(stats.get("total_size"));
assertNotNull(stats.get("entry#0"));
}
@@ -76,7 +77,7 @@ public class TestSolrFieldCacheMBean extends SolrTestCaseJ4 {
SolrFieldCacheMBean mbean = new SolrFieldCacheMBean();
NamedList stats = checkJmx ? mbean.getStatisticsForJmx() : mbean.getStatistics();
assert(new Integer(stats.get("entries_count").toString()) > 0);
- assertNotNull(stats.get("total_size"));
+ assertNull(stats.get("total_size"));
assertNull(stats.get("entry#0"));
}
}
[08/32] lucene-solr:jira/solr-5944: LUCENE-7583: buffer small
leaf-block writes in BKDWriter
Posted by ho...@apache.org.
LUCENE-7583: buffer small leaf-block writes in BKDWriter
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/b97d9d74
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/b97d9d74
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/b97d9d74
Branch: refs/heads/jira/solr-5944
Commit: b97d9d7478f99660c1cfc91ef4461b7405254dea
Parents: cacabc9
Author: Mike McCandless <mi...@apache.org>
Authored: Wed Dec 7 18:59:23 2016 -0500
Committer: Mike McCandless <mi...@apache.org>
Committed: Wed Dec 7 18:59:23 2016 -0500
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 +
.../CompressingStoredFieldsWriter.java | 19 ++--
.../CompressingTermVectorsWriter.java | 11 +-
.../GrowableByteArrayDataOutput.java | 83 ---------------
.../util/GrowableByteArrayDataOutput.java | 103 +++++++++++++++++++
.../org/apache/lucene/util/bkd/BKDWriter.java | 85 ++++++++-------
.../apache/lucene/util/bkd/DocIdsWriter.java | 4 +-
.../TestGrowableByteArrayDataOutput.java | 80 --------------
.../store/TestGrowableByteArrayDataOutput.java | 80 ++++++++++++++
9 files changed, 251 insertions(+), 218 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index c6c39ac..26a9dec 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -134,6 +134,10 @@ Optimizations
a compressed format, using substantially less RAM in some cases
(Adrien Grand, Mike McCandless)
+* LUCENE-7583: BKD writing now buffers each leaf block in heap before
+ writing to disk, giving a small speedup in points-heavy use cases.
+ (Mike McCandless)
+
Other
* LUCENE-7546: Fixed references to benchmark wikipedia data and the Jenkins line-docs file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsWriter.java
index 1956ab7..cda855d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsWriter.java
@@ -33,6 +33,7 @@ import org.apache.lucene.index.MergeState;
import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.GrowableByteArrayDataOutput;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
@@ -157,7 +158,7 @@ public final class CompressingStoredFieldsWriter extends StoredFieldsWriter {
}
this.numStoredFields[numBufferedDocs] = numStoredFieldsInDoc;
numStoredFieldsInDoc = 0;
- endOffsets[numBufferedDocs] = bufferedDocs.length;
+ endOffsets[numBufferedDocs] = bufferedDocs.getPosition();
++numBufferedDocs;
if (triggerFlush()) {
flush();
@@ -210,7 +211,7 @@ public final class CompressingStoredFieldsWriter extends StoredFieldsWriter {
}
private boolean triggerFlush() {
- return bufferedDocs.length >= chunkSize || // chunks of at least chunkSize bytes
+ return bufferedDocs.getPosition() >= chunkSize || // chunks of at least chunkSize bytes
numBufferedDocs >= maxDocsPerChunk;
}
@@ -223,23 +224,23 @@ public final class CompressingStoredFieldsWriter extends StoredFieldsWriter {
lengths[i] = endOffsets[i] - endOffsets[i - 1];
assert lengths[i] >= 0;
}
- final boolean sliced = bufferedDocs.length >= 2 * chunkSize;
+ final boolean sliced = bufferedDocs.getPosition() >= 2 * chunkSize;
writeHeader(docBase, numBufferedDocs, numStoredFields, lengths, sliced);
// compress stored fields to fieldsStream
if (sliced) {
// big chunk, slice it
- for (int compressed = 0; compressed < bufferedDocs.length; compressed += chunkSize) {
- compressor.compress(bufferedDocs.bytes, compressed, Math.min(chunkSize, bufferedDocs.length - compressed), fieldsStream);
+ for (int compressed = 0; compressed < bufferedDocs.getPosition(); compressed += chunkSize) {
+ compressor.compress(bufferedDocs.getBytes(), compressed, Math.min(chunkSize, bufferedDocs.getPosition() - compressed), fieldsStream);
}
} else {
- compressor.compress(bufferedDocs.bytes, 0, bufferedDocs.length, fieldsStream);
+ compressor.compress(bufferedDocs.getBytes(), 0, bufferedDocs.getPosition(), fieldsStream);
}
// reset
docBase += numBufferedDocs;
numBufferedDocs = 0;
- bufferedDocs.length = 0;
+ bufferedDocs.reset();
numChunks++;
}
@@ -459,7 +460,7 @@ public final class CompressingStoredFieldsWriter extends StoredFieldsWriter {
flush();
numDirtyChunks++; // incomplete: we had to force this flush
} else {
- assert bufferedDocs.length == 0;
+ assert bufferedDocs.getPosition() == 0;
}
if (docBase != numDocs) {
throw new RuntimeException("Wrote " + docBase + " docs, finish called with numDocs=" + numDocs);
@@ -468,7 +469,7 @@ public final class CompressingStoredFieldsWriter extends StoredFieldsWriter {
fieldsStream.writeVLong(numChunks);
fieldsStream.writeVLong(numDirtyChunks);
CodecUtil.writeFooter(fieldsStream);
- assert bufferedDocs.length == 0;
+ assert bufferedDocs.getPosition() == 0;
}
// bulk merge is scary: its caused corruption bugs in the past.
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.java
index 46a289a..9bd2483 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsWriter.java
@@ -37,6 +37,7 @@ import org.apache.lucene.index.MergeState;
import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.GrowableByteArrayDataOutput;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
@@ -269,8 +270,8 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {
@Override
public void finishDocument() throws IOException {
// append the payload bytes of the doc after its terms
- termSuffixes.writeBytes(payloadBytes.bytes, payloadBytes.length);
- payloadBytes.length = 0;
+ termSuffixes.writeBytes(payloadBytes.getBytes(), payloadBytes.getPosition());
+ payloadBytes.reset();
++numDocs;
if (triggerFlush()) {
flush();
@@ -316,7 +317,7 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {
}
private boolean triggerFlush() {
- return termSuffixes.length >= chunkSize
+ return termSuffixes.getPosition() >= chunkSize
|| pendingDocs.size() >= MAX_DOCUMENTS_PER_CHUNK;
}
@@ -355,14 +356,14 @@ public final class CompressingTermVectorsWriter extends TermVectorsWriter {
flushPayloadLengths();
// compress terms and payloads and write them to the output
- compressor.compress(termSuffixes.bytes, 0, termSuffixes.length, vectorsStream);
+ compressor.compress(termSuffixes.getBytes(), 0, termSuffixes.getPosition(), vectorsStream);
}
// reset
pendingDocs.clear();
curDoc = null;
curField = null;
- termSuffixes.length = 0;
+ termSuffixes.reset();
numChunks++;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/core/src/java/org/apache/lucene/codecs/compressing/GrowableByteArrayDataOutput.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/compressing/GrowableByteArrayDataOutput.java b/lucene/core/src/java/org/apache/lucene/codecs/compressing/GrowableByteArrayDataOutput.java
deleted file mode 100644
index ec551d1..0000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/compressing/GrowableByteArrayDataOutput.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.lucene.codecs.compressing;
-
-
-import java.io.IOException;
-
-import org.apache.lucene.store.DataOutput;
-import org.apache.lucene.util.ArrayUtil;
-import org.apache.lucene.util.UnicodeUtil;
-
-/**
- * A {@link DataOutput} that can be used to build a byte[].
- * @lucene.internal
- */
-public final class GrowableByteArrayDataOutput extends DataOutput {
-
- /** Minimum utf8 byte size of a string over which double pass over string is to save memory during encode */
- static final int MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING = 65536;
-
- /** The bytes */
- public byte[] bytes;
- /** The length */
- public int length;
-
- // scratch for utf8 encoding of small strings
- byte[] scratchBytes = new byte[16];
-
- /** Create a {@link GrowableByteArrayDataOutput} with the given initial capacity. */
- public GrowableByteArrayDataOutput(int cp) {
- this.bytes = new byte[ArrayUtil.oversize(cp, 1)];
- this.length = 0;
- }
-
- @Override
- public void writeByte(byte b) {
- if (length >= bytes.length) {
- bytes = ArrayUtil.grow(bytes);
- }
- bytes[length++] = b;
- }
-
- @Override
- public void writeBytes(byte[] b, int off, int len) {
- final int newLength = length + len;
- bytes = ArrayUtil.grow(bytes, newLength);
- System.arraycopy(b, off, bytes, length, len);
- length = newLength;
- }
-
- @Override
- public void writeString(String string) throws IOException {
- int maxLen = UnicodeUtil.maxUTF8Length(string.length());
- if (maxLen <= MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING) {
- // string is small enough that we don't need to save memory by falling back to double-pass approach
- // this is just an optimized writeString() that re-uses scratchBytes.
- scratchBytes = ArrayUtil.grow(scratchBytes, maxLen);
- int len = UnicodeUtil.UTF16toUTF8(string, 0, string.length(), scratchBytes);
- writeVInt(len);
- writeBytes(scratchBytes, len);
- } else {
- // use a double pass approach to avoid allocating a large intermediate buffer for string encoding
- int numBytes = UnicodeUtil.calcUTF16toUTF8Length(string, 0, string.length());
- writeVInt(numBytes);
- bytes = ArrayUtil.grow(bytes, length + numBytes);
- length = UnicodeUtil.UTF16toUTF8(string, 0, string.length(), bytes, length);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/core/src/java/org/apache/lucene/util/GrowableByteArrayDataOutput.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/util/GrowableByteArrayDataOutput.java b/lucene/core/src/java/org/apache/lucene/util/GrowableByteArrayDataOutput.java
new file mode 100644
index 0000000..5f00d4a
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/util/GrowableByteArrayDataOutput.java
@@ -0,0 +1,103 @@
+/*
+ * 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.store;
+
+import java.io.IOException;
+
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.UnicodeUtil;
+
+/**
+ * A {@link DataOutput} that can be used to build a byte[].
+ *
+ * @lucene.internal
+ */
+public final class GrowableByteArrayDataOutput extends DataOutput {
+
+ /** Minimum utf8 byte size of a string over which double pass over string is to save memory during encode */
+ static final int MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING = 65536;
+
+ /** The bytes */
+ private byte[] bytes;
+
+ /** The length */
+ private int length;
+
+ // scratch for utf8 encoding of small strings
+ private byte[] scratchBytes;
+
+ /** Create a {@link GrowableByteArrayDataOutput} with the given initial capacity. */
+ public GrowableByteArrayDataOutput(int cp) {
+ this.bytes = new byte[ArrayUtil.oversize(cp, 1)];
+ this.length = 0;
+ }
+
+ @Override
+ public void writeByte(byte b) {
+ if (length >= bytes.length) {
+ bytes = ArrayUtil.grow(bytes);
+ }
+ bytes[length++] = b;
+ }
+
+ @Override
+ public void writeBytes(byte[] b, int off, int len) {
+ final int newLength = length + len;
+ if (newLength > bytes.length) {
+ bytes = ArrayUtil.grow(bytes, newLength);
+ }
+ System.arraycopy(b, off, bytes, length, len);
+ length = newLength;
+ }
+
+ @Override
+ public void writeString(String string) throws IOException {
+ int maxLen = UnicodeUtil.maxUTF8Length(string.length());
+ if (maxLen <= MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING) {
+ // string is small enough that we don't need to save memory by falling back to double-pass approach
+ // this is just an optimized writeString() that re-uses scratchBytes.
+ if (scratchBytes == null) {
+ scratchBytes = new byte[ArrayUtil.oversize(maxLen, Character.BYTES)];
+ } else {
+ scratchBytes = ArrayUtil.grow(scratchBytes, maxLen);
+ }
+ int len = UnicodeUtil.UTF16toUTF8(string, 0, string.length(), scratchBytes);
+ writeVInt(len);
+ writeBytes(scratchBytes, len);
+ } else {
+ // use a double pass approach to avoid allocating a large intermediate buffer for string encoding
+ int numBytes = UnicodeUtil.calcUTF16toUTF8Length(string, 0, string.length());
+ writeVInt(numBytes);
+ bytes = ArrayUtil.grow(bytes, length + numBytes);
+ length = UnicodeUtil.UTF16toUTF8(string, 0, string.length(), bytes, length);
+ }
+ }
+
+ public byte[] getBytes() {
+ return bytes;
+ }
+
+ public int getPosition() {
+ return length;
+ }
+
+ public void reset() {
+ length = 0;
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java b/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java
index c82a0c8..9657578 100644
--- a/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java
@@ -30,7 +30,9 @@ import org.apache.lucene.index.MergeState;
import org.apache.lucene.index.PointValues.IntersectVisitor;
import org.apache.lucene.index.PointValues.Relation;
import org.apache.lucene.store.ChecksumIndexInput;
+import org.apache.lucene.store.DataOutput;
import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.GrowableByteArrayDataOutput;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;
@@ -478,8 +480,8 @@ public class BKDWriter implements Closeable {
}
build(1, numLeaves, values, 0, Math.toIntExact(pointCount), out,
- minPackedValue, maxPackedValue, splitPackedValues, leafBlockFPs,
- new int[maxPointsInLeafNode]);
+ minPackedValue, maxPackedValue, splitPackedValues, leafBlockFPs,
+ new int[maxPointsInLeafNode]);
long indexFP = out.getFilePointer();
writeIndex(out, leafBlockFPs, splitPackedValues);
@@ -556,6 +558,9 @@ public class BKDWriter implements Closeable {
return oneDimWriter.finish();
}
+ // reused when writing leaf blocks
+ private final GrowableByteArrayDataOutput scratchOut = new GrowableByteArrayDataOutput(32*1024);
+
private class OneDimensionBKDWriter {
final IndexOutput out;
@@ -563,8 +568,8 @@ public class BKDWriter implements Closeable {
final List<byte[]> leafBlockStartValues = new ArrayList<>();
final byte[] leafValues = new byte[maxPointsInLeafNode * packedBytesLength];
final int[] leafDocs = new int[maxPointsInLeafNode];
- long valueCount;
- int leafCount;
+ private long valueCount;
+ private int leafCount;
OneDimensionBKDWriter(IndexOutput out) {
if (numDims != 1) {
@@ -589,7 +594,7 @@ public class BKDWriter implements Closeable {
// for asserts
final byte[] lastPackedValue;
- int lastDocID;
+ private int lastDocID;
void add(byte[] packedValue, int docID) throws IOException {
assert valueInOrder(valueCount + leafCount,
@@ -606,8 +611,7 @@ public class BKDWriter implements Closeable {
if (leafCount == maxPointsInLeafNode) {
// We write a block once we hit exactly the max count ... this is different from
- // when we flush a new segment, where we write between max/2 and max per leaf block,
- // so merged segments will behave differently from newly flushed segments:
+ // when we write N > 1 dimensional points where we write between max/2 and max per leaf block
writeLeafBlock();
leafCount = 0;
}
@@ -644,7 +648,6 @@ public class BKDWriter implements Closeable {
}
private void writeLeafBlock() throws IOException {
- //System.out.println("writeLeafBlock pos=" + out.getFilePointer());
assert leafCount != 0;
if (valueCount == 0) {
System.arraycopy(leafValues, 0, minPackedValue, 0, packedBytesLength);
@@ -660,42 +663,39 @@ public class BKDWriter implements Closeable {
leafBlockFPs.add(out.getFilePointer());
checkMaxLeafNodeCount(leafBlockFPs.size());
- Arrays.fill(commonPrefixLengths, bytesPerDim);
// Find per-dim common prefix:
- for(int dim=0;dim<numDims;dim++) {
- int offset1 = dim * bytesPerDim;
- int offset2 = (leafCount - 1) * packedBytesLength + offset1;
- for(int j=0;j<commonPrefixLengths[dim];j++) {
- if (leafValues[offset1+j] != leafValues[offset2+j]) {
- commonPrefixLengths[dim] = j;
- break;
- }
+ int prefix = bytesPerDim;
+ int offset = (leafCount - 1) * packedBytesLength;
+ for(int j=0;j<bytesPerDim;j++) {
+ if (leafValues[j] != leafValues[offset+j]) {
+ prefix = j;
+ break;
}
}
- writeLeafBlockDocs(out, leafDocs, 0, leafCount);
- writeCommonPrefixes(out, commonPrefixLengths, leafValues);
+ commonPrefixLengths[0] = prefix;
- final IntFunction<BytesRef> packedValues = new IntFunction<BytesRef>() {
- final BytesRef scratch = new BytesRef();
-
- {
- scratch.length = packedBytesLength;
- scratch.bytes = leafValues;
- }
+ assert scratchOut.getPosition() == 0;
+ writeLeafBlockDocs(scratchOut, leafDocs, 0, leafCount);
+ writeCommonPrefixes(scratchOut, commonPrefixLengths, leafValues);
+ scratchBytesRef1.length = packedBytesLength;
+ scratchBytesRef1.bytes = leafValues;
+
+ final IntFunction<BytesRef> packedValues = new IntFunction<BytesRef>() {
@Override
public BytesRef apply(int i) {
- scratch.offset = packedBytesLength * i;
- return scratch;
+ scratchBytesRef1.offset = packedBytesLength * i;
+ return scratchBytesRef1;
}
};
assert valuesInOrderAndBounds(leafCount, 0, Arrays.copyOf(leafValues, packedBytesLength),
Arrays.copyOfRange(leafValues, (leafCount - 1) * packedBytesLength, leafCount * packedBytesLength),
packedValues, leafDocs, 0);
- writeLeafBlockPackedValues(out, commonPrefixLengths, leafCount, 0, packedValues);
+ writeLeafBlockPackedValues(scratchOut, commonPrefixLengths, leafCount, 0, packedValues);
+ out.writeBytes(scratchOut.getBytes(), 0, scratchOut.getPosition());
+ scratchOut.reset();
}
-
}
// TODO: there must be a simpler way?
@@ -1259,13 +1259,13 @@ public class BKDWriter implements Closeable {
out.writeBytes(packedIndex, 0, packedIndex.length);
}
- private void writeLeafBlockDocs(IndexOutput out, int[] docIDs, int start, int count) throws IOException {
+ private void writeLeafBlockDocs(DataOutput out, int[] docIDs, int start, int count) throws IOException {
assert count > 0: "maxPointsInLeafNode=" + maxPointsInLeafNode;
out.writeVInt(count);
DocIdsWriter.writeDocIds(docIDs, start, count, out);
}
- private void writeLeafBlockPackedValues(IndexOutput out, int[] commonPrefixLengths, int count, int sortedDim, IntFunction<BytesRef> packedValues) throws IOException {
+ private void writeLeafBlockPackedValues(DataOutput out, int[] commonPrefixLengths, int count, int sortedDim, IntFunction<BytesRef> packedValues) throws IOException {
int prefixLenSum = Arrays.stream(commonPrefixLengths).sum();
if (prefixLenSum == packedBytesLength) {
// all values in this block are equal
@@ -1290,7 +1290,7 @@ public class BKDWriter implements Closeable {
}
}
- private void writeLeafBlockPackedValuesRange(IndexOutput out, int[] commonPrefixLengths, int start, int end, IntFunction<BytesRef> packedValues) throws IOException {
+ private void writeLeafBlockPackedValuesRange(DataOutput out, int[] commonPrefixLengths, int start, int end, IntFunction<BytesRef> packedValues) throws IOException {
for (int i = start; i < end; ++i) {
BytesRef ref = packedValues.apply(i);
assert ref.length == packedBytesLength;
@@ -1316,7 +1316,7 @@ public class BKDWriter implements Closeable {
return end - start;
}
- private void writeCommonPrefixes(IndexOutput out, int[] commonPrefixes, byte[] packedValue) throws IOException {
+ private void writeCommonPrefixes(DataOutput out, int[] commonPrefixes, byte[] packedValue) throws IOException {
for(int dim=0;dim<numDims;dim++) {
out.writeVInt(commonPrefixes[dim]);
//System.out.println(commonPrefixes[dim] + " of " + bytesPerDim);
@@ -1449,7 +1449,8 @@ public class BKDWriter implements Closeable {
}
}
- /* Recursively reorders the provided reader and writes the bkd-tree on the fly. */
+ /* Recursively reorders the provided reader and writes the bkd-tree on the fly; this method is used
+ * when we are writing a new segment directly from IndexWriter's indexing buffer (MutablePointsReader). */
private void build(int nodeID, int leafNodeOffset,
MutablePointValues reader, int from, int to,
IndexOutput out,
@@ -1513,18 +1514,20 @@ public class BKDWriter implements Closeable {
// Save the block file pointer:
leafBlockFPs[nodeID - leafNodeOffset] = out.getFilePointer();
+ assert scratchOut.getPosition() == 0;
+
// Write doc IDs
int[] docIDs = spareDocIds;
for (int i = from; i < to; ++i) {
docIDs[i - from] = reader.getDocID(i);
}
//System.out.println("writeLeafBlock pos=" + out.getFilePointer());
- writeLeafBlockDocs(out, docIDs, 0, count);
+ writeLeafBlockDocs(scratchOut, docIDs, 0, count);
// Write the common prefixes:
reader.getValue(from, scratchBytesRef1);
System.arraycopy(scratchBytesRef1.bytes, scratchBytesRef1.offset, scratch1, 0, packedBytesLength);
- writeCommonPrefixes(out, commonPrefixLengths, scratch1);
+ writeCommonPrefixes(scratchOut, commonPrefixLengths, scratch1);
// Write the full values:
IntFunction<BytesRef> packedValues = new IntFunction<BytesRef>() {
@@ -1536,7 +1539,10 @@ public class BKDWriter implements Closeable {
};
assert valuesInOrderAndBounds(count, sortedDim, minPackedValue, maxPackedValue, packedValues,
docIDs, 0);
- writeLeafBlockPackedValues(out, commonPrefixLengths, count, sortedDim, packedValues);
+ writeLeafBlockPackedValues(scratchOut, commonPrefixLengths, count, sortedDim, packedValues);
+
+ out.writeBytes(scratchOut.getBytes(), 0, scratchOut.getPosition());
+ scratchOut.reset();
} else {
// inner node
@@ -1577,7 +1583,8 @@ public class BKDWriter implements Closeable {
}
}
- /** The array (sized numDims) of PathSlice describe the cell we have currently recursed to. */
+ /** The array (sized numDims) of PathSlice describe the cell we have currently recursed to.
+ /* This method is used when we are merging previously written segments, in the numDims > 1 case. */
private void build(int nodeID, int leafNodeOffset,
PathSlice[] slices,
LongBitSet ordBitSet,
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/core/src/java/org/apache/lucene/util/bkd/DocIdsWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/util/bkd/DocIdsWriter.java b/lucene/core/src/java/org/apache/lucene/util/bkd/DocIdsWriter.java
index 9dce5a8..d76c6c7 100644
--- a/lucene/core/src/java/org/apache/lucene/util/bkd/DocIdsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/util/bkd/DocIdsWriter.java
@@ -19,14 +19,14 @@ package org.apache.lucene.util.bkd;
import java.io.IOException;
import org.apache.lucene.index.PointValues.IntersectVisitor;
+import org.apache.lucene.store.DataOutput;
import org.apache.lucene.store.IndexInput;
-import org.apache.lucene.store.IndexOutput;
class DocIdsWriter {
private DocIdsWriter() {}
- static void writeDocIds(int[] docIds, int start, int count, IndexOutput out) throws IOException {
+ static void writeDocIds(int[] docIds, int start, int count, DataOutput out) throws IOException {
// docs can be sorted either when all docs in a block have the same value
// or when a segment is sorted
boolean sorted = true;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestGrowableByteArrayDataOutput.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestGrowableByteArrayDataOutput.java b/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestGrowableByteArrayDataOutput.java
deleted file mode 100644
index 37a7e4c..0000000
--- a/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestGrowableByteArrayDataOutput.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.lucene.codecs.compressing;
-
-
-import org.apache.lucene.util.LuceneTestCase;
-import org.apache.lucene.util.TestUtil;
-import org.apache.lucene.util.UnicodeUtil;
-import org.junit.Test;
-
-/**
- * Test for {@link GrowableByteArrayDataOutput}
- */
-public class TestGrowableByteArrayDataOutput extends LuceneTestCase {
-
- @Test
- public void testWriteSmallStrings() throws Exception {
- int minSizeForDoublePass = GrowableByteArrayDataOutput.MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING;
-
- // a simple string encoding test
- int num = atLeast(1000);
- for (int i = 0; i < num; i++) {
- // create a small string such that the single pass approach is used
- int length = TestUtil.nextInt(random(), 1, minSizeForDoublePass - 1);
- String unicode = TestUtil.randomFixedByteLengthUnicodeString(random(), length);
- byte[] utf8 = new byte[UnicodeUtil.maxUTF8Length(unicode.length())];
- int len = UnicodeUtil.UTF16toUTF8(unicode, 0, unicode.length(), utf8);
-
- GrowableByteArrayDataOutput dataOutput = new GrowableByteArrayDataOutput(1 << 8);
- //explicitly write utf8 len so that we know how many bytes it occupies
- dataOutput.writeVInt(len);
- int vintLen = dataOutput.length;
- // now write the string which will internally write number of bytes as a vint and then utf8 bytes
- dataOutput.writeString(unicode);
-
- assertEquals("GrowableByteArrayDataOutput wrote the wrong length after encode", len + vintLen * 2, dataOutput.length);
- for (int j = 0, k = vintLen * 2; j < len; j++, k++) {
- assertEquals(utf8[j], dataOutput.bytes[k]);
- }
- }
- }
-
- @Test
- public void testWriteLargeStrings() throws Exception {
- int minSizeForDoublePass = GrowableByteArrayDataOutput.MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING;
-
- int num = atLeast(100);
- for (int i = 0; i < num; i++) {
- String unicode = TestUtil.randomRealisticUnicodeString(random(), minSizeForDoublePass, 10 * minSizeForDoublePass);
- byte[] utf8 = new byte[UnicodeUtil.maxUTF8Length(unicode.length())];
- int len = UnicodeUtil.UTF16toUTF8(unicode, 0, unicode.length(), utf8);
-
- GrowableByteArrayDataOutput dataOutput = new GrowableByteArrayDataOutput(1 << 8);
- //explicitly write utf8 len so that we know how many bytes it occupies
- dataOutput.writeVInt(len);
- int vintLen = dataOutput.length;
- // now write the string which will internally write number of bytes as a vint and then utf8 bytes
- dataOutput.writeString(unicode);
-
- assertEquals("GrowableByteArrayDataOutput wrote the wrong length after encode", len + vintLen * 2, dataOutput.length);
- for (int j = 0, k = vintLen * 2; j < len; j++, k++) {
- assertEquals(utf8[j], dataOutput.bytes[k]);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/b97d9d74/lucene/core/src/test/org/apache/lucene/store/TestGrowableByteArrayDataOutput.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/store/TestGrowableByteArrayDataOutput.java b/lucene/core/src/test/org/apache/lucene/store/TestGrowableByteArrayDataOutput.java
new file mode 100644
index 0000000..10992b7
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/store/TestGrowableByteArrayDataOutput.java
@@ -0,0 +1,80 @@
+/*
+ * 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.store;
+
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.TestUtil;
+import org.apache.lucene.util.UnicodeUtil;
+import org.junit.Test;
+
+/**
+ * Test for {@link GrowableByteArrayDataOutput}
+ */
+public class TestGrowableByteArrayDataOutput extends LuceneTestCase {
+
+ @Test
+ public void testWriteSmallStrings() throws Exception {
+ int minSizeForDoublePass = GrowableByteArrayDataOutput.MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING;
+
+ // a simple string encoding test
+ int num = atLeast(1000);
+ for (int i = 0; i < num; i++) {
+ // create a small string such that the single pass approach is used
+ int length = TestUtil.nextInt(random(), 1, minSizeForDoublePass - 1);
+ String unicode = TestUtil.randomFixedByteLengthUnicodeString(random(), length);
+ byte[] utf8 = new byte[UnicodeUtil.maxUTF8Length(unicode.length())];
+ int len = UnicodeUtil.UTF16toUTF8(unicode, 0, unicode.length(), utf8);
+
+ GrowableByteArrayDataOutput dataOutput = new GrowableByteArrayDataOutput(1 << 8);
+ //explicitly write utf8 len so that we know how many bytes it occupies
+ dataOutput.writeVInt(len);
+ int vintLen = dataOutput.getPosition();
+ // now write the string which will internally write number of bytes as a vint and then utf8 bytes
+ dataOutput.writeString(unicode);
+
+ assertEquals("GrowableByteArrayDataOutput wrote the wrong length after encode", len + vintLen * 2, dataOutput.getPosition());
+ for (int j = 0, k = vintLen * 2; j < len; j++, k++) {
+ assertEquals(utf8[j], dataOutput.getBytes()[k]);
+ }
+ }
+ }
+
+ @Test
+ public void testWriteLargeStrings() throws Exception {
+ int minSizeForDoublePass = GrowableByteArrayDataOutput.MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING;
+
+ int num = atLeast(100);
+ for (int i = 0; i < num; i++) {
+ String unicode = TestUtil.randomRealisticUnicodeString(random(), minSizeForDoublePass, 10 * minSizeForDoublePass);
+ byte[] utf8 = new byte[UnicodeUtil.maxUTF8Length(unicode.length())];
+ int len = UnicodeUtil.UTF16toUTF8(unicode, 0, unicode.length(), utf8);
+
+ GrowableByteArrayDataOutput dataOutput = new GrowableByteArrayDataOutput(1 << 8);
+ //explicitly write utf8 len so that we know how many bytes it occupies
+ dataOutput.writeVInt(len);
+ int vintLen = dataOutput.getPosition();
+ // now write the string which will internally write number of bytes as a vint and then utf8 bytes
+ dataOutput.writeString(unicode);
+
+ assertEquals("GrowableByteArrayDataOutput wrote the wrong length after encode", len + vintLen * 2, dataOutput.getPosition());
+ for (int j = 0, k = vintLen * 2; j < len; j++, k++) {
+ assertEquals(utf8[j], dataOutput.getBytes()[k]);
+ }
+ }
+ }
+}
[21/32] lucene-solr:jira/solr-5944: SOLR-9707: Don't forward
DeleteByQuery requests to down replicas
Posted by ho...@apache.org.
SOLR-9707: Don't forward DeleteByQuery requests to down replicas
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/fecbbe08
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/fecbbe08
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/fecbbe08
Branch: refs/heads/jira/solr-5944
Commit: fecbbe081fd4a777f01517fdd8631e69797def38
Parents: 39ba130
Author: Varun Thacker <va...@apache.org>
Authored: Mon Dec 12 15:28:22 2016 -0800
Committer: Varun Thacker <va...@apache.org>
Committed: Mon Dec 12 15:28:22 2016 -0800
----------------------------------------------------------------------
solr/CHANGES.txt | 2 ++
.../solr/update/processor/DistributedUpdateProcessor.java | 8 +++-----
2 files changed, 5 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/fecbbe08/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 37cccae..a8a3f97 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -240,6 +240,8 @@ Bug Fixes
* SOLR-9834: A variety of spots in the code can create a collection zk node after the collection has been
removed. (Mark Miller)
+* SOLR-9707: Don't forward DeleteByQuery requests to down replicas. (Jessica Cheng Mallet via Varun Thacker)
+
Other Changes
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/fecbbe08/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 b8bdd16..c62a90a 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
@@ -658,8 +658,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
String shardId = cloudDesc.getShardId();
try {
- Replica leaderReplica = zkController.getZkStateReader().getLeaderRetry(
- collection, shardId);
+ Replica leaderReplica = zkController.getZkStateReader().getLeaderRetry(collection, shardId);
isLeader = leaderReplica.getName().equals(
req.getCore().getCoreDescriptor().getCloudDescriptor()
.getCoreNodeName());
@@ -668,7 +667,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
forwardToLeader = false;
List<ZkCoreNodeProps> replicaProps = zkController.getZkStateReader()
- .getReplicaProps(collection, shardId, leaderReplica.getName());
+ .getReplicaProps(collection, shardId, leaderReplica.getName(), null, Replica.State.DOWN);
if (replicaProps != null) {
nodes = new ArrayList<>(replicaProps.size());
for (ZkCoreNodeProps props : replicaProps) {
@@ -677,8 +676,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
- throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "",
- e);
+ throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
}
return nodes;
[12/32] lucene-solr:jira/solr-5944: LUCENE-7583: move this class to
the right package
Posted by ho...@apache.org.
LUCENE-7583: move this class to the right package
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/c1856175
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/c1856175
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/c1856175
Branch: refs/heads/jira/solr-5944
Commit: c185617582b4bf3ce2899c9ae67e9eeaf2c21741
Parents: 1d2e440
Author: Mike McCandless <mi...@apache.org>
Authored: Thu Dec 8 18:34:51 2016 -0500
Committer: Mike McCandless <mi...@apache.org>
Committed: Thu Dec 8 18:34:51 2016 -0500
----------------------------------------------------------------------
.../store/GrowableByteArrayDataOutput.java | 103 +++++++++++++++++++
.../util/GrowableByteArrayDataOutput.java | 103 -------------------
2 files changed, 103 insertions(+), 103 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c1856175/lucene/core/src/java/org/apache/lucene/store/GrowableByteArrayDataOutput.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/store/GrowableByteArrayDataOutput.java b/lucene/core/src/java/org/apache/lucene/store/GrowableByteArrayDataOutput.java
new file mode 100644
index 0000000..5f00d4a
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/store/GrowableByteArrayDataOutput.java
@@ -0,0 +1,103 @@
+/*
+ * 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.store;
+
+import java.io.IOException;
+
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.UnicodeUtil;
+
+/**
+ * A {@link DataOutput} that can be used to build a byte[].
+ *
+ * @lucene.internal
+ */
+public final class GrowableByteArrayDataOutput extends DataOutput {
+
+ /** Minimum utf8 byte size of a string over which double pass over string is to save memory during encode */
+ static final int MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING = 65536;
+
+ /** The bytes */
+ private byte[] bytes;
+
+ /** The length */
+ private int length;
+
+ // scratch for utf8 encoding of small strings
+ private byte[] scratchBytes;
+
+ /** Create a {@link GrowableByteArrayDataOutput} with the given initial capacity. */
+ public GrowableByteArrayDataOutput(int cp) {
+ this.bytes = new byte[ArrayUtil.oversize(cp, 1)];
+ this.length = 0;
+ }
+
+ @Override
+ public void writeByte(byte b) {
+ if (length >= bytes.length) {
+ bytes = ArrayUtil.grow(bytes);
+ }
+ bytes[length++] = b;
+ }
+
+ @Override
+ public void writeBytes(byte[] b, int off, int len) {
+ final int newLength = length + len;
+ if (newLength > bytes.length) {
+ bytes = ArrayUtil.grow(bytes, newLength);
+ }
+ System.arraycopy(b, off, bytes, length, len);
+ length = newLength;
+ }
+
+ @Override
+ public void writeString(String string) throws IOException {
+ int maxLen = UnicodeUtil.maxUTF8Length(string.length());
+ if (maxLen <= MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING) {
+ // string is small enough that we don't need to save memory by falling back to double-pass approach
+ // this is just an optimized writeString() that re-uses scratchBytes.
+ if (scratchBytes == null) {
+ scratchBytes = new byte[ArrayUtil.oversize(maxLen, Character.BYTES)];
+ } else {
+ scratchBytes = ArrayUtil.grow(scratchBytes, maxLen);
+ }
+ int len = UnicodeUtil.UTF16toUTF8(string, 0, string.length(), scratchBytes);
+ writeVInt(len);
+ writeBytes(scratchBytes, len);
+ } else {
+ // use a double pass approach to avoid allocating a large intermediate buffer for string encoding
+ int numBytes = UnicodeUtil.calcUTF16toUTF8Length(string, 0, string.length());
+ writeVInt(numBytes);
+ bytes = ArrayUtil.grow(bytes, length + numBytes);
+ length = UnicodeUtil.UTF16toUTF8(string, 0, string.length(), bytes, length);
+ }
+ }
+
+ public byte[] getBytes() {
+ return bytes;
+ }
+
+ public int getPosition() {
+ return length;
+ }
+
+ public void reset() {
+ length = 0;
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/c1856175/lucene/core/src/java/org/apache/lucene/util/GrowableByteArrayDataOutput.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/util/GrowableByteArrayDataOutput.java b/lucene/core/src/java/org/apache/lucene/util/GrowableByteArrayDataOutput.java
deleted file mode 100644
index 5f00d4a..0000000
--- a/lucene/core/src/java/org/apache/lucene/util/GrowableByteArrayDataOutput.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.lucene.store;
-
-import java.io.IOException;
-
-import org.apache.lucene.store.DataOutput;
-import org.apache.lucene.util.ArrayUtil;
-import org.apache.lucene.util.UnicodeUtil;
-
-/**
- * A {@link DataOutput} that can be used to build a byte[].
- *
- * @lucene.internal
- */
-public final class GrowableByteArrayDataOutput extends DataOutput {
-
- /** Minimum utf8 byte size of a string over which double pass over string is to save memory during encode */
- static final int MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING = 65536;
-
- /** The bytes */
- private byte[] bytes;
-
- /** The length */
- private int length;
-
- // scratch for utf8 encoding of small strings
- private byte[] scratchBytes;
-
- /** Create a {@link GrowableByteArrayDataOutput} with the given initial capacity. */
- public GrowableByteArrayDataOutput(int cp) {
- this.bytes = new byte[ArrayUtil.oversize(cp, 1)];
- this.length = 0;
- }
-
- @Override
- public void writeByte(byte b) {
- if (length >= bytes.length) {
- bytes = ArrayUtil.grow(bytes);
- }
- bytes[length++] = b;
- }
-
- @Override
- public void writeBytes(byte[] b, int off, int len) {
- final int newLength = length + len;
- if (newLength > bytes.length) {
- bytes = ArrayUtil.grow(bytes, newLength);
- }
- System.arraycopy(b, off, bytes, length, len);
- length = newLength;
- }
-
- @Override
- public void writeString(String string) throws IOException {
- int maxLen = UnicodeUtil.maxUTF8Length(string.length());
- if (maxLen <= MIN_UTF8_SIZE_TO_ENABLE_DOUBLE_PASS_ENCODING) {
- // string is small enough that we don't need to save memory by falling back to double-pass approach
- // this is just an optimized writeString() that re-uses scratchBytes.
- if (scratchBytes == null) {
- scratchBytes = new byte[ArrayUtil.oversize(maxLen, Character.BYTES)];
- } else {
- scratchBytes = ArrayUtil.grow(scratchBytes, maxLen);
- }
- int len = UnicodeUtil.UTF16toUTF8(string, 0, string.length(), scratchBytes);
- writeVInt(len);
- writeBytes(scratchBytes, len);
- } else {
- // use a double pass approach to avoid allocating a large intermediate buffer for string encoding
- int numBytes = UnicodeUtil.calcUTF16toUTF8Length(string, 0, string.length());
- writeVInt(numBytes);
- bytes = ArrayUtil.grow(bytes, length + numBytes);
- length = UnicodeUtil.UTF16toUTF8(string, 0, string.length(), bytes, length);
- }
- }
-
- public byte[] getBytes() {
- return bytes;
- }
-
- public int getPosition() {
- return length;
- }
-
- public void reset() {
- length = 0;
- }
-}
[16/32] lucene-solr:jira/solr-5944: LUCENE-7570: don't run merges
while holding the commitLock to prevent deadlock when merges are stalled and
a tragic merge exception strikes
Posted by ho...@apache.org.
LUCENE-7570: don't run merges while holding the commitLock to prevent deadlock when merges are stalled and a tragic merge exception strikes
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/2b073a2f
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/2b073a2f
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/2b073a2f
Branch: refs/heads/jira/solr-5944
Commit: 2b073a2f296289617bea8256d7efec06049df739
Parents: 7cffae3
Author: Mike McCandless <mi...@apache.org>
Authored: Fri Dec 9 18:41:30 2016 -0500
Committer: Mike McCandless <mi...@apache.org>
Committed: Fri Dec 9 18:41:30 2016 -0500
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 ++
.../org/apache/lucene/index/IndexWriter.java | 26 ++++++--
.../index/TestTragicIndexWriterDeadlock.java | 69 +++++++++++++++++++-
3 files changed, 91 insertions(+), 8 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/2b073a2f/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index da6e3d2..15b89f0 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -94,6 +94,10 @@ Bug Fixes
in the index sort, since this would lead to corruption. (Jim
Ferenczi via Mike McCandless)
+* LUCENE-7570: IndexWriter may deadlock if a commit is running while
+ there are too many merges running and one of the merges hits a
+ tragic exception (Joey Echeverria via Mike McCandless)
+
Improvements
* LUCENE-6824: TermAutomatonQuery now rewrites to TermQuery,
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/2b073a2f/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
index 3ee87b1..4789505 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
@@ -2952,11 +2952,16 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
@Override
public final long prepareCommit() throws IOException {
ensureOpen();
- pendingSeqNo = prepareCommitInternal(config.getMergePolicy());
+ boolean[] doMaybeMerge = new boolean[1];
+ pendingSeqNo = prepareCommitInternal(doMaybeMerge);
+ // we must do this outside of the commitLock else we can deadlock:
+ if (doMaybeMerge[0]) {
+ maybeMerge(config.getMergePolicy(), MergeTrigger.FULL_FLUSH, UNBOUNDED_MAX_MERGE_SEGMENTS);
+ }
return pendingSeqNo;
}
- private long prepareCommitInternal(MergePolicy mergePolicy) throws IOException {
+ private long prepareCommitInternal(boolean[] doMaybeMerge) throws IOException {
startCommitTime = System.nanoTime();
synchronized(commitLock) {
ensureOpen(false);
@@ -3063,7 +3068,7 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
boolean success = false;
try {
if (anySegmentsFlushed) {
- maybeMerge(mergePolicy, MergeTrigger.FULL_FLUSH, UNBOUNDED_MAX_MERGE_SEGMENTS);
+ doMaybeMerge[0] = true;
}
startCommit(toCommit);
success = true;
@@ -3184,6 +3189,10 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
infoStream.message("IW", "commit: start");
}
+ boolean[] doMaybeMerge = new boolean[1];
+
+ long seqNo;
+
synchronized(commitLock) {
ensureOpen(false);
@@ -3191,13 +3200,11 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
infoStream.message("IW", "commit: enter lock");
}
- long seqNo;
-
if (pendingCommit == null) {
if (infoStream.isEnabled("IW")) {
infoStream.message("IW", "commit: now prepare");
}
- seqNo = prepareCommitInternal(mergePolicy);
+ seqNo = prepareCommitInternal(doMaybeMerge);
} else {
if (infoStream.isEnabled("IW")) {
infoStream.message("IW", "commit: already prepared");
@@ -3206,9 +3213,14 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
}
finishCommit();
+ }
- return seqNo;
+ // we must do this outside of the commitLock else we can deadlock:
+ if (doMaybeMerge[0]) {
+ maybeMerge(mergePolicy, MergeTrigger.FULL_FLUSH, UNBOUNDED_MAX_MERGE_SEGMENTS);
}
+
+ return seqNo;
}
private final void finishCommit() throws IOException {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/2b073a2f/lucene/core/src/test/org/apache/lucene/index/TestTragicIndexWriterDeadlock.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestTragicIndexWriterDeadlock.java b/lucene/core/src/test/org/apache/lucene/index/TestTragicIndexWriterDeadlock.java
index 3cce698..80f9392 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestTragicIndexWriterDeadlock.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestTragicIndexWriterDeadlock.java
@@ -14,13 +14,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.lucene.index;
+package org.apache.lucene.index;
+import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.lucene.document.Document;
+import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.LuceneTestCase;
@@ -92,4 +94,69 @@ public class TestTragicIndexWriterDeadlock extends LuceneTestCase {
w.close();
dir.close();
}
+
+ // LUCENE-7570
+ public void testDeadlockStalledMerges() throws Exception {
+ Directory dir = newDirectory();
+ IndexWriterConfig iwc = new IndexWriterConfig();
+
+ // so we merge every 2 segments:
+ LogMergePolicy mp = new LogDocMergePolicy();
+ mp.setMergeFactor(2);
+ iwc.setMergePolicy(mp);
+ CountDownLatch done = new CountDownLatch(1);
+ ConcurrentMergeScheduler cms = new ConcurrentMergeScheduler() {
+ @Override
+ protected void doMerge(IndexWriter writer, MergePolicy.OneMerge merge) throws IOException {
+ // let merge takes forever, until commit thread is stalled
+ try {
+ done.await();
+ } catch (InterruptedException ie) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(ie);
+ }
+ super.doMerge(writer, merge);
+ }
+
+ @Override
+ protected synchronized void doStall() {
+ done.countDown();
+ super.doStall();
+ }
+
+ @Override
+ protected void handleMergeException(Directory dir, Throwable exc) {
+ }
+ };
+
+ // so we stall once the 2nd merge wants to run:
+ cms.setMaxMergesAndThreads(1, 1);
+ iwc.setMergeScheduler(cms);
+
+ // so we write a segment every 2 indexed docs:
+ iwc.setMaxBufferedDocs(2);
+
+ final IndexWriter w = new IndexWriter(dir, iwc) {
+ @Override
+ void mergeSuccess(MergePolicy.OneMerge merge) {
+ // tragedy strikes!
+ throw new OutOfMemoryError();
+ }
+ };
+
+ w.addDocument(new Document());
+ w.addDocument(new Document());
+ // w writes first segment
+ w.addDocument(new Document());
+ w.addDocument(new Document());
+ // w writes second segment, and kicks off merge, that takes forever (done.await)
+ w.addDocument(new Document());
+ w.addDocument(new Document());
+ // w writes third segment
+ w.addDocument(new Document());
+ w.commit();
+ // w writes fourth segment, and commit flushes and kicks off merge that stalls
+ w.close();
+ dir.close();
+ }
}
[14/32] lucene-solr:jira/solr-5944: LUCENE-7581: don't allow updating
a doc values field if it's used in the index sort
Posted by ho...@apache.org.
LUCENE-7581: don't allow updating a doc values field if it's used in the index sort
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/4efbde4e
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/4efbde4e
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/4efbde4e
Branch: refs/heads/jira/solr-5944
Commit: 4efbde4e76277f364952866c071bb953ca2be070
Parents: 22d04a7
Author: Mike McCandless <mi...@apache.org>
Authored: Fri Dec 9 18:05:13 2016 -0500
Committer: Mike McCandless <mi...@apache.org>
Committed: Fri Dec 9 18:05:13 2016 -0500
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 +++
.../org/apache/lucene/index/IndexWriter.java | 6 ++++
.../apache/lucene/index/IndexWriterConfig.java | 3 ++
.../lucene/index/LiveIndexWriterConfig.java | 13 +++++++++
.../apache/lucene/index/TestIndexSorting.java | 30 ++++++++++++++++++--
5 files changed, 53 insertions(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/4efbde4e/lucene/CHANGES.txt
----------------------------------------------------------------------
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index b9deb7e..da6e3d2 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -90,6 +90,10 @@ Bug Fixes
that does not extend ReflectiveAccessException in Java 9.
(Uwe Schindler)
+* LUCENE-7581: Lucene now prevents updating a doc values field that is used
+ in the index sort, since this would lead to corruption. (Jim
+ Ferenczi via Mike McCandless)
+
Improvements
* LUCENE-6824: TermAutomatonQuery now rewrites to TermQuery,
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/4efbde4e/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
index 9868785..3ee87b1 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
@@ -1619,6 +1619,9 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
if (!globalFieldNumberMap.contains(field, DocValuesType.NUMERIC)) {
throw new IllegalArgumentException("can only update existing numeric-docvalues fields!");
}
+ if (config.getIndexSortFields().contains(field)) {
+ throw new IllegalArgumentException("cannot update docvalues field involved in the index sort, field=" + field + ", sort=" + config.getIndexSort());
+ }
try {
long seqNo = docWriter.updateDocValues(new NumericDocValuesUpdate(term, field, value));
if (seqNo < 0) {
@@ -1713,6 +1716,9 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
if (!globalFieldNumberMap.contains(f.name(), dvType)) {
throw new IllegalArgumentException("can only update existing docvalues fields! field=" + f.name() + ", type=" + dvType);
}
+ if (config.getIndexSortFields().contains(f.name())) {
+ throw new IllegalArgumentException("cannot update docvalues field involved in the index sort, field=" + f.name() + ", sort=" + config.getIndexSort());
+ }
switch (dvType) {
case NUMERIC:
dvUpdates[i] = new NumericDocValuesUpdate(term, f.name(), (Long) f.numericValue());
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/4efbde4e/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java b/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
index 4f642ee..ce4f0a8 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
@@ -18,7 +18,9 @@ package org.apache.lucene.index;
import java.io.PrintStream;
+import java.util.Arrays;
import java.util.EnumSet;
+import java.util.stream.Collectors;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
@@ -474,6 +476,7 @@ public final class IndexWriterConfig extends LiveIndexWriterConfig {
}
}
this.indexSort = sort;
+ this.indexSortFields = Arrays.stream(sort.getSort()).map((s) -> s.getField()).collect(Collectors.toSet());
return this;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/4efbde4e/lucene/core/src/java/org/apache/lucene/index/LiveIndexWriterConfig.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/LiveIndexWriterConfig.java b/lucene/core/src/java/org/apache/lucene/index/LiveIndexWriterConfig.java
index cec70c0..d9e1bc7 100644
--- a/lucene/core/src/java/org/apache/lucene/index/LiveIndexWriterConfig.java
+++ b/lucene/core/src/java/org/apache/lucene/index/LiveIndexWriterConfig.java
@@ -17,6 +17,9 @@
package org.apache.lucene.index;
+import java.util.Collections;
+import java.util.Set;
+
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.index.DocumentsWriterPerThread.IndexingChain;
@@ -98,6 +101,9 @@ public class LiveIndexWriterConfig {
/** The sort order to use to write merged segments. */
protected Sort indexSort = null;
+ /** The field names involved in the index sort */
+ protected Set<String> indexSortFields = Collections.emptySet();
+
// used by IndexWriterConfig
LiveIndexWriterConfig(Analyzer analyzer) {
this.analyzer = analyzer;
@@ -457,6 +463,13 @@ public class LiveIndexWriterConfig {
return indexSort;
}
+ /**
+ * Returns the field names involved in the index sort
+ */
+ public Set<String> getIndexSortFields() {
+ return indexSortFields;
+ }
+
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/4efbde4e/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
index 5ebf8f4..08a85ef 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
@@ -1700,6 +1700,29 @@ public class TestIndexSorting extends LuceneTestCase {
dir.close();
}
+
+ // docvalues fields involved in the index sort cannot be updated
+ public void testBadDVUpdate() throws Exception {
+ Directory dir = newDirectory();
+ IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
+ Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG));
+ iwc.setIndexSort(indexSort);
+ IndexWriter w = new IndexWriter(dir, iwc);
+ Document doc = new Document();
+ doc.add(new StringField("id", new BytesRef("0"), Store.NO));
+ doc.add(new NumericDocValuesField("foo", random().nextInt()));
+ w.addDocument(doc);
+ w.commit();
+ IllegalArgumentException exc = expectThrows(IllegalArgumentException.class,
+ () -> w.updateDocValues(new Term("id", "0"), new NumericDocValuesField("foo", -1)));
+ assertEquals(exc.getMessage(), "cannot update docvalues field involved in the index sort, field=foo, sort=<long: \"foo\">");
+ exc = expectThrows(IllegalArgumentException.class,
+ () -> w.updateNumericDocValue(new Term("id", "0"), "foo", -1));
+ assertEquals(exc.getMessage(), "cannot update docvalues field involved in the index sort, field=foo, sort=<long: \"foo\">");
+ w.close();
+ dir.close();
+ }
+
static class DVUpdateRunnable implements Runnable {
private final int numDocs;
@@ -1727,7 +1750,7 @@ public class TestIndexSorting extends LuceneTestCase {
final long value = random.nextInt(20);
synchronized (values) {
- w.updateDocValues(new Term("id", Integer.toString(id)), new NumericDocValuesField("foo", value));
+ w.updateDocValues(new Term("id", Integer.toString(id)), new NumericDocValuesField("bar", value));
values.put(id, value);
}
@@ -1762,7 +1785,8 @@ public class TestIndexSorting extends LuceneTestCase {
for (int i = 0; i < numDocs; ++i) {
Document doc = new Document();
doc.add(new StringField("id", Integer.toString(i), Store.NO));
- doc.add(new NumericDocValuesField("foo", -1));
+ doc.add(new NumericDocValuesField("foo", random().nextInt()));
+ doc.add(new NumericDocValuesField("bar", -1));
w.addDocument(doc);
values.put(i, -1L);
}
@@ -1786,7 +1810,7 @@ public class TestIndexSorting extends LuceneTestCase {
for (int i = 0; i < numDocs; ++i) {
final TopDocs topDocs = searcher.search(new TermQuery(new Term("id", Integer.toString(i))), 1);
assertEquals(1, topDocs.totalHits);
- NumericDocValues dvs = MultiDocValues.getNumericValues(reader, "foo");
+ NumericDocValues dvs = MultiDocValues.getNumericValues(reader, "bar");
int hitDoc = topDocs.scoreDocs[0].doc;
assertEquals(hitDoc, dvs.advance(hitDoc));
assertEquals(values.get(i).longValue(), dvs.longValue());
[09/32] lucene-solr:jira/solr-5944: SOLR-9834: A variety of spots in
the code can create a collection zk node after the collection has been
removed.
Posted by ho...@apache.org.
SOLR-9834: A variety of spots in the code can create a collection zk node after the collection has been removed.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/10552099
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/10552099
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/10552099
Branch: refs/heads/jira/solr-5944
Commit: 1055209940faec71bd8046af3323d5982529525b
Parents: b97d9d7
Author: markrmiller <ma...@apache.org>
Authored: Thu Dec 8 12:03:55 2016 -0500
Committer: markrmiller <ma...@apache.org>
Committed: Thu Dec 8 12:03:55 2016 -0500
----------------------------------------------------------------------
solr/CHANGES.txt | 3 +
.../solr/cloud/CloudConfigSetService.java | 24 ++-
.../org/apache/solr/cloud/CloudDescriptor.java | 2 +-
.../apache/solr/cloud/CreateCollectionCmd.java | 146 ++++++++++++++++++-
.../org/apache/solr/cloud/ElectionContext.java | 20 +--
.../org/apache/solr/cloud/LeaderElector.java | 9 +-
.../org/apache/solr/cloud/ZkController.java | 128 +---------------
.../apache/solr/cloud/ZkSolrResourceLoader.java | 2 +-
.../org/apache/solr/core/ConfigSetService.java | 7 +-
.../solr/handler/admin/CollectionsHandler.java | 2 +
.../apache/solr/cloud/LeaderElectionTest.java | 2 +
...verseerCollectionConfigSetProcessorTest.java | 33 +++--
.../org/apache/solr/cloud/ZkSolrClientTest.java | 54 +++++++
.../apache/solr/common/cloud/SolrZkClient.java | 29 +++-
.../apache/solr/common/cloud/ZkCmdExecutor.java | 15 +-
15 files changed, 307 insertions(+), 169 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 8dee837..abd9997 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -230,6 +230,9 @@ Bug Fixes
* SOLR-9832: Schema modifications are not immediately visible on the coordinating node. (Steve Rowe)
+* SOLR-9834: A variety of spots in the code can create a collection zk node after the collection has been
+ removed. (Mark Miller)
+
Other Changes
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/cloud/CloudConfigSetService.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/CloudConfigSetService.java b/solr/core/src/java/org/apache/solr/cloud/CloudConfigSetService.java
index bf11e92..6e0583f 100644
--- a/solr/core/src/java/org/apache/solr/cloud/CloudConfigSetService.java
+++ b/solr/core/src/java/org/apache/solr/cloud/CloudConfigSetService.java
@@ -16,12 +16,20 @@
*/
package org.apache.solr.cloud;
+import java.lang.invoke.MethodHandles;
+
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.core.ConfigSetService;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrResourceLoader;
+import org.apache.zookeeper.KeeperException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class CloudConfigSetService extends ConfigSetService {
-
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
private final ZkController zkController;
public CloudConfigSetService(SolrResourceLoader loader, ZkController zkController) {
@@ -31,8 +39,18 @@ public class CloudConfigSetService extends ConfigSetService {
@Override
public SolrResourceLoader createCoreResourceLoader(CoreDescriptor cd) {
- // TODO: Shouldn't the collection node be created by the Collections API?
- zkController.createCollectionZkNode(cd.getCloudDescriptor());
+ try {
+ // for back compat with cores that can create collections without the collections API
+ if (!zkController.getZkClient().exists(ZkStateReader.COLLECTIONS_ZKNODE + "/" + cd.getCollectionName(), true)) {
+ CreateCollectionCmd.createCollectionZkNode(zkController.getZkClient(), cd.getCollectionName(), cd.getCloudDescriptor().getParams());
+ }
+ } catch (KeeperException e) {
+ SolrException.log(log, null, e);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ SolrException.log(log, null, e);
+ }
+
String configName = zkController.getZkStateReader().readConfigName(cd.getCollectionName());
return new ZkSolrResourceLoader(cd.getInstanceDir(), configName, parentLoader.getClassLoader(),
cd.getSubstitutableProperties(), zkController);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java b/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java
index 4dd1527..fdc7b02 100644
--- a/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java
+++ b/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java
@@ -33,7 +33,7 @@ public class CloudDescriptor {
private String roles = null;
private Integer numShards;
private String nodeName = null;
- private Map<String, String> collectionParams = new HashMap<>();
+ private Map<String,String> collectionParams = new HashMap<>();
private volatile boolean isLeader = false;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/cloud/CreateCollectionCmd.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/CreateCollectionCmd.java b/solr/core/src/java/org/apache/solr/cloud/CreateCollectionCmd.java
index a067b4a..a1bb70e 100644
--- a/solr/core/src/java/org/apache/solr/cloud/CreateCollectionCmd.java
+++ b/solr/core/src/java/org/apache/solr/cloud/CreateCollectionCmd.java
@@ -25,19 +25,23 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.solr.cloud.OverseerCollectionMessageHandler.Cmd;
import org.apache.solr.cloud.overseer.ClusterStateMutator;
import org.apache.solr.cloud.rule.ReplicaAssigner;
import org.apache.solr.common.SolrException;
+import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DocRouter;
import org.apache.solr.common.cloud.ImplicitDocRouter;
import org.apache.solr.common.cloud.Replica;
+import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkConfigManager;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
+import org.apache.solr.common.cloud.ZooKeeperException;
import org.apache.solr.common.params.CoreAdminParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
@@ -46,7 +50,9 @@ import org.apache.solr.common.util.Utils;
import org.apache.solr.handler.component.ShardHandler;
import org.apache.solr.handler.component.ShardRequest;
import org.apache.solr.util.TimeOut;
+import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.NoNodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -64,9 +70,11 @@ import static org.apache.solr.common.util.StrUtils.formatString;
public class CreateCollectionCmd implements Cmd {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final OverseerCollectionMessageHandler ocmh;
+ private SolrZkClient zkClient;
public CreateCollectionCmd(OverseerCollectionMessageHandler ocmh) {
this.ocmh = ocmh;
+ this.zkClient = ocmh.zkStateReader.getZkClient();
}
@Override
@@ -84,7 +92,6 @@ public class CreateCollectionCmd implements Cmd {
ocmh.validateConfigOrThrowSolrException(configName);
-
try {
// look at the replication factor and see if it matches reality
// if it does not, find best nodes to create more cores
@@ -157,10 +164,20 @@ public class CreateCollectionCmd implements Cmd {
}
ZkStateReader zkStateReader = ocmh.zkStateReader;
- boolean isLegacyCloud = Overseer.isLegacy(zkStateReader);
+ boolean isLegacyCloud = Overseer.isLegacy(zkStateReader);
ocmh.createConfNode(configName, collectionName, isLegacyCloud);
+ Map<String,String> collectionParams = new HashMap<>();
+ Map<String,Object> collectionProps = message.getProperties();
+ for (String propName : collectionProps.keySet()) {
+ if (propName.startsWith(ZkController.COLLECTION_PARAM_PREFIX)) {
+ collectionParams.put(propName.substring(ZkController.COLLECTION_PARAM_PREFIX.length()), (String) collectionProps.get(propName));
+ }
+ }
+
+ createCollectionZkNode(zkClient, collectionName, collectionParams);
+
Overseer.getStateUpdateQueue(zkStateReader.getZkClient()).offer(Utils.toJSON(message));
// wait for a while until we don't see the collection
@@ -288,4 +305,129 @@ public class CreateCollectionCmd implements Cmd {
}
return configName;
}
+
+ public static void createCollectionZkNode(SolrZkClient zkClient, String collection, Map<String,String> params) {
+ log.debug("Check for collection zkNode:" + collection);
+ String collectionPath = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection;
+
+ try {
+ if (!zkClient.exists(collectionPath, true)) {
+ log.debug("Creating collection in ZooKeeper:" + collection);
+
+ try {
+ Map<String,Object> collectionProps = new HashMap<>();
+
+ // TODO: if collection.configName isn't set, and there isn't already a conf in zk, just use that?
+ String defaultConfigName = System.getProperty(ZkController.COLLECTION_PARAM_PREFIX + ZkController.CONFIGNAME_PROP, collection);
+
+ if (params.size() > 0) {
+ collectionProps.putAll(params);
+ // if the config name wasn't passed in, use the default
+ if (!collectionProps.containsKey(ZkController.CONFIGNAME_PROP)) {
+ // users can create the collection node and conf link ahead of time, or this may return another option
+ getConfName(zkClient, collection, collectionPath, collectionProps);
+ }
+
+ } else if (System.getProperty("bootstrap_confdir") != null) {
+ // if we are bootstrapping a collection, default the config for
+ // a new collection to the collection we are bootstrapping
+ log.info("Setting config for collection:" + collection + " to " + defaultConfigName);
+
+ Properties sysProps = System.getProperties();
+ for (String sprop : System.getProperties().stringPropertyNames()) {
+ if (sprop.startsWith(ZkController.COLLECTION_PARAM_PREFIX)) {
+ collectionProps.put(sprop.substring(ZkController.COLLECTION_PARAM_PREFIX.length()), sysProps.getProperty(sprop));
+ }
+ }
+
+ // if the config name wasn't passed in, use the default
+ if (!collectionProps.containsKey(ZkController.CONFIGNAME_PROP))
+ collectionProps.put(ZkController.CONFIGNAME_PROP, defaultConfigName);
+
+ } else if (Boolean.getBoolean("bootstrap_conf")) {
+ // the conf name should should be the collection name of this core
+ collectionProps.put(ZkController.CONFIGNAME_PROP, collection);
+ } else {
+ getConfName(zkClient, collection, collectionPath, collectionProps);
+ }
+
+ collectionProps.remove(ZkStateReader.NUM_SHARDS_PROP); // we don't put numShards in the collections properties
+
+ ZkNodeProps zkProps = new ZkNodeProps(collectionProps);
+ zkClient.makePath(collectionPath, Utils.toJSON(zkProps), CreateMode.PERSISTENT, null, true);
+
+ } catch (KeeperException e) {
+ // it's okay if the node already exists
+ if (e.code() != KeeperException.Code.NODEEXISTS) {
+ throw e;
+ }
+ }
+ } else {
+ log.debug("Collection zkNode exists");
+ }
+
+ } catch (KeeperException e) {
+ // it's okay if another beats us creating the node
+ if (e.code() == KeeperException.Code.NODEEXISTS) {
+ return;
+ }
+ throw new SolrException(ErrorCode.SERVER_ERROR, "Error creating collection node in Zookeeper", e);
+ } catch (InterruptedException e) {
+ Thread.interrupted();
+ throw new SolrException(ErrorCode.SERVER_ERROR, "Error creating collection node in Zookeeper", e);
+ }
+
+ }
+
+ private static void getConfName(SolrZkClient zkClient, String collection, String collectionPath, Map<String,Object> collectionProps) throws KeeperException,
+ InterruptedException {
+ // check for configName
+ log.debug("Looking for collection configName");
+ if (collectionProps.containsKey("configName")) {
+ log.info("configName was passed as a param {}", collectionProps.get("configName"));
+ return;
+ }
+
+ List<String> configNames = null;
+ int retry = 1;
+ int retryLimt = 6;
+ for (; retry < retryLimt; retry++) {
+ if (zkClient.exists(collectionPath, true)) {
+ ZkNodeProps cProps = ZkNodeProps.load(zkClient.getData(collectionPath, null, null, true));
+ if (cProps.containsKey(ZkController.CONFIGNAME_PROP)) {
+ break;
+ }
+ }
+
+ // if there is only one conf, use that
+ try {
+ configNames = zkClient.getChildren(ZkConfigManager.CONFIGS_ZKNODE, null,
+ true);
+ } catch (NoNodeException e) {
+ // just keep trying
+ }
+ if (configNames != null && configNames.size() == 1) {
+ // no config set named, but there is only 1 - use it
+ log.info("Only one config set found in zk - using it:" + configNames.get(0));
+ collectionProps.put(ZkController.CONFIGNAME_PROP, configNames.get(0));
+ break;
+ }
+
+ if (configNames != null && configNames.contains(collection)) {
+ log.info(
+ "Could not find explicit collection configName, but found config name matching collection name - using that set.");
+ collectionProps.put(ZkController.CONFIGNAME_PROP, collection);
+ break;
+ }
+
+ log.info("Could not find collection configName - pausing for 3 seconds and trying again - try: " + retry);
+ Thread.sleep(3000);
+ }
+ if (retry == retryLimt) {
+ log.error("Could not find configName for collection " + collection);
+ throw new ZooKeeperException(
+ SolrException.ErrorCode.SERVER_ERROR,
+ "Could not find configName for collection " + collection + " found:" + configNames);
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java b/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java
index 183f177..b3cd585 100644
--- a/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java
+++ b/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java
@@ -125,17 +125,6 @@ class ShardLeaderElectionContextBase extends ElectionContext {
this.zkClient = zkStateReader.getZkClient();
this.shardId = shardId;
this.collection = collection;
-
- try {
- new ZkCmdExecutor(zkStateReader.getZkClient().getZkClientTimeout())
- .ensureExists(ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection,
- zkClient);
- } catch (KeeperException e) {
- throw new SolrException(ErrorCode.SERVER_ERROR, e);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new SolrException(ErrorCode.SERVER_ERROR, e);
- }
}
@Override
@@ -175,9 +164,16 @@ class ShardLeaderElectionContextBase extends ElectionContext {
void runLeaderProcess(boolean weAreReplacement, int pauseBeforeStartMs)
throws KeeperException, InterruptedException, IOException {
// register as leader - if an ephemeral is already there, wait to see if it goes away
+
+ if (!zkClient.exists(ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection, true)) {
+ log.info("Will not register as leader because collection appears to be gone.");
+ return;
+ }
+
String parent = new Path(leaderPath).getParent().toString();
ZkCmdExecutor zcmd = new ZkCmdExecutor(30000);
- zcmd.ensureExists(parent, zkClient);
+ // only if /collections/{collection} exists already do we succeed in creating this path
+ zcmd.ensureExists(parent, (byte[])null, CreateMode.PERSISTENT, zkClient, 2);
try {
RetryUtil.retryOnThrowable(NodeExistsException.class, 60000, 5000, () -> {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/cloud/LeaderElector.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/LeaderElector.java b/solr/core/src/java/org/apache/solr/cloud/LeaderElector.java
index 71fdcfd..aa8943d 100644
--- a/solr/core/src/java/org/apache/solr/cloud/LeaderElector.java
+++ b/solr/core/src/java/org/apache/solr/cloud/LeaderElector.java
@@ -360,8 +360,13 @@ public class LeaderElector {
public void setup(final ElectionContext context) throws InterruptedException,
KeeperException {
String electZKPath = context.electionPath + LeaderElector.ELECTION_NODE;
-
- zkCmdExecutor.ensureExists(electZKPath, zkClient);
+ if (context instanceof OverseerElectionContext) {
+ zkCmdExecutor.ensureExists(electZKPath, zkClient);
+ } else {
+ // we use 2 param so that replica won't create /collection/{collection} if it doesn't exist
+ zkCmdExecutor.ensureExists(electZKPath, (byte[])null, CreateMode.PERSISTENT, zkClient, 2);
+ }
+
this.context = context;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/cloud/ZkController.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.java
index c0a8d55..eba7067 100644
--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java
+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java
@@ -34,7 +34,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
@@ -1273,130 +1272,6 @@ public class ZkController {
zkClient.printLayoutToStdOut();
}
- public void createCollectionZkNode(CloudDescriptor cd) {
- String collection = cd.getCollectionName();
-
- log.debug("Check for collection zkNode:" + collection);
- String collectionPath = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection;
-
- try {
- if (!zkClient.exists(collectionPath, true)) {
- log.debug("Creating collection in ZooKeeper:" + collection);
-
- try {
- Map<String, Object> collectionProps = new HashMap<>();
-
- // TODO: if collection.configName isn't set, and there isn't already a conf in zk, just use that?
- String defaultConfigName = System.getProperty(COLLECTION_PARAM_PREFIX + CONFIGNAME_PROP, collection);
-
- // params passed in - currently only done via core admin (create core commmand).
- if (cd.getParams().size() > 0) {
- collectionProps.putAll(cd.getParams());
- // if the config name wasn't passed in, use the default
- if (!collectionProps.containsKey(CONFIGNAME_PROP)) {
- // TODO: getting the configName from the collectionPath should fail since we already know it doesn't exist?
- getConfName(collection, collectionPath, collectionProps);
- }
-
- } else if (System.getProperty("bootstrap_confdir") != null) {
- // if we are bootstrapping a collection, default the config for
- // a new collection to the collection we are bootstrapping
- log.info("Setting config for collection:" + collection + " to " + defaultConfigName);
-
- Properties sysProps = System.getProperties();
- for (String sprop : System.getProperties().stringPropertyNames()) {
- if (sprop.startsWith(COLLECTION_PARAM_PREFIX)) {
- collectionProps.put(sprop.substring(COLLECTION_PARAM_PREFIX.length()), sysProps.getProperty(sprop));
- }
- }
-
- // if the config name wasn't passed in, use the default
- if (!collectionProps.containsKey(CONFIGNAME_PROP))
- collectionProps.put(CONFIGNAME_PROP, defaultConfigName);
-
- } else if (Boolean.getBoolean("bootstrap_conf")) {
- // the conf name should should be the collection name of this core
- collectionProps.put(CONFIGNAME_PROP, cd.getCollectionName());
- } else {
- getConfName(collection, collectionPath, collectionProps);
- }
-
- collectionProps.remove(ZkStateReader.NUM_SHARDS_PROP); // we don't put numShards in the collections properties
-
- ZkNodeProps zkProps = new ZkNodeProps(collectionProps);
- zkClient.makePath(collectionPath, Utils.toJSON(zkProps), CreateMode.PERSISTENT, null, true);
-
- } catch (KeeperException e) {
- // it's okay if the node already exists
- if (e.code() != KeeperException.Code.NODEEXISTS) {
- throw e;
- }
- }
- } else {
- log.debug("Collection zkNode exists");
- }
-
- } catch (KeeperException e) {
- // it's okay if another beats us creating the node
- if (e.code() == KeeperException.Code.NODEEXISTS) {
- return;
- }
- throw new SolrException(ErrorCode.SERVER_ERROR, "Error creating collection node in Zookeeper", e);
- } catch (InterruptedException e) {
- Thread.interrupted();
- throw new SolrException(ErrorCode.SERVER_ERROR, "Error creating collection node in Zookeeper", e);
- }
-
- }
-
-
- private void getConfName(String collection, String collectionPath,
- Map<String, Object> collectionProps) throws KeeperException,
- InterruptedException {
- // check for configName
- log.debug("Looking for collection configName");
- List<String> configNames = null;
- int retry = 1;
- int retryLimt = 6;
- for (; retry < retryLimt; retry++) {
- if (zkClient.exists(collectionPath, true)) {
- ZkNodeProps cProps = ZkNodeProps.load(zkClient.getData(collectionPath, null, null, true));
- if (cProps.containsKey(CONFIGNAME_PROP)) {
- break;
- }
- }
-
- // if there is only one conf, use that
- try {
- configNames = zkClient.getChildren(ZkConfigManager.CONFIGS_ZKNODE, null,
- true);
- } catch (NoNodeException e) {
- // just keep trying
- }
- if (configNames != null && configNames.size() == 1) {
- // no config set named, but there is only 1 - use it
- log.info("Only one config set found in zk - using it:" + configNames.get(0));
- collectionProps.put(CONFIGNAME_PROP, configNames.get(0));
- break;
- }
-
- if (configNames != null && configNames.contains(collection)) {
- log.info("Could not find explicit collection configName, but found config name matching collection name - using that set.");
- collectionProps.put(CONFIGNAME_PROP, collection);
- break;
- }
-
- log.info("Could not find collection configName - pausing for 3 seconds and trying again - try: " + retry);
- Thread.sleep(3000);
- }
- if (retry == retryLimt) {
- log.error("Could not find configName for collection " + collection);
- throw new ZooKeeperException(
- SolrException.ErrorCode.SERVER_ERROR,
- "Could not find configName for collection " + collection + " found:" + configNames);
- }
- }
-
public ZkStateReader getZkStateReader() {
return zkStateReader;
}
@@ -2175,7 +2050,8 @@ public class ZkController {
} else {
String parentZNodePath = getLeaderInitiatedRecoveryZnodePath(collection, shardId);
try {
- zkClient.makePath(parentZNodePath, retryOnConnLoss);
+ // make sure we don't create /collections/{collection} if they do not exist with 2 param
+ zkClient.makePath(parentZNodePath, (byte[]) null, CreateMode.PERSISTENT, (Watcher) null, true, retryOnConnLoss, 2);
} catch (KeeperException.NodeExistsException nee) {
// if it exists, that's great!
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/cloud/ZkSolrResourceLoader.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkSolrResourceLoader.java b/solr/core/src/java/org/apache/solr/cloud/ZkSolrResourceLoader.java
index 209ca68..b4137b3 100644
--- a/solr/core/src/java/org/apache/solr/cloud/ZkSolrResourceLoader.java
+++ b/solr/core/src/java/org/apache/solr/cloud/ZkSolrResourceLoader.java
@@ -109,7 +109,7 @@ public class ZkSolrResourceLoader extends SolrResourceLoader {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Error opening " + file, e);
- } catch (KeeperException e) {
+ } catch (Exception e) {
throw new IOException("Error opening " + file, e);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/core/ConfigSetService.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/core/ConfigSetService.java b/solr/core/src/java/org/apache/solr/core/ConfigSetService.java
index 3f47f46..e4a135e 100644
--- a/solr/core/src/java/org/apache/solr/core/ConfigSetService.java
+++ b/solr/core/src/java/org/apache/solr/core/ConfigSetService.java
@@ -78,11 +78,10 @@ public abstract class ConfigSetService {
IndexSchema schema = createIndexSchema(dcore, solrConfig);
NamedList properties = createConfigSetProperties(dcore, coreLoader);
return new ConfigSet(configName(dcore), solrConfig, schema, properties);
- }
- catch (Exception e) {
+ } catch (Exception e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
- "Could not load conf for core " + dcore.getName() +
- ": " + e.getMessage(), e);
+ "Could not load conf for core " + dcore.getName() +
+ ": " + e.getMessage(), e);
}
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
index 01095a1..1915176 100644
--- a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
@@ -346,9 +346,11 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
try {
String path = ZkStateReader.CONFIGS_ZKNODE + "/" + SYSTEM_COLL + "/schema.xml";
byte[] data = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader().getResourceAsStream("SystemCollectionSchema.xml"));
+ assert data != null && data.length > 0;
cmdExecutor.ensureExists(path, data, CreateMode.PERSISTENT, zk);
path = ZkStateReader.CONFIGS_ZKNODE + "/" + SYSTEM_COLL + "/solrconfig.xml";
data = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader().getResourceAsStream("SystemCollectionSolrConfig.xml"));
+ assert data != null && data.length > 0;
cmdExecutor.ensureExists(path, data, CreateMode.PERSISTENT, zk);
} catch (IOException e) {
throw new SolrException(ErrorCode.SERVER_ERROR, e);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/test/org/apache/solr/cloud/LeaderElectionTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/LeaderElectionTest.java b/solr/core/src/test/org/apache/solr/cloud/LeaderElectionTest.java
index 8e1be10..2582872 100644
--- a/solr/core/src/test/org/apache/solr/cloud/LeaderElectionTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/LeaderElectionTest.java
@@ -80,6 +80,8 @@ public class LeaderElectionTest extends SolrTestCaseJ4 {
zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT);
zkStateReader = new ZkStateReader(zkClient);
seqToThread = Collections.synchronizedMap(new HashMap<Integer,Thread>());
+ zkClient.makePath("/collections/collection1", true);
+ zkClient.makePath("/collections/collection2", true);
}
class TestLeaderElectionContext extends ShardLeaderElectionContextBase {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionConfigSetProcessorTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionConfigSetProcessorTest.java b/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionConfigSetProcessorTest.java
index 239afa1..6a7906d 100644
--- a/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionConfigSetProcessorTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionConfigSetProcessorTest.java
@@ -44,6 +44,7 @@ import org.apache.solr.handler.component.ShardRequest;
import org.apache.solr.handler.component.ShardResponse;
import org.apache.solr.util.TimeOut;
import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.Watcher;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.After;
@@ -114,7 +115,6 @@ public class OverseerCollectionConfigSetProcessorTest extends SolrTestCaseJ4 {
zkStateReaderMock = createMock(ZkStateReader.class);
clusterStateMock = createMock(ClusterState.class);
solrZkClientMock = createMock(SolrZkClient.class);
-
}
@AfterClass
@@ -143,9 +143,7 @@ public class OverseerCollectionConfigSetProcessorTest extends SolrTestCaseJ4 {
reset(zkStateReaderMock);
reset(clusterStateMock);
reset(solrZkClientMock);
- underTest = new OverseerCollectionConfigSetProcessorToBeTested(zkStateReaderMock,
- "1234", shardHandlerFactoryMock, ADMIN_PATH, workQueueMock, runningMapMock,
- completedMapMock, failureMapMock);
+
zkMap.clear();
collectionsSet.clear();
}
@@ -157,12 +155,12 @@ public class OverseerCollectionConfigSetProcessorTest extends SolrTestCaseJ4 {
}
protected Set<String> commonMocks(int liveNodesCount) throws Exception {
-
shardHandlerFactoryMock.getShardHandler();
expectLastCall().andAnswer(() -> {
log.info("SHARDHANDLER");
return shardHandlerMock;
}).anyTimes();
+
workQueueMock.peekTopN(EasyMock.anyInt(), anyObject(Predicate.class), EasyMock.anyLong());
expectLastCall().andAnswer(() -> {
Object result;
@@ -203,12 +201,12 @@ public class OverseerCollectionConfigSetProcessorTest extends SolrTestCaseJ4 {
workQueueMock.poll();
expectLastCall().andAnswer(() -> queue.poll()).anyTimes();
-
- zkStateReaderMock.getClusterState();
- expectLastCall().andAnswer(() -> clusterStateMock).anyTimes();
zkStateReaderMock.getZkClient();
expectLastCall().andAnswer(() -> solrZkClientMock).anyTimes();
+
+ zkStateReaderMock.getClusterState();
+ expectLastCall().andAnswer(() -> clusterStateMock).anyTimes();
zkStateReaderMock.updateClusterState();
@@ -262,6 +260,18 @@ public class OverseerCollectionConfigSetProcessorTest extends SolrTestCaseJ4 {
String key = (String) getCurrentArguments()[0];
return key;
}).anyTimes();
+
+ solrZkClientMock.makePath(anyObject(String.class), anyObject(byte[].class), anyObject(CreateMode.class), anyObject(Watcher.class), anyBoolean());
+ expectLastCall().andAnswer(() -> {
+ String key = (String) getCurrentArguments()[0];
+ return key;
+ }).anyTimes();
+
+ solrZkClientMock.makePath(anyObject(String.class), anyObject(byte[].class), anyObject(CreateMode.class), anyObject(Watcher.class), anyBoolean(), anyBoolean(), anyInt());
+ expectLastCall().andAnswer(() -> {
+ String key = (String) getCurrentArguments()[0];
+ return key;
+ }).anyTimes();
solrZkClientMock.exists(anyObject(String.class),anyBoolean());
expectLastCall().andAnswer(() -> {
@@ -518,12 +528,17 @@ public class OverseerCollectionConfigSetProcessorTest extends SolrTestCaseJ4 {
replicationFactor);
}
- replay(workQueueMock);
replay(solrZkClientMock);
replay(zkStateReaderMock);
+ replay(workQueueMock);
replay(clusterStateMock);
replay(shardHandlerFactoryMock);
replay(shardHandlerMock);
+
+
+ underTest = new OverseerCollectionConfigSetProcessorToBeTested(zkStateReaderMock,
+ "1234", shardHandlerFactoryMock, ADMIN_PATH, workQueueMock, runningMapMock,
+ completedMapMock, failureMapMock);
log.info("clusterstate " + clusterStateMock.hashCode());
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/core/src/test/org/apache/solr/cloud/ZkSolrClientTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/ZkSolrClientTest.java b/solr/core/src/test/org/apache/solr/cloud/ZkSolrClientTest.java
index 39ef1b8..faa2ba7 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ZkSolrClientTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ZkSolrClientTest.java
@@ -26,6 +26,7 @@ import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkCmdExecutor;
import org.apache.solr.common.cloud.ZkOperation;
import org.apache.solr.util.AbstractSolrTestCase;
+import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
@@ -304,6 +305,59 @@ public class ZkSolrClientTest extends AbstractSolrTestCase {
}
}
+
+ public void testSkipPathPartsOnMakePath() throws Exception {
+ try (ZkConnection conn = new ZkConnection()) {
+ final SolrZkClient zkClient = conn.getClient();
+
+ zkClient.makePath("/test", true);
+
+ // should work
+ zkClient.makePath("/test/path/here", (byte[]) null, CreateMode.PERSISTENT, (Watcher) null, true, true, 1);
+
+ zkClient.clean("/");
+
+ // should not work
+ try {
+ zkClient.makePath("/test/path/here", (byte[]) null, CreateMode.PERSISTENT, (Watcher) null, true, true, 1);
+ fail("We should not be able to create this path");
+ } catch (Exception e) {
+
+ }
+
+ zkClient.clean("/");
+
+ ZkCmdExecutor zkCmdExecutor = new ZkCmdExecutor(30000);
+ try {
+ zkCmdExecutor.ensureExists("/collection/collection/leader", (byte[]) null, CreateMode.PERSISTENT, zkClient, 2);
+ fail("We should not be able to create this path");
+ } catch (Exception e) {
+
+ }
+
+ zkClient.makePath("/collection", true);
+
+ try {
+ zkCmdExecutor.ensureExists("/collections/collection/leader", (byte[]) null, CreateMode.PERSISTENT, zkClient, 2);
+ fail("We should not be able to create this path");
+ } catch (Exception e) {
+
+ }
+ zkClient.makePath("/collection/collection", true);
+
+ byte[] bytes = new byte[10];
+ zkCmdExecutor.ensureExists("/collection/collection", bytes, CreateMode.PERSISTENT, zkClient, 2);
+
+ byte[] returnedBytes = zkClient.getData("/collection/collection", null, null, true);
+
+ assertNull("We skipped 2 path parts, so data won't be written", returnedBytes);
+
+ zkClient.makePath("/collection/collection/leader", true);
+
+ zkCmdExecutor.ensureExists("/collection/collection/leader", (byte[]) null, CreateMode.PERSISTENT, zkClient, 2);
+
+ }
+ }
@Override
public void tearDown() throws Exception {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZkClient.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZkClient.java b/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZkClient.java
index 422d9e5..3f8deea 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZkClient.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZkClient.java
@@ -411,13 +411,13 @@ public class SolrZkClient implements Closeable {
public void makePath(String path, boolean failOnExists, boolean retryOnConnLoss) throws KeeperException,
InterruptedException {
- makePath(path, null, CreateMode.PERSISTENT, null, failOnExists, retryOnConnLoss);
+ makePath(path, null, CreateMode.PERSISTENT, null, failOnExists, retryOnConnLoss, 0);
}
public void makePath(String path, File file, boolean failOnExists, boolean retryOnConnLoss)
throws IOException, KeeperException, InterruptedException {
makePath(path, FileUtils.readFileToByteArray(file),
- CreateMode.PERSISTENT, null, failOnExists, retryOnConnLoss);
+ CreateMode.PERSISTENT, null, failOnExists, retryOnConnLoss, 0);
}
public void makePath(String path, File file, boolean retryOnConnLoss) throws IOException,
@@ -463,21 +463,35 @@ public class SolrZkClient implements Closeable {
*/
public void makePath(String path, byte[] data, CreateMode createMode,
Watcher watcher, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
- makePath(path, data, createMode, watcher, true, retryOnConnLoss);
+ makePath(path, data, createMode, watcher, true, retryOnConnLoss, 0);
+ }
+
+ /**
+ * Creates the path in ZooKeeper, creating each node as necessary.
+ *
+ * e.g. If <code>path=/solr/group/node</code> and none of the nodes, solr,
+ * group, node exist, each will be created.
+ *
+ * @param data to set on the last zkNode
+ */
+ public void makePath(String path, byte[] data, CreateMode createMode,
+ Watcher watcher, boolean failOnExists, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
+ makePath(path, data, createMode, watcher, failOnExists, retryOnConnLoss, 0);
}
-
/**
* Creates the path in ZooKeeper, creating each node as necessary.
*
* e.g. If <code>path=/solr/group/node</code> and none of the nodes, solr,
* group, node exist, each will be created.
+ *
+ * skipPathParts will force the call to fail if the first skipPathParts do not exist already.
*
* Note: retryOnConnLoss is only respected for the final node - nodes
* before that are always retried on connection loss.
*/
public void makePath(String path, byte[] data, CreateMode createMode,
- Watcher watcher, boolean failOnExists, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
+ Watcher watcher, boolean failOnExists, boolean retryOnConnLoss, int skipPathParts) throws KeeperException, InterruptedException {
log.debug("makePath: {}", path);
boolean retry = true;
@@ -487,9 +501,12 @@ public class SolrZkClient implements Closeable {
String[] paths = path.split("/");
StringBuilder sbPath = new StringBuilder();
for (int i = 0; i < paths.length; i++) {
- byte[] bytes = null;
String pathPiece = paths[i];
sbPath.append("/" + pathPiece);
+ if (i < skipPathParts) {
+ continue;
+ }
+ byte[] bytes = null;
final String currentPath = sbPath.toString();
Object exists = exists(currentPath, watcher, retryOnConnLoss);
if (exists == null || ((i == paths.length -1) && failOnExists)) {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/10552099/solr/solrj/src/java/org/apache/solr/common/cloud/ZkCmdExecutor.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkCmdExecutor.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkCmdExecutor.java
index 0f50f0a..c27f767 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkCmdExecutor.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkCmdExecutor.java
@@ -75,17 +75,26 @@ public class ZkCmdExecutor {
}
public void ensureExists(String path, final SolrZkClient zkClient) throws KeeperException, InterruptedException {
- ensureExists(path, null, CreateMode.PERSISTENT, zkClient);
+ ensureExists(path, null, CreateMode.PERSISTENT, zkClient, 0);
+ }
+
+
+ public void ensureExists(String path, final byte[] data, final SolrZkClient zkClient) throws KeeperException, InterruptedException {
+ ensureExists(path, data, CreateMode.PERSISTENT, zkClient, 0);
+ }
+
+ public void ensureExists(String path, final byte[] data, CreateMode createMode, final SolrZkClient zkClient) throws KeeperException, InterruptedException {
+ ensureExists(path, data, createMode, zkClient, 0);
}
public void ensureExists(final String path, final byte[] data,
- CreateMode createMode, final SolrZkClient zkClient) throws KeeperException, InterruptedException {
+ CreateMode createMode, final SolrZkClient zkClient, int skipPathParts) throws KeeperException, InterruptedException {
if (zkClient.exists(path, true)) {
return;
}
try {
- zkClient.makePath(path, data, createMode, true);
+ zkClient.makePath(path, data, createMode, null, true, true, skipPathParts);
} catch (NodeExistsException e) {
// it's okay if another beats us creating the node
}
[28/32] lucene-solr:jira/solr-5944: SOLR-1953: It may be possible for
temporary files to accumulate until the Solr process is shut down.
Posted by ho...@apache.org.
SOLR-1953: It may be possible for temporary files to accumulate until the Solr process is shut down.
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/e82399d0
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/e82399d0
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/e82399d0
Branch: refs/heads/jira/solr-5944
Commit: e82399d0677651ad4be1d8d2bdc4777b5d90b0fa
Parents: 22d9af4
Author: markrmiller <ma...@apache.org>
Authored: Mon Dec 12 11:10:58 2016 -0500
Committer: markrmiller <ma...@apache.org>
Committed: Wed Dec 14 11:16:50 2016 -0500
----------------------------------------------------------------------
solr/CHANGES.txt | 3 +
.../apache/solr/servlet/SolrDispatchFilter.java | 15 ++
.../apache/solr/servlet/SolrRequestParsers.java | 31 ++--
.../solr/util/SolrFileCleaningTracker.java | 147 +++++++++++++++++++
4 files changed, 182 insertions(+), 14 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e82399d0/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 41af0ff..946a04e 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -244,6 +244,9 @@ Bug Fixes
* SOLR-9823: CoreContainer incorrectly setting MDCLoggingContext for core (Jessica Cheng Mallet via Erick Erickson)
+* SOLR-1953: It may be possible for temporary files to accumulate until the Solr process is shut down.
+ (Karl Wright, Mark Miller)
+
Other Changes
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e82399d0/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
index 5a4cfb6..e8c4657 100644
--- a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
+++ b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
@@ -45,6 +45,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.commons.io.FileCleaningTracker;
import org.apache.commons.io.input.CloseShieldInputStream;
import org.apache.commons.io.output.CloseShieldOutputStream;
import org.apache.commons.lang.StringUtils;
@@ -62,6 +63,7 @@ import org.apache.solr.core.SolrXmlConfig;
import org.apache.solr.request.SolrRequestInfo;
import org.apache.solr.security.AuthenticationPlugin;
import org.apache.solr.security.PKIAuthenticationPlugin;
+import org.apache.solr.util.SolrFileCleaningTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -123,6 +125,8 @@ public class SolrDispatchFilter extends BaseSolrFilter {
{
log.trace("SolrDispatchFilter.init(): {}", this.getClass().getClassLoader());
+ SolrRequestParsers.fileCleaningTracker = new SolrFileCleaningTracker();
+
StartupLoggingUtils.checkLogDir();
logWelcomeBanner();
String muteConsole = System.getProperty(SOLR_LOG_MUTECONSOLE);
@@ -240,6 +244,17 @@ public class SolrDispatchFilter extends BaseSolrFilter {
@Override
public void destroy() {
+ try {
+ FileCleaningTracker fileCleaningTracker = SolrRequestParsers.fileCleaningTracker;
+ if (fileCleaningTracker != null) {
+ fileCleaningTracker.exitWhenFinished();
+ }
+ } catch (Exception e) {
+ log.warn("Exception closing FileCleaningTracker", e);
+ } finally {
+ SolrRequestParsers.fileCleaningTracker = null;
+ }
+
if (cores != null) {
try {
cores.shutdown();
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e82399d0/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.java b/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.java
index 9d7e7d9..968320e 100644
--- a/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.java
+++ b/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.java
@@ -42,6 +42,7 @@ import java.util.Map;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.commons.io.FileCleaningTracker;
import org.apache.commons.io.input.CloseShieldInputStream;
import org.apache.lucene.util.IOUtils;
import org.apache.solr.common.SolrException;
@@ -58,6 +59,7 @@ import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.util.RTimerTree;
+import org.apache.solr.util.SolrFileCleaningTracker;
import static org.apache.solr.common.params.CommonParams.PATH;
@@ -88,6 +90,8 @@ public class SolrRequestParsers
/** Default instance for e.g. admin requests. Limits to 2 MB uploads and does not allow remote streams. */
public static final SolrRequestParsers DEFAULT = new SolrRequestParsers();
+ public static volatile SolrFileCleaningTracker fileCleaningTracker;
+
/**
* Pass in an xml configuration. A null configuration will enable
* everything with maximum values.
@@ -532,31 +536,30 @@ public class SolrRequestParsers
/**
* Extract Multipart streams
*/
- static class MultipartRequestParser implements SolrRequestParser
- {
+ static class MultipartRequestParser implements SolrRequestParser {
private final int uploadLimitKB;
+ private DiskFileItemFactory factory = new DiskFileItemFactory();
- public MultipartRequestParser( int limit )
- {
+ public MultipartRequestParser(int limit) {
uploadLimitKB = limit;
+
+ // Set factory constraints
+ FileCleaningTracker fct = fileCleaningTracker;
+ if (fct != null) {
+ factory.setFileCleaningTracker(fileCleaningTracker);
+ }
+ // TODO - configure factory.setSizeThreshold(yourMaxMemorySize);
+ // TODO - configure factory.setRepository(yourTempDirectory);
}
@Override
- public SolrParams parseParamsAndFillStreams(
- final HttpServletRequest req, ArrayList<ContentStream> streams ) throws Exception
- {
+ public SolrParams parseParamsAndFillStreams(
+ final HttpServletRequest req, ArrayList<ContentStream> streams) throws Exception {
if( !ServletFileUpload.isMultipartContent(req) ) {
throw new SolrException( ErrorCode.BAD_REQUEST, "Not multipart content! "+req.getContentType() );
}
MultiMapSolrParams params = parseQueryString( req.getQueryString() );
-
- // Create a factory for disk-based file items
- DiskFileItemFactory factory = new DiskFileItemFactory();
-
- // Set factory constraints
- // TODO - configure factory.setSizeThreshold(yourMaxMemorySize);
- // TODO - configure factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/e82399d0/solr/core/src/java/org/apache/solr/util/SolrFileCleaningTracker.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/util/SolrFileCleaningTracker.java b/solr/core/src/java/org/apache/solr/util/SolrFileCleaningTracker.java
new file mode 100644
index 0000000..9c66f0f
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/util/SolrFileCleaningTracker.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.util;
+
+import java.io.File;
+import java.lang.ref.PhantomReference;
+import java.lang.ref.ReferenceQueue;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+
+import org.apache.commons.io.FileCleaningTracker;
+import org.apache.commons.io.FileDeleteStrategy;
+
+public class SolrFileCleaningTracker extends FileCleaningTracker {
+
+ ReferenceQueue<Object> q = new ReferenceQueue<>();
+
+ final Collection<Tracker> trackers = Collections.synchronizedSet(new HashSet<Tracker>());
+
+ final List<String> deleteFailures = Collections.synchronizedList(new ArrayList<String>());
+
+ volatile boolean exitWhenFinished = false;
+
+ Thread reaper;
+
+ public void track(final File file, final Object marker) {
+ track(file, marker, null);
+ }
+
+ public void track(final File file, final Object marker, final FileDeleteStrategy deleteStrategy) {
+ if (file == null) {
+ throw new NullPointerException("The file must not be null");
+ }
+ addTracker(file.getPath(), marker, deleteStrategy);
+ }
+
+ public void track(final String path, final Object marker) {
+ track(path, marker, null);
+ }
+
+ public void track(final String path, final Object marker, final FileDeleteStrategy deleteStrategy) {
+ if (path == null) {
+ throw new NullPointerException("The path must not be null");
+ }
+ addTracker(path, marker, deleteStrategy);
+ }
+
+ private synchronized void addTracker(final String path, final Object marker,
+ final FileDeleteStrategy deleteStrategy) {
+ if (exitWhenFinished) {
+ throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called");
+ }
+ if (reaper == null) {
+ reaper = new Reaper();
+ reaper.start();
+ }
+ trackers.add(new Tracker(path, deleteStrategy, marker, q));
+ }
+
+ public int getTrackCount() {
+ return trackers.size();
+ }
+
+ public List<String> getDeleteFailures() {
+ return deleteFailures;
+ }
+
+ public synchronized void exitWhenFinished() {
+ // synchronized block protects reaper
+ exitWhenFinished = true;
+ if (reaper != null) {
+ synchronized (reaper) {
+ reaper.interrupt();
+ try {
+ reaper.join();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+ }
+
+ private final class Reaper extends Thread {
+ Reaper() {
+ super("MultiPart Upload Tmp File Reaper");
+ setDaemon(true);
+ }
+
+ @Override
+ public void run() {
+ while (exitWhenFinished == false || trackers.size() > 0) {
+ try {
+ // Wait for a tracker to remove.
+ final Tracker tracker = (Tracker) q.remove(); // cannot return null
+ trackers.remove(tracker);
+ if (!tracker.delete()) {
+ deleteFailures.add(tracker.getPath());
+ }
+ tracker.clear();
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ break;
+ }
+ }
+ }
+ }
+
+ private static final class Tracker extends PhantomReference<Object> {
+
+ private final String path;
+
+ private final FileDeleteStrategy deleteStrategy;
+
+ Tracker(final String path, final FileDeleteStrategy deleteStrategy, final Object marker,
+ final ReferenceQueue<? super Object> queue) {
+ super(marker, queue);
+ this.path = path;
+ this.deleteStrategy = deleteStrategy == null ? FileDeleteStrategy.NORMAL : deleteStrategy;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public boolean delete() {
+ return deleteStrategy.deleteQuietly(new File(path));
+ }
+ }
+
+}
\ No newline at end of file
[17/32] lucene-solr:jira/solr-5944: SOLR-9843: Fix up
DocValuesNotIndexedTest failures. Debugging code
Posted by ho...@apache.org.
SOLR-9843: Fix up DocValuesNotIndexedTest failures. Debugging code
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/d75abe1a
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/d75abe1a
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/d75abe1a
Branch: refs/heads/jira/solr-5944
Commit: d75abe1a3022b5d596b7fca4c7e8623782010a88
Parents: 2b073a2
Author: Erick Erickson <er...@apache.org>
Authored: Sat Dec 10 14:03:15 2016 -0800
Committer: Erick Erickson <er...@apache.org>
Committed: Sat Dec 10 14:03:15 2016 -0800
----------------------------------------------------------------------
.../solr/cloud/DocValuesNotIndexedTest.java | 64 ++++++++++++--------
1 file changed, 39 insertions(+), 25 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d75abe1a/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java b/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java
index b8507b1..f5257f8 100644
--- a/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java
@@ -18,15 +18,15 @@
package org.apache.solr.cloud;
import java.io.IOException;
-import java.text.SimpleDateFormat;
+import java.lang.invoke.MethodHandles;
+import java.time.Instant;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule;
import org.apache.solr.client.solrj.SolrQuery;
@@ -50,11 +50,16 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.apache.lucene.util.LuceneTestCase.random;
import static org.apache.solr.client.solrj.request.schema.SchemaRequest.*;
public class DocValuesNotIndexedTest extends SolrCloudTestCase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
@Rule
public TestRule solrTestRules = RuleChain.outerRule(new SystemPropertiesRestoreRule());
@@ -79,7 +84,7 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
.process(cluster.getSolrClient());
fieldsToTestSingle =
- Collections.unmodifiableList(Stream.of(
+ Collections.unmodifiableList(Arrays.asList(
new FieldProps("intField", "int", 1),
new FieldProps("longField", "long", 1),
new FieldProps("doubleField", "double", 1),
@@ -87,10 +92,10 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
new FieldProps("dateField", "date", 1),
new FieldProps("stringField", "string", 1),
new FieldProps("boolField", "boolean", 1)
- ).collect(Collectors.toList()));
+ ));
fieldsToTestMulti =
- Collections.unmodifiableList(Stream.of(
+ Collections.unmodifiableList(Arrays.asList(
new FieldProps("intFieldMulti", "int", 5),
new FieldProps("longFieldMulti", "long", 5),
new FieldProps("doubleFieldMulti", "double", 5),
@@ -98,11 +103,11 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
new FieldProps("dateFieldMulti", "date", 5),
new FieldProps("stringFieldMulti", "string", 5),
new FieldProps("boolFieldMulti", "boolean", 2)
- ).collect(Collectors.toList()));
+ ));
// Fields to test for grouping and sorting with sortMinssingFirst/Last.
fieldsToTestGroupSortFirst =
- Collections.unmodifiableList(Stream.of(
+ Collections.unmodifiableList(Arrays.asList(
new FieldProps("intGSF", "int"),
new FieldProps("longGSF", "long"),
new FieldProps("doubleGSF", "double"),
@@ -110,10 +115,10 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
new FieldProps("dateGSF", "date"),
new FieldProps("stringGSF", "string"),
new FieldProps("boolGSF", "boolean")
- ).collect(Collectors.toList()));
+ ));
fieldsToTestGroupSortLast =
- Collections.unmodifiableList(Stream.of(
+ Collections.unmodifiableList(Arrays.asList(
new FieldProps("intGSL", "int"),
new FieldProps("longGSL", "long"),
new FieldProps("doubleGSL", "double"),
@@ -121,7 +126,7 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
new FieldProps("dateGSL", "date"),
new FieldProps("stringGSL", "string"),
new FieldProps("boolGSL", "boolean")
- ).collect(Collectors.toList()));
+ ));
List<Update> updateList = new ArrayList<>(fieldsToTestSingle.size() +
fieldsToTestMulti.size() + fieldsToTestGroupSortFirst.size() + fieldsToTestGroupSortLast.size() +
@@ -235,7 +240,7 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
new UpdateRequest()
.add(docs)
.commit(client, COLLECTION);
-
+
checkSortOrder(client, fieldsToTestGroupSortFirst, "asc", new String[]{"4", "2", "1", "3"}, new String[]{"4", "1", "2", "3"});
checkSortOrder(client, fieldsToTestGroupSortFirst, "desc", new String[]{"3", "1", "2", "4"}, new String[]{"2", "3", "1", "4"});
@@ -251,6 +256,10 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
solrQuery.addSort("id", SolrQuery.ORDER.asc);
final QueryResponse rsp = client.query(COLLECTION, solrQuery);
SolrDocumentList res = rsp.getResults();
+ //TODO remove after SOLR-9843
+ if (order.length != res.getNumFound()) {
+ log.error("(3) About to fail, response is: " + rsp.toString());
+ }
assertEquals("Should have exactly " + order.length + " documents returned", order.length, res.getNumFound());
String expected;
for (int idx = 0; idx < res.size(); ++idx) {
@@ -264,7 +273,7 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
@Test
public void testGroupingDocAbsent() throws IOException, SolrServerException {
- List<SolrInputDocument> docs = new ArrayList<>(3);
+ List<SolrInputDocument> docs = new ArrayList<>(4);
docs.add(makeGSDoc(2, fieldsToTestGroupSortFirst, null));
docs.add(makeGSDoc(1, fieldsToTestGroupSortFirst, null));
docs.add(makeGSDoc(3, fieldsToTestGroupSortFirst, null));
@@ -296,7 +305,11 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
if (prop.getName().startsWith("bool")) expected = 3; //true, false and null
List<Group> fieldCommandGroups = fieldCommand.getValues();
- assertEquals("Did not find the expected number of groups!", expected, fieldCommandGroups.size());
+ //TODO: remove me since this is excessive in the normal case, this is in for SOLR-9843
+ if (expected != fieldCommandGroups.size()) {
+ log.error("(1) About to fail assert, response is: " + rsp.toString());
+ }
+ assertEquals("Did not find the expected number of groups for field " + prop.getName(), expected, fieldCommandGroups.size());
}
}
@@ -316,7 +329,7 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
docs.add(doc);
if ((idx % 5) == 0) {
doc = new SolrInputDocument();
- doc.addField("id", idx + 100);
+ doc.addField("id", idx + 10_000);
docs.add(doc);
}
}
@@ -368,6 +381,8 @@ public class DocValuesNotIndexedTest extends SolrCloudTestCase {
break;
default:
+ //TODO remove me after SOLR-9843
+ log.error("(2) About to fail, response is: " + rsp.toString());
fail("Unexpected number of elements in the group for " + prop.getName() + ": " + grp.getResult().size());
}
}
@@ -450,8 +465,6 @@ class FieldProps {
private Object base;
private int counter = 0;
- static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
-
FieldProps(String name, String type, int expectedCount) {
this.name = name;
this.type = type;
@@ -460,22 +473,23 @@ class FieldProps {
}
void resetBase() {
if (name.startsWith("int")) {
- base = Math.abs(DocValuesNotIndexedTest.random().nextInt());
+ base = Math.abs(random().nextInt());
} else if (name.startsWith("long")) {
- base = Math.abs(DocValuesNotIndexedTest.random().nextLong());
+ base = Math.abs(random().nextLong());
} else if (name.startsWith("float")) {
- base = Math.abs(DocValuesNotIndexedTest.random().nextFloat());
+ base = Math.abs(random().nextFloat());
} else if (name.startsWith("double")) {
- base = Math.abs(DocValuesNotIndexedTest.random().nextDouble());
+ base = Math.abs(random().nextDouble());
} else if (name.startsWith("date")) {
- base = Math.abs(DocValuesNotIndexedTest.random().nextLong());
+ base = Math.abs(random().nextLong());
} else if (name.startsWith("bool")) {
base = true; // Must start with a known value since bools only have a two values....
} else if (name.startsWith("string")) {
- base = "base_string_" + DocValuesNotIndexedTest.random().nextInt(1_000_000) + "_";
+ base = "base_string_" + random().nextInt(1_000_000) + "_";
} else {
throw new RuntimeException("Should have found a prefix for the field before now!");
}
+ counter = 0;
}
FieldProps(String name, String type) {
@@ -496,7 +510,7 @@ class FieldProps {
public String getValue(boolean incrementCounter) {
if (incrementCounter) {
- counter += DocValuesNotIndexedTest.random().nextInt(10) + 100;
+ counter += random().nextInt(10) + 10_000;
}
if (name.startsWith("int")) {
return Integer.toString((int) base + counter);
@@ -511,7 +525,7 @@ class FieldProps {
return Double.toString((double) base + counter);
}
if (name.startsWith("date")) {
- return format.format(985_847_645 + (long) base + counter);
+ return Instant.ofEpochMilli(985_847_645 + (long) base + counter).toString();
}
if (name.startsWith("bool")) {
String ret = Boolean.toString((boolean) base);
[03/32] lucene-solr:jira/solr-5944: Merge remote-tracking branch
'origin/master'
Posted by ho...@apache.org.
Merge remote-tracking branch 'origin/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/10500c89
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/10500c89
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/10500c89
Branch: refs/heads/jira/solr-5944
Commit: 10500c894da171b6826e5101a981283ec434b9de
Parents: 3f6164c 8b98b15
Author: Noble Paul <no...@apache.org>
Authored: Wed Dec 7 18:42:39 2016 +0530
Committer: Noble Paul <no...@apache.org>
Committed: Wed Dec 7 18:42:39 2016 +0530
----------------------------------------------------------------------
lucene/CHANGES.txt | 4 +
.../uhighlight/MemoryIndexOffsetStrategy.java | 10 +-
.../uhighlight/MultiTermHighlighting.java | 37 +--
.../lucene/search/uhighlight/PhraseHelper.java | 158 ++++++++---
.../search/uhighlight/UnifiedHighlighter.java | 64 +++--
.../uhighlight/TestUnifiedHighlighter.java | 275 +++++++++++++++++++
.../TestUnifiedHighlighterExtensibility.java | 3 +-
solr/CHANGES.txt | 9 +
.../src/java/org/apache/solr/core/SolrCore.java | 8 -
.../solr/handler/admin/SystemInfoHandler.java | 51 +++-
.../solr/schema/ManagedIndexSchemaFactory.java | 12 +
.../org/apache/solr/schema/SchemaManager.java | 2 +-
.../ManagedSchemaRoundRobinCloudTest.java | 98 +++++++
.../solrj/impl/ConcurrentUpdateSolrClient.java | 16 +-
.../solr/client/solrj/SolrExampleTests.java | 7 +-
15 files changed, 649 insertions(+), 105 deletions(-)
----------------------------------------------------------------------
[20/32] lucene-solr:jira/solr-5944: SOLR-9844: Improve FieldCache
usage api response formatting and show total size information
Posted by ho...@apache.org.
SOLR-9844: Improve FieldCache usage api response formatting and show total size information
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/39ba1304
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/39ba1304
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/39ba1304
Branch: refs/heads/jira/solr-5944
Commit: 39ba13046bc48beaa139923d5f9fbf7d6fc192b2
Parents: 87d8b54
Author: Varun Thacker <va...@apache.org>
Authored: Mon Dec 12 12:38:14 2016 -0800
Committer: Varun Thacker <va...@apache.org>
Committed: Mon Dec 12 12:46:57 2016 -0800
----------------------------------------------------------------------
.../org/apache/lucene/index/SegmentCoreReaders.java | 8 ++++++++
solr/CHANGES.txt | 3 +++
.../org/apache/solr/search/SolrFieldCacheMBean.java | 2 ++
.../java/org/apache/solr/uninverting/FieldCache.java | 14 +++++---------
.../solr/uninverting/FieldCacheSanityChecker.java | 3 ++-
.../apache/solr/uninverting/UninvertingReader.java | 10 ++++++++++
.../apache/solr/search/TestSolrFieldCacheMBean.java | 1 +
7 files changed, 31 insertions(+), 10 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/39ba1304/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.java b/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.java
index e99c1ad..21ac4a1 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.java
@@ -56,6 +56,7 @@ final class SegmentCoreReaders {
final TermVectorsReader termVectorsReaderOrig;
final PointsReader pointsReader;
final Directory cfsReader;
+ final String segment;
/**
* fieldinfos for this core: means gen=-1.
* this is the exact fieldinfos these codec components saw at write.
@@ -98,6 +99,8 @@ final class SegmentCoreReaders {
cfsDir = dir;
}
+ segment = si.info.name;
+
coreFieldInfos = codec.fieldInfosFormat().read(cfsDir, si.info, "", context);
final SegmentReadState segmentReadState = new SegmentReadState(cfsDir, si.info, coreFieldInfos, context);
@@ -192,4 +195,9 @@ final class SegmentCoreReaders {
void removeCoreClosedListener(CoreClosedListener listener) {
coreClosedListeners.remove(listener);
}
+
+ @Override
+ public String toString() {
+ return "SegmentCoreReader(" + segment + ")";
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/39ba1304/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 78f7f55..37cccae 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -164,6 +164,9 @@ New Features
* SOLR-5043: New solr.dns.prevent.reverse.lookup system property that can be used to prevent long core
(re)load delays on systems with missconfigured hostname/DNS (hossman)
+* SOLR-9844: FieldCache information fetched via the mbeans handler or seen via the UI now displays the total size used.
+ The individual cache entries in the response are now formatted better as well. (Varun Thacker)
+
Optimizations
----------------------
* SOLR-9704: Facet Module / JSON Facet API: Optimize blockChildren facets that have
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/39ba1304/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java b/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java
index 62bc4fa..70781e9 100644
--- a/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java
+++ b/solr/core/src/java/org/apache/solr/search/SolrFieldCacheMBean.java
@@ -64,11 +64,13 @@ public class SolrFieldCacheMBean implements JmxAugmentedSolrInfoMBean {
if (listEntries) {
String[] entries = UninvertingReader.getUninvertedStats();
stats.add("entries_count", entries.length);
+ stats.add("total_size", UninvertingReader.getTotalSize());
for (int i = 0; i < entries.length; i++) {
stats.add("entry#" + i, entries[i]);
}
} else {
stats.add("entries_count", UninvertingReader.getUninvertedStatsSize());
+ stats.add("total_size", UninvertingReader.getTotalSize());
}
return stats;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/39ba1304/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java b/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java
index 32f5615..544800e 100644
--- a/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java
+++ b/solr/core/src/java/org/apache/solr/uninverting/FieldCache.java
@@ -384,7 +384,7 @@ public interface FieldCache {
return custom;
}
- public Object getValue() {
+ public Accountable getValue() {
return value;
}
@@ -399,15 +399,11 @@ public interface FieldCache {
@Override
public String toString() {
- StringBuilder b = new StringBuilder(250);
- b.append("'").append(getReaderKey()).append("'=>");
- b.append("'").append(getFieldName()).append("',");
- b.append(getCacheType()).append(",").append(getCustom());
- b.append("=>").append(getValue().getClass().getName()).append("#");
- b.append(System.identityHashCode(getValue()));
-
+ StringBuilder b = new StringBuilder(100);
+ b.append("segment='").append(getReaderKey().toString()).append("', ");
+ b.append("field='").append(getFieldName()).append("', ");
String s = getEstimatedSize();
- b.append(" (size =~ ").append(s).append(')');
+ b.append("size =~ ").append(s);
return b.toString();
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/39ba1304/solr/core/src/java/org/apache/solr/uninverting/FieldCacheSanityChecker.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/uninverting/FieldCacheSanityChecker.java b/solr/core/src/java/org/apache/solr/uninverting/FieldCacheSanityChecker.java
index ec398f2..3d874ce 100644
--- a/solr/core/src/java/org/apache/solr/uninverting/FieldCacheSanityChecker.java
+++ b/solr/core/src/java/org/apache/solr/uninverting/FieldCacheSanityChecker.java
@@ -27,6 +27,7 @@ import java.util.Set;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.store.AlreadyClosedException;
+import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.MapOfSets;
import org.apache.solr.uninverting.FieldCache.CacheEntry;
@@ -103,7 +104,7 @@ final class FieldCacheSanityChecker {
// iterate over all the cacheEntries to get the mappings we'll need
for (int i = 0; i < cacheEntries.length; i++) {
final CacheEntry item = cacheEntries[i];
- final Object val = item.getValue();
+ final Accountable val = item.getValue();
// It's OK to have dup entries, where one is eg
// float[] and the other is the Bits (from
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/39ba1304/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java b/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java
index 7825666..87fb7a6 100644
--- a/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java
+++ b/solr/core/src/java/org/apache/solr/uninverting/UninvertingReader.java
@@ -37,6 +37,7 @@ import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.SortedSetDocValues;
+import org.apache.lucene.util.RamUsageEstimator;
import org.apache.solr.uninverting.FieldCache.CacheEntry;
/**
@@ -386,4 +387,13 @@ public class UninvertingReader extends FilterLeafReader {
public static int getUninvertedStatsSize() {
return FieldCache.DEFAULT.getCacheEntries().length;
}
+
+ public static String getTotalSize() {
+ CacheEntry[] entries = FieldCache.DEFAULT.getCacheEntries();
+ long totalBytesUsed = 0;
+ for (int i = 0; i < entries.length; i++) {
+ totalBytesUsed += entries[i].getValue().ramBytesUsed();
+ }
+ return RamUsageEstimator.humanReadableUnits(totalBytesUsed);
+ }
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/39ba1304/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java b/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java
index 5343f73..a705e1e 100644
--- a/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java
+++ b/solr/core/src/test/org/apache/solr/search/TestSolrFieldCacheMBean.java
@@ -76,6 +76,7 @@ public class TestSolrFieldCacheMBean extends SolrTestCaseJ4 {
SolrFieldCacheMBean mbean = new SolrFieldCacheMBean();
NamedList stats = checkJmx ? mbean.getStatisticsForJmx() : mbean.getStatistics();
assert(new Integer(stats.get("entries_count").toString()) > 0);
+ assertNotNull(stats.get("total_size"));
assertNull(stats.get("entry#0"));
}
}
[15/32] lucene-solr:jira/solr-5944: don't create unnecessary lambda
Posted by ho...@apache.org.
don't create unnecessary lambda
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/7cffae3a
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/7cffae3a
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/7cffae3a
Branch: refs/heads/jira/solr-5944
Commit: 7cffae3a16f7d0c94a79a273a702c0013af7f5ac
Parents: 4efbde4
Author: Mike McCandless <mi...@apache.org>
Authored: Fri Dec 9 18:35:13 2016 -0500
Committer: Mike McCandless <mi...@apache.org>
Committed: Fri Dec 9 18:35:13 2016 -0500
----------------------------------------------------------------------
.../core/src/java/org/apache/lucene/index/IndexWriterConfig.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7cffae3a/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java b/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
index ce4f0a8..1e1e795 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
@@ -476,7 +476,7 @@ public final class IndexWriterConfig extends LiveIndexWriterConfig {
}
}
this.indexSort = sort;
- this.indexSortFields = Arrays.stream(sort.getSort()).map((s) -> s.getField()).collect(Collectors.toSet());
+ this.indexSortFields = Arrays.stream(sort.getSort()).map(SortField::getField).collect(Collectors.toSet());
return this;
}
[06/32] lucene-solr:jira/solr-5944: SOLR-8542: couple of tweaks
(Michael Nilsson, Diego Ceccarelli, Christine Poerschke)
Posted by ho...@apache.org.
SOLR-8542: couple of tweaks (Michael Nilsson, Diego Ceccarelli, Christine Poerschke)
* removed code triplication in ManagedModelStore
* LTRScoringQuery.java tweaks
* FeatureLogger.makeFeatureVector(...) can now safely be called repeatedly (though that doesn't happen at present)
* make Feature.FeatureWeight.extractTerms a no-op; (OriginalScore|SolrFeature)Weight now implement extractTerms
* LTRThreadModule javadocs and README.md tweaks
* add TestFieldValueFeature.testBooleanValue test; replace "T"/"F" magic string use in FieldValueFeature
* add TestOriginalScoreScorer test; add OriginalScoreScorer.freq() method
* in TestMultipleAdditiveTreesModel revive dead explain 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/bfc3690d
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/bfc3690d
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/bfc3690d
Branch: refs/heads/jira/solr-5944
Commit: bfc3690d5203cee20550450bac3771e5c2b85cbf
Parents: d2ed42b
Author: Christine Poerschke <cp...@apache.org>
Authored: Wed Dec 7 20:43:49 2016 +0000
Committer: Christine Poerschke <cp...@apache.org>
Committed: Wed Dec 7 20:46:42 2016 +0000
----------------------------------------------------------------------
solr/contrib/ltr/README.md | 6 +--
.../java/org/apache/solr/ltr/FeatureLogger.java | 10 ++--
.../org/apache/solr/ltr/LTRScoringQuery.java | 22 ++++-----
.../org/apache/solr/ltr/LTRThreadModule.java | 29 ++++++++++++
.../org/apache/solr/ltr/feature/Feature.java | 3 +-
.../solr/ltr/feature/FieldValueFeature.java | 18 +++++---
.../solr/ltr/feature/OriginalScoreFeature.java | 12 ++++-
.../apache/solr/ltr/feature/SolrFeature.java | 17 +++++--
.../ltr/store/rest/ManagedFeatureStore.java | 1 -
.../solr/ltr/store/rest/ManagedModelStore.java | 32 ++++++-------
.../test-files/solr/collection1/conf/schema.xml | 2 +
.../solr/ltr/feature/TestFieldValueFeature.java | 48 +++++++++++++++++---
.../ltr/feature/TestOriginalScoreScorer.java | 47 +++++++++++++++++++
.../model/TestMultipleAdditiveTreesModel.java | 44 +++++++++---------
.../java/org/apache/solr/schema/BoolField.java | 4 +-
15 files changed, 212 insertions(+), 83 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/README.md
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/README.md b/solr/contrib/ltr/README.md
index 88e2f67..2033ffc 100644
--- a/solr/contrib/ltr/README.md
+++ b/solr/contrib/ltr/README.md
@@ -390,17 +390,17 @@ About half the time for ranking is spent in the creation of weights for each fea
<!-- Query parser used to rerank top docs with a provided model -->
<queryParser name="ltr" class="org.apache.solr.ltr.search.LTRQParserPlugin">
<int name="threadModule.totalPoolThreads">10</int> <!-- Maximum threads to share for all requests -->
- <int name="threadModule.numThreadsPerRequest">5</int> <!-- Maximum threads to use for a single requests-->
+ <int name="threadModule.numThreadsPerRequest">5</int> <!-- Maximum threads to use for a single request -->
</queryParser>
<!-- Transformer for extracting features -->
<transformer name="features" class="org.apache.solr.ltr.response.transform.LTRFeatureLoggerTransformerFactory">
<int name="threadModule.totalPoolThreads">10</int> <!-- Maximum threads to share for all requests -->
- <int name="threadModule.numThreadsPerRequest">5</int> <!-- Maximum threads to use for a single requests-->
+ <int name="threadModule.numThreadsPerRequest">5</int> <!-- Maximum threads to use for a single request -->
</transformer>
</config>
```
-The threadModule.totalPoolThreads option limits the total number of threads to be used across all query instances at any given time. threadModule.numThreadsPerRequest limits the number of threads used to process a single query. In the above example, 10 threads will be used to services all queries and a maximum of 5 threads to service a single query. If the solr instances is expected to receive no more than one query at a time, it is best to set both these numbers to the same value. If multiple queries need to serviced simultaneously, the numbers can be adjusted based on the expected response times. If the value of threadModule.numThreadsPerRequest is higher, the reponse time for a single query will be improved upto a point. If multiple queries are serviced simultaneously, the threadModule.totalPoolThreads imposes a contention between the queries if (threadModule.numThreadsPerRequest*total parallel queries > threadModule.totalPoolThreads).
+The threadModule.totalPoolThreads option limits the total number of threads to be used across all query instances at any given time. threadModule.numThreadsPerRequest limits the number of threads used to process a single query. In the above example, 10 threads will be used to services all queries and a maximum of 5 threads to service a single query. If the solr instance is expected to receive no more than one query at a time, it is best to set both these numbers to the same value. If multiple queries need to be serviced simultaneously, the numbers can be adjusted based on the expected response times. If the value of threadModule.numThreadsPerRequest is higher, the response time for a single query will be improved upto a point. If multiple queries are serviced simultaneously, the threadModule.totalPoolThreads imposes a contention between the queries if (threadModule.numThreadsPerRequest*total parallel queries > threadModule.totalPoolThreads).
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/FeatureLogger.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/FeatureLogger.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/FeatureLogger.java
index a5afd05..9c10c2c 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/FeatureLogger.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/FeatureLogger.java
@@ -151,7 +151,6 @@ public abstract class FeatureLogger<FV_TYPE> {
}
public static class CSVFeatureLogger extends FeatureLogger<String> {
- StringBuilder sb = new StringBuilder(500);
char keyValueSep = ':';
char featureSep = ';';
@@ -171,6 +170,10 @@ public abstract class FeatureLogger<FV_TYPE> {
@Override
public String makeFeatureVector(LTRScoringQuery.FeatureInfo[] featuresInfo) {
+ // Allocate the buffer to a size based on the number of features instead of the
+ // default 16. You need space for the name, value, and two separators per feature,
+ // but not all the features are expected to fire, so this is just a naive estimate.
+ StringBuilder sb = new StringBuilder(featuresInfo.length * 3);
boolean isDense = featureFormat.equals(FeatureFormat.DENSE);
for (LTRScoringQuery.FeatureInfo featInfo:featuresInfo) {
if (featInfo.isUsed() || isDense){
@@ -181,9 +184,8 @@ public abstract class FeatureLogger<FV_TYPE> {
}
}
- final String features = (sb.length() > 0 ? sb.substring(0,
- sb.length() - 1) : "");
- sb.setLength(0);
+ final String features = (sb.length() > 0 ?
+ sb.substring(0, sb.length() - 1) : "");
return features;
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRScoringQuery.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRScoringQuery.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRScoringQuery.java
index 991c1ed..d60ebf5 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRScoringQuery.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRScoringQuery.java
@@ -205,10 +205,10 @@ public class LTRScoringQuery extends Query {
List<Feature.FeatureWeight > featureWeights = new ArrayList<>(features.size());
if (querySemaphore == null) {
- createWeights(searcher, needsScores, boost, featureWeights, features);
+ createWeights(searcher, needsScores, featureWeights, features);
}
else{
- createWeightsParallel(searcher, needsScores, boost, featureWeights, features);
+ createWeightsParallel(searcher, needsScores, featureWeights, features);
}
int i=0, j = 0;
if (this.extractAllFeatures) {
@@ -228,7 +228,7 @@ public class LTRScoringQuery extends Query {
return new ModelWeight(modelFeaturesWeights, extractedFeatureWeights, allFeatures.size());
}
- private void createWeights(IndexSearcher searcher, boolean needsScores, float boost,
+ private void createWeights(IndexSearcher searcher, boolean needsScores,
List<Feature.FeatureWeight > featureWeights, Collection<Feature> features) throws IOException {
final SolrQueryRequest req = getRequest();
// since the feature store is a linkedhashmap order is preserved
@@ -271,7 +271,7 @@ public class LTRScoringQuery extends Query {
}
} // end of call CreateWeightCallable
- private void createWeightsParallel(IndexSearcher searcher, boolean needsScores, float boost,
+ private void createWeightsParallel(IndexSearcher searcher, boolean needsScores,
List<Feature.FeatureWeight > featureWeights, Collection<Feature> features) throws RuntimeException {
final SolrQueryRequest req = getRequest();
@@ -401,8 +401,9 @@ public class LTRScoringQuery extends Query {
/**
* Goes through all the stored feature values, and calculates the normalized
* values for all the features that will be used for scoring.
+ * Then calculate and return the model's score.
*/
- private void makeNormalizedFeatures() {
+ private float makeNormalizedFeaturesAndScore() {
int pos = 0;
for (final Feature.FeatureWeight feature : modelFeatureWeights) {
final int featureId = feature.getIndex();
@@ -415,6 +416,7 @@ public class LTRScoringQuery extends Query {
pos++;
}
ltrScoringModel.normalizeFeaturesInPlace(modelFeatureValuesNormalized);
+ return ltrScoringModel.score(modelFeatureValuesNormalized);
}
@Override
@@ -491,8 +493,8 @@ public class LTRScoringQuery extends Query {
for (final Feature.FeatureWeight.FeatureScorer subSocer : featureScorers) {
subSocer.setDocInfo(docInfo);
}
- if (featureScorers.size() <= 1) { // TODO: Allow the use of dense
- // features in other cases
+ if (featureScorers.size() <= 1) {
+ // future enhancement: allow the use of dense features in other cases
featureTraversalScorer = new DenseModelScorer(weight, featureScorers);
} else {
featureTraversalScorer = new SparseModelScorer(weight, featureScorers);
@@ -570,8 +572,7 @@ public class LTRScoringQuery extends Query {
featuresInfo[featureId].setUsed(true);
}
}
- makeNormalizedFeatures();
- return ltrScoringModel.score(modelFeatureValuesNormalized);
+ return makeNormalizedFeaturesAndScore();
}
@Override
@@ -663,8 +664,7 @@ public class LTRScoringQuery extends Query {
}
}
}
- makeNormalizedFeatures();
- return ltrScoringModel.score(modelFeatureValuesNormalized);
+ return makeNormalizedFeaturesAndScore();
}
@Override
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRThreadModule.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRThreadModule.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRThreadModule.java
index 8e2563f..b8d0bda 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRThreadModule.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/LTRThreadModule.java
@@ -29,6 +29,35 @@ import org.apache.solr.util.DefaultSolrThreadFactory;
import org.apache.solr.util.SolrPluginUtils;
import org.apache.solr.util.plugin.NamedListInitializedPlugin;
+/**
+ * The LTRThreadModule is optionally used by the {@link org.apache.solr.ltr.search.LTRQParserPlugin} and
+ * {@link org.apache.solr.ltr.response.transform.LTRFeatureLoggerTransformerFactory LTRFeatureLoggerTransformerFactory}
+ * classes to parallelize the creation of {@link org.apache.solr.ltr.feature.Feature.FeatureWeight Feature.FeatureWeight}
+ * objects.
+ * <p>
+ * Example configuration:
+ * <pre>
+ <queryParser name="ltr" class="org.apache.solr.ltr.search.LTRQParserPlugin">
+ <int name="threadModule.totalPoolThreads">10</int>
+ <int name="threadModule.numThreadsPerRequest">5</int>
+ </queryParser>
+
+ <transformer name="features" class="org.apache.solr.ltr.response.transform.LTRFeatureLoggerTransformerFactory">
+ <int name="threadModule.totalPoolThreads">10</int>
+ <int name="threadModule.numThreadsPerRequest">5</int>
+ </transformer>
+</pre>
+ * If an individual solr instance is expected to receive no more than one query at a time, it is best
+ * to set <code>totalPoolThreads</code> and <code>numThreadsPerRequest</code> to the same value.
+ *
+ * If multiple queries need to be serviced simultaneously then <code>totalPoolThreads</code> and
+ * <code>numThreadsPerRequest</code> can be adjusted based on the expected response times.
+ *
+ * If the value of <code>numThreadsPerRequest</code> is higher, the response time for a single query
+ * will be improved up to a point. If multiple queries are serviced simultaneously, the value of
+ * <code>totalPoolThreads</code> imposes a contention between the queries if
+ * <code>(totalPoolThreads < numThreadsPerRequest * total parallel queries)</code>.
+ */
final public class LTRThreadModule implements NamedListInitializedPlugin {
public static LTRThreadModule getInstance(NamedList args) {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/Feature.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/Feature.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/Feature.java
index 228b964..48e8942 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/Feature.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/Feature.java
@@ -258,8 +258,7 @@ public abstract class Feature extends Query {
@Override
public void extractTerms(Set<Term> terms) {
- // needs to be implemented by query subclasses
- throw new UnsupportedOperationException();
+ // no-op
}
/**
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/FieldValueFeature.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/FieldValueFeature.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/FieldValueFeature.java
index 279adbc..5fcf144 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/FieldValueFeature.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/FieldValueFeature.java
@@ -29,6 +29,7 @@ import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.solr.request.SolrQueryRequest;
+import org.apache.solr.schema.BoolField;
/**
* This feature returns the value of a field in the current document
@@ -119,13 +120,16 @@ public class FieldValueFeature extends Feature {
return number.floatValue();
} else {
final String string = indexableField.stringValue();
- // boolean values in the index are encoded with the
- // chars T/F
- if (string.equals("T")) {
- return 1;
- }
- if (string.equals("F")) {
- return 0;
+ if (string.length() == 1) {
+ // boolean values in the index are encoded with the
+ // a single char contained in TRUE_TOKEN or FALSE_TOKEN
+ // (see BoolField)
+ if (string.charAt(0) == BoolField.TRUE_TOKEN[0]) {
+ return 1;
+ }
+ if (string.charAt(0) == BoolField.FALSE_TOKEN[0]) {
+ return 0;
+ }
}
}
} catch (final IOException e) {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/OriginalScoreFeature.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/OriginalScoreFeature.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/OriginalScoreFeature.java
index 125615c..549880b 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/OriginalScoreFeature.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/OriginalScoreFeature.java
@@ -19,8 +19,10 @@ package org.apache.solr.ltr.feature;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
+import java.util.Set;
import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.Term;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
@@ -76,7 +78,10 @@ public class OriginalScoreFeature extends Feature {
return "OriginalScoreFeature [query:" + originalQuery.toString() + "]";
}
-
+ @Override
+ public void extractTerms(Set<Term> terms) {
+ w.extractTerms(terms);
+ }
@Override
public FeatureScorer scorer(LeafReaderContext context) throws IOException {
@@ -103,6 +108,11 @@ public class OriginalScoreFeature extends Feature {
}
@Override
+ public int freq() throws IOException {
+ return originalScorer.freq();
+ }
+
+ @Override
public int docID() {
return originalScorer.docID();
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/SolrFeature.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/SolrFeature.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/SolrFeature.java
index cb7c1a0..13eb96f 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/SolrFeature.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/feature/SolrFeature.java
@@ -21,8 +21,10 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.Term;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.IndexSearcher;
@@ -123,9 +125,9 @@ public class SolrFeature extends Feature {
* Weight for a SolrFeature
**/
public class SolrFeatureWeight extends FeatureWeight {
- Weight solrQueryWeight;
- Query query;
- List<Query> queryAndFilters;
+ final private Weight solrQueryWeight;
+ final private Query query;
+ final private List<Query> queryAndFilters;
public SolrFeatureWeight(IndexSearcher searcher,
SolrQueryRequest request, Query originalQuery, Map<String,String[]> efi) throws IOException {
@@ -174,6 +176,8 @@ public class SolrFeature extends Feature {
if (query != null) {
queryAndFilters.add(query);
solrQueryWeight = searcher.createNormalizedWeight(query, true);
+ } else {
+ solrQueryWeight = null;
}
} catch (final SyntaxError e) {
throw new FeatureException("Failed to parse feature query.", e);
@@ -202,6 +206,13 @@ public class SolrFeature extends Feature {
}
@Override
+ public void extractTerms(Set<Term> terms) {
+ if (solrQueryWeight != null) {
+ solrQueryWeight.extractTerms(terms);
+ }
+ }
+
+ @Override
public FeatureScorer scorer(LeafReaderContext context) throws IOException {
Scorer solrScorer = null;
if (solrQueryWeight != null) {
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedFeatureStore.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedFeatureStore.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedFeatureStore.java
index beb217c..2c7bce5 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedFeatureStore.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedFeatureStore.java
@@ -57,7 +57,6 @@ public class ManagedFeatureStore extends ManagedResource implements ManagedResou
/** the feature store rest endpoint **/
public static final String REST_END_POINT = "/schema/feature-store";
- // TODO: reduce from public to package visibility (once tests no longer need public access)
/** name of the attribute containing the feature class **/
static final String CLASS_KEY = "class";
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedModelStore.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedModelStore.java b/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedModelStore.java
index 97aaa40..9c19b0a 100644
--- a/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedModelStore.java
+++ b/solr/contrib/ltr/src/java/org/apache/solr/ltr/store/rest/ManagedModelStore.java
@@ -61,7 +61,6 @@ public class ManagedModelStore extends ManagedResource implements ManagedResourc
/** the model store rest endpoint **/
public static final String REST_END_POINT = "/schema/model-store";
- // TODO: reduce from public to package visibility (once tests no longer need public access)
/**
* Managed model store: the name of the attribute containing all the models of
@@ -124,16 +123,20 @@ public class ManagedModelStore extends ManagedResource implements ManagedResourc
if ((managedData != null) && (managedData instanceof List)) {
final List<Map<String,Object>> up = (List<Map<String,Object>>) managedData;
for (final Map<String,Object> u : up) {
- try {
- final LTRScoringModel algo = fromLTRScoringModelMap(solrResourceLoader, u, managedFeatureStore);
- addModel(algo);
- } catch (final ModelException e) {
- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
- }
+ addModelFromMap(u);
}
}
}
+ private void addModelFromMap(Map<String,Object> modelMap) {
+ try {
+ final LTRScoringModel algo = fromLTRScoringModelMap(solrResourceLoader, modelMap, managedFeatureStore);
+ addModel(algo);
+ } catch (final ModelException e) {
+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
+ }
+ }
+
public synchronized void addModel(LTRScoringModel ltrScoringModel) throws ModelException {
try {
log.info("adding model {}", ltrScoringModel.getName());
@@ -146,26 +149,17 @@ public class ManagedModelStore extends ManagedResource implements ManagedResourc
@SuppressWarnings("unchecked")
@Override
protected Object applyUpdatesToManagedData(Object updates) {
+
if (updates instanceof List) {
final List<Map<String,Object>> up = (List<Map<String,Object>>) updates;
for (final Map<String,Object> u : up) {
- try {
- final LTRScoringModel algo = fromLTRScoringModelMap(solrResourceLoader, u, managedFeatureStore);
- addModel(algo);
- } catch (final ModelException e) {
- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
- }
+ addModelFromMap(u);
}
}
if (updates instanceof Map) {
final Map<String,Object> map = (Map<String,Object>) updates;
- try {
- final LTRScoringModel algo = fromLTRScoringModelMap(solrResourceLoader, map, managedFeatureStore);
- addModel(algo);
- } catch (final ModelException e) {
- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
- }
+ addModelFromMap(map);
}
return modelsAsManagedResources(store.getModels());
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/test-files/solr/collection1/conf/schema.xml
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/test-files/solr/collection1/conf/schema.xml b/solr/contrib/ltr/src/test-files/solr/collection1/conf/schema.xml
index 15cf140..0b958c0 100644
--- a/solr/contrib/ltr/src/test-files/solr/collection1/conf/schema.xml
+++ b/solr/contrib/ltr/src/test-files/solr/collection1/conf/schema.xml
@@ -24,6 +24,8 @@
<field name="keywords" type="text_general" indexed="true" stored="true" multiValued="true"/>
<field name="popularity" type="int" indexed="true" stored="true" />
<field name="normHits" type="float" indexed="true" stored="true" />
+ <field name="isTrendy" type="boolean" indexed="true" stored="true" />
+
<field name="text" type="text_general" indexed="true" stored="false" multiValued="true"/>
<field name="_version_" type="long" indexed="true" stored="true"/>
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestFieldValueFeature.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestFieldValueFeature.java b/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestFieldValueFeature.java
index af150c0..9574273 100644
--- a/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestFieldValueFeature.java
+++ b/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestFieldValueFeature.java
@@ -32,21 +32,21 @@ public class TestFieldValueFeature extends TestRerankBase {
setuptest("solrconfig-ltr.xml", "schema.xml");
assertU(adoc("id", "1", "title", "w1", "description", "w1", "popularity",
- "1"));
+ "1","isTrendy","true"));
assertU(adoc("id", "2", "title", "w2 2asd asdd didid", "description",
"w2 2asd asdd didid", "popularity", "2"));
assertU(adoc("id", "3", "title", "w3", "description", "w3", "popularity",
- "3"));
+ "3","isTrendy","true"));
assertU(adoc("id", "4", "title", "w4", "description", "w4", "popularity",
- "4"));
+ "4","isTrendy","false"));
assertU(adoc("id", "5", "title", "w5", "description", "w5", "popularity",
- "5"));
+ "5","isTrendy","true"));
assertU(adoc("id", "6", "title", "w1 w2", "description", "w1 w2",
- "popularity", "6"));
+ "popularity", "6","isTrendy","false"));
assertU(adoc("id", "7", "title", "w1 w2 w3 w4 w5", "description",
- "w1 w2 w3 w4 w5 w8", "popularity", "7"));
+ "w1 w2 w3 w4 w5 w8", "popularity", "7","isTrendy","true"));
assertU(adoc("id", "8", "title", "w1 w1 w1 w2 w2 w8", "description",
- "w1 w1 w1 w2 w2", "popularity", "8"));
+ "w1 w1 w1 w2 w2", "popularity", "8","isTrendy","false"));
// a document without the popularity field
assertU(adoc("id", "42", "title", "NO popularity", "description", "NO popularity"));
@@ -169,5 +169,39 @@ public class TestFieldValueFeature extends TestRerankBase {
}
+ @Test
+ public void testBooleanValue() throws Exception {
+ final String fstore = "test_boolean_store";
+ loadFeature("trendy", FieldValueFeature.class.getCanonicalName(), fstore,
+ "{\"field\":\"isTrendy\"}");
+
+ loadModel("trendy-model", LinearModel.class.getCanonicalName(),
+ new String[] {"trendy"}, fstore, "{\"weights\":{\"trendy\":1.0}}");
+
+ SolrQuery query = new SolrQuery();
+ query.setQuery("id:4");
+ query.add("rq", "{!ltr model=trendy-model reRankDocs=4}");
+ query.add("fl", "[fv]");
+ assertJQ("/query" + query.toQueryString(),
+ "/response/docs/[0]/=={'[fv]':'trendy:0.0'}");
+
+
+ query = new SolrQuery();
+ query.setQuery("id:5");
+ query.add("rq", "{!ltr model=trendy-model reRankDocs=4}");
+ query.add("fl", "[fv]");
+ assertJQ("/query" + query.toQueryString(),
+ "/response/docs/[0]/=={'[fv]':'trendy:1.0'}");
+
+ // check default value is false
+ query = new SolrQuery();
+ query.setQuery("id:2");
+ query.add("rq", "{!ltr model=trendy-model reRankDocs=4}");
+ query.add("fl", "[fv]");
+ assertJQ("/query" + query.toQueryString(),
+ "/response/docs/[0]/=={'[fv]':'trendy:0.0'}");
+
+ }
+
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestOriginalScoreScorer.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestOriginalScoreScorer.java b/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestOriginalScoreScorer.java
new file mode 100644
index 0000000..e85ebed
--- /dev/null
+++ b/solr/contrib/ltr/src/test/org/apache/solr/ltr/feature/TestOriginalScoreScorer.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.ltr.feature;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.util.LuceneTestCase;
+import org.junit.Test;
+
+public class TestOriginalScoreScorer extends LuceneTestCase {
+
+ @Test
+ public void testOverridesAbstractScorerMethods() {
+ final Class<?> ossClass = OriginalScoreFeature.OriginalScoreWeight.OriginalScoreScorer.class;
+ for (final Method scorerClassMethod : Scorer.class.getDeclaredMethods()) {
+ final int modifiers = scorerClassMethod.getModifiers();
+ if (!Modifier.isAbstract(modifiers)) continue;
+
+ try {
+ final Method ossClassMethod = ossClass.getDeclaredMethod(
+ scorerClassMethod.getName(),
+ scorerClassMethod.getParameterTypes());
+ assertEquals("getReturnType() difference",
+ scorerClassMethod.getReturnType(),
+ ossClassMethod.getReturnType());
+ } catch (NoSuchMethodException e) {
+ fail(ossClass + " needs to override '" + scorerClassMethod + "'");
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestMultipleAdditiveTreesModel.java
----------------------------------------------------------------------
diff --git a/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestMultipleAdditiveTreesModel.java b/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestMultipleAdditiveTreesModel.java
index 3748331..5604370 100644
--- a/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestMultipleAdditiveTreesModel.java
+++ b/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestMultipleAdditiveTreesModel.java
@@ -16,7 +16,7 @@
*/
package org.apache.solr.ltr.model;
-//import static org.junit.internal.matchers.StringContains.containsString;
+import static org.junit.internal.matchers.StringContains.containsString;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.ltr.TestRerankBase;
@@ -93,30 +93,28 @@ public class TestMultipleAdditiveTreesModel extends TestRerankBase {
// test out the explain feature, make sure it returns something
query.setParam("debugQuery", "on");
- String qryResult = JQ("/query" + query.toQueryString());
+ String qryResult = JQ("/query" + query.toQueryString());
qryResult = qryResult.replaceAll("\n", " ");
- // FIXME containsString doesn't exist.
- // assertThat(qryResult, containsString("\"debug\":{"));
- // qryResult = qryResult.substring(qryResult.indexOf("debug"));
- //
- // assertThat(qryResult, containsString("\"explain\":{"));
- // qryResult = qryResult.substring(qryResult.indexOf("explain"));
- //
- // assertThat(qryResult, containsString("multipleadditivetreesmodel"));
- // assertThat(qryResult,
- // containsString(MultipleAdditiveTreesModel.class.getCanonicalName()));
- //
- // assertThat(qryResult, containsString("-100.0 = tree 0"));
- // assertThat(qryResult, containsString("50.0 = tree 0"));
- // assertThat(qryResult, containsString("-20.0 = tree 1"));
- // assertThat(qryResult, containsString("'matchedTitle':1.0 > 0.5"));
- // assertThat(qryResult, containsString("'matchedTitle':0.0 <= 0.5"));
- //
- // assertThat(qryResult, containsString(" Go Right "));
- // assertThat(qryResult, containsString(" Go Left "));
- // assertThat(qryResult,
- // containsString("'this_feature_doesnt_exist' does not exist in FV"));
+
+ assertThat(qryResult, containsString("\"debug\":{"));
+ qryResult = qryResult.substring(qryResult.indexOf("debug"));
+
+ assertThat(qryResult, containsString("\"explain\":{"));
+ qryResult = qryResult.substring(qryResult.indexOf("explain"));
+
+ assertThat(qryResult, containsString("multipleadditivetreesmodel"));
+ assertThat(qryResult, containsString(MultipleAdditiveTreesModel.class.getCanonicalName()));
+
+ assertThat(qryResult, containsString("-100.0 = tree 0"));
+ assertThat(qryResult, containsString("50.0 = tree 0"));
+ assertThat(qryResult, containsString("-20.0 = tree 1"));
+ assertThat(qryResult, containsString("'matchedTitle':1.0 > 0.5"));
+ assertThat(qryResult, containsString("'matchedTitle':0.0 <= 0.5"));
+
+ assertThat(qryResult, containsString(" Go Right "));
+ assertThat(qryResult, containsString(" Go Left "));
+ assertThat(qryResult, containsString("'this_feature_doesnt_exist' does not exist in FV"));
}
@Test
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/bfc3690d/solr/core/src/java/org/apache/solr/schema/BoolField.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/schema/BoolField.java b/solr/core/src/java/org/apache/solr/schema/BoolField.java
index 210ea0b..1645ee6 100644
--- a/solr/core/src/java/org/apache/solr/schema/BoolField.java
+++ b/solr/core/src/java/org/apache/solr/schema/BoolField.java
@@ -71,8 +71,8 @@ public class BoolField extends PrimitiveFieldType {
}
// avoid instantiating every time...
- protected final static char[] TRUE_TOKEN = {'T'};
- protected final static char[] FALSE_TOKEN = {'F'};
+ public final static char[] TRUE_TOKEN = {'T'};
+ public final static char[] FALSE_TOKEN = {'F'};
////////////////////////////////////////////////////////////////////////
// TODO: look into creating my own queryParser that can more efficiently
[22/32] lucene-solr:jira/solr-5944: SOLR:9823: CoreContainer
incorrectly setting MDCLoggingContext for core
Posted by ho...@apache.org.
SOLR:9823: CoreContainer incorrectly setting MDCLoggingContext for 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/8c79ab26
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/8c79ab26
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/8c79ab26
Branch: refs/heads/jira/solr-5944
Commit: 8c79ab2649437c8c7ca275f6481c058c67626660
Parents: fecbbe0
Author: Erick <er...@apache.org>
Authored: Mon Dec 12 18:43:30 2016 -0800
Committer: Erick <er...@apache.org>
Committed: Mon Dec 12 18:43:30 2016 -0800
----------------------------------------------------------------------
solr/CHANGES.txt | 2 ++
solr/core/src/java/org/apache/solr/core/CoreContainer.java | 2 +-
2 files changed, 3 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8c79ab26/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index a8a3f97..41af0ff 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -242,6 +242,8 @@ Bug Fixes
* SOLR-9707: Don't forward DeleteByQuery requests to down replicas. (Jessica Cheng Mallet via Varun Thacker)
+* SOLR-9823: CoreContainer incorrectly setting MDCLoggingContext for core (Jessica Cheng Mallet via Erick Erickson)
+
Other Changes
----------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/8c79ab26/solr/core/src/java/org/apache/solr/core/CoreContainer.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/core/CoreContainer.java b/solr/core/src/java/org/apache/solr/core/CoreContainer.java
index ad4560e..7c38b81 100644
--- a/solr/core/src/java/org/apache/solr/core/CoreContainer.java
+++ b/solr/core/src/java/org/apache/solr/core/CoreContainer.java
@@ -857,7 +857,7 @@ public class CoreContainer {
SolrCore core = null;
try {
- MDCLoggingContext.setCore(core);
+ MDCLoggingContext.setCoreDescriptor(dcore);
SolrIdentifierValidator.validateCoreName(dcore.getName());
if (zkSys.getZkController() != null) {
zkSys.getZkController().preRegister(dcore);
[31/32] lucene-solr:jira/solr-5944: SOLR-8959: Refactored
TestSegmentSorting out of TestMiniSolrCloudCluster
Posted by ho...@apache.org.
SOLR-8959: Refactored TestSegmentSorting out of TestMiniSolrCloudCluster
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/6525bb56
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/6525bb56
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/6525bb56
Branch: refs/heads/jira/solr-5944
Commit: 6525bb56f027655e5a01f028fa373305c0d01caa
Parents: 5123743
Author: Chris Hostetter <ho...@apache.org>
Authored: Wed Dec 14 13:18:56 2016 -0700
Committer: Chris Hostetter <ho...@apache.org>
Committed: Wed Dec 14 13:18:56 2016 -0700
----------------------------------------------------------------------
solr/CHANGES.txt | 3 +
.../cloud/SegmentTerminateEarlyTestState.java | 12 +-
.../solr/cloud/TestMiniSolrCloudCluster.java | 50 -------
.../apache/solr/cloud/TestSegmentSorting.java | 133 +++++++++++++++++++
4 files changed, 145 insertions(+), 53 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6525bb56/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 5f0357b..73b0e9b 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -290,6 +290,9 @@ Other Changes
* SOLR-9846: OverseerAutoReplicaFailoverThread can take too long to stop and leak out of unit tests. (Mark Miller)
+* SOLR-8959: Refactored TestSegmentSorting out of TestMiniSolrCloudCluster (hossman)
+
+
================== 6.3.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/6525bb56/solr/core/src/test/org/apache/solr/cloud/SegmentTerminateEarlyTestState.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/SegmentTerminateEarlyTestState.java b/solr/core/src/test/org/apache/solr/cloud/SegmentTerminateEarlyTestState.java
index 199423b..b3df9e7 100644
--- a/solr/core/src/test/org/apache/solr/cloud/SegmentTerminateEarlyTestState.java
+++ b/solr/core/src/test/org/apache/solr/cloud/SegmentTerminateEarlyTestState.java
@@ -22,6 +22,7 @@ import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
+import java.util.Random;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
@@ -47,7 +48,12 @@ class SegmentTerminateEarlyTestState {
Integer maxTimestampMM = null;
int numDocs = 0;
+ final Random rand;
+ public SegmentTerminateEarlyTestState(Random rand) {
+ this.rand = rand;
+ }
+
void addDocuments(CloudSolrClient cloudSolrClient,
int numCommits, int numDocsPerCommit, boolean optimize) throws Exception {
for (int cc = 1; cc <= numCommits; ++cc) {
@@ -56,7 +62,7 @@ class SegmentTerminateEarlyTestState {
final Integer docKey = new Integer(numDocs);
SolrInputDocument doc = new SolrInputDocument();
doc.setField(keyField, ""+docKey);
- final int MM = TestMiniSolrCloudCluster.random().nextInt(60); // minutes
+ final int MM = rand.nextInt(60); // minutes
if (minTimestampMM == null || MM <= minTimestampMM.intValue()) {
if (minTimestampMM != null && MM < minTimestampMM.intValue()) {
minTimestampDocKeys.clear();
@@ -116,7 +122,7 @@ class SegmentTerminateEarlyTestState {
query.setFields(keyField, oddField, timestampField);
final int rowsWanted = 1;
query.setRows(rowsWanted);
- final Boolean shardsInfoWanted = (TestMiniSolrCloudCluster.random().nextBoolean() ? null : new Boolean(TestMiniSolrCloudCluster.random().nextBoolean()));
+ final Boolean shardsInfoWanted = (rand.nextBoolean() ? null : new Boolean(rand.nextBoolean()));
if (shardsInfoWanted != null) {
query.set(ShardParams.SHARDS_INFO, shardsInfoWanted.booleanValue());
}
@@ -163,7 +169,7 @@ class SegmentTerminateEarlyTestState {
query.setSort(timestampField, SolrQuery.ORDER.desc);
query.setFields(keyField, oddField, timestampField);
query.setRows(1);
- final Boolean shardsInfoWanted = (TestMiniSolrCloudCluster.random().nextBoolean() ? null : new Boolean(TestMiniSolrCloudCluster.random().nextBoolean()));
+ final Boolean shardsInfoWanted = (rand.nextBoolean() ? null : new Boolean(rand.nextBoolean()));
if (shardsInfoWanted != null) {
query.set(ShardParams.SHARDS_INFO, shardsInfoWanted.booleanValue());
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6525bb56/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudCluster.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudCluster.java b/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudCluster.java
index 97ecb67..de18875 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudCluster.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudCluster.java
@@ -16,7 +16,6 @@
*/
package org.apache.solr.cloud;
-import java.io.File;
import java.lang.invoke.MethodHandles;
import java.net.URL;
import java.util.ArrayList;
@@ -384,53 +383,4 @@ public class TestMiniSolrCloudCluster extends LuceneTestCase {
}
}
- @Test
- public void testSegmentTerminateEarly() throws Exception {
-
- final String collectionName = "testSegmentTerminateEarlyCollection";
-
- final SegmentTerminateEarlyTestState tstes = new SegmentTerminateEarlyTestState();
-
- File solrXml = new File(SolrTestCaseJ4.TEST_HOME(), "solr.xml");
- Builder jettyConfig = JettyConfig.builder();
- jettyConfig.waitForLoadingCoresToFinish(null);
- final MiniSolrCloudCluster miniCluster = createMiniSolrCloudCluster();
- final CloudSolrClient cloudSolrClient = miniCluster.getSolrClient();
- cloudSolrClient.setDefaultCollection(collectionName);
-
- try {
- // create collection
- {
- final String asyncId = (random().nextBoolean() ? null : "asyncId("+collectionName+".create)="+random().nextInt());
- final Map<String, String> collectionProperties = new HashMap<>();
- collectionProperties.put(CoreDescriptor.CORE_CONFIG, "solrconfig-sortingmergepolicyfactory.xml");
- createCollection(miniCluster, collectionName, null, asyncId, Boolean.TRUE, collectionProperties);
- }
-
- ZkStateReader zkStateReader = cloudSolrClient.getZkStateReader();
- AbstractDistribZkTestBase.waitForRecoveriesToFinish(collectionName, zkStateReader, true, true, 330);
-
- // add some documents, then optimize to get merged-sorted segments
- tstes.addDocuments(cloudSolrClient, 10, 10, true);
-
- // CommonParams.SEGMENT_TERMINATE_EARLY parameter intentionally absent
- tstes.queryTimestampDescending(cloudSolrClient);
-
- // add a few more documents, but don't optimize to have some not-merge-sorted segments
- tstes.addDocuments(cloudSolrClient, 2, 10, false);
-
- // CommonParams.SEGMENT_TERMINATE_EARLY parameter now present
- tstes.queryTimestampDescendingSegmentTerminateEarlyYes(cloudSolrClient);
- tstes.queryTimestampDescendingSegmentTerminateEarlyNo(cloudSolrClient);
-
- // CommonParams.SEGMENT_TERMINATE_EARLY parameter present but it won't be used
- tstes.queryTimestampDescendingSegmentTerminateEarlyYesGrouped(cloudSolrClient);
- tstes.queryTimestampAscendingSegmentTerminateEarlyYes(cloudSolrClient); // uses a sort order that is _not_ compatible with the merge sort order
-
- }
- finally {
- miniCluster.shutdown();
- }
- }
-
}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/6525bb56/solr/core/src/test/org/apache/solr/cloud/TestSegmentSorting.java
----------------------------------------------------------------------
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestSegmentSorting.java b/solr/core/src/test/org/apache/solr/cloud/TestSegmentSorting.java
new file mode 100644
index 0000000..016b63e
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/cloud/TestSegmentSorting.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.cloud;
+
+import java.lang.invoke.MethodHandles;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.lucene.index.TieredMergePolicy;
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.request.CollectionAdminRequest;
+import org.apache.solr.common.cloud.ZkStateReader;
+import org.apache.solr.core.CoreDescriptor;
+import org.apache.solr.index.TieredMergePolicyFactory;
+
+import org.junit.After;
+import org.junit.BeforeClass;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class TestSegmentSorting extends SolrCloudTestCase {
+
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final int NUM_SERVERS = 5;
+ private static final int NUM_SHARDS = 2;
+ private static final int REPLICATION_FACTOR = 2;
+
+ @BeforeClass
+ public static void setupCluster() throws Exception {
+ configureCluster(NUM_SERVERS).configure();
+ }
+
+ @After
+ public void ensureClusterEmpty() throws Exception {
+ cluster.deleteAllCollections();
+ cluster.getSolrClient().setDefaultCollection(null);
+ }
+
+ private void createCollection(MiniSolrCloudCluster miniCluster, String collectionName, String createNodeSet, String asyncId,
+ Boolean indexToPersist, Map<String,String> collectionProperties) throws Exception {
+ String configName = "solrCloudCollectionConfig";
+ miniCluster.uploadConfigSet(SolrTestCaseJ4.TEST_PATH().resolve("collection1").resolve("conf"), configName);
+
+ final boolean persistIndex = (indexToPersist != null ? indexToPersist.booleanValue() : random().nextBoolean());
+ if (collectionProperties == null) {
+ collectionProperties = new HashMap<>();
+ }
+ collectionProperties.putIfAbsent(CoreDescriptor.CORE_CONFIG, "solrconfig-tlog.xml");
+ collectionProperties.putIfAbsent("solr.tests.maxBufferedDocs", "100000");
+ collectionProperties.putIfAbsent("solr.tests.ramBufferSizeMB", "100");
+ // use non-test classes so RandomizedRunner isn't necessary
+ if (random().nextBoolean()) {
+ collectionProperties.putIfAbsent(SolrTestCaseJ4.SYSTEM_PROPERTY_SOLR_TESTS_MERGEPOLICY, TieredMergePolicy.class.getName());
+ collectionProperties.putIfAbsent(SolrTestCaseJ4.SYSTEM_PROPERTY_SOLR_TESTS_USEMERGEPOLICY, "true");
+ collectionProperties.putIfAbsent(SolrTestCaseJ4.SYSTEM_PROPERTY_SOLR_TESTS_USEMERGEPOLICYFACTORY, "false");
+ } else {
+ collectionProperties.putIfAbsent(SolrTestCaseJ4.SYSTEM_PROPERTY_SOLR_TESTS_MERGEPOLICYFACTORY, TieredMergePolicyFactory.class.getName());
+ collectionProperties.putIfAbsent(SolrTestCaseJ4.SYSTEM_PROPERTY_SOLR_TESTS_USEMERGEPOLICYFACTORY, "true");
+ collectionProperties.putIfAbsent(SolrTestCaseJ4.SYSTEM_PROPERTY_SOLR_TESTS_USEMERGEPOLICY, "false");
+ }
+ collectionProperties.putIfAbsent("solr.tests.mergeScheduler", "org.apache.lucene.index.ConcurrentMergeScheduler");
+ collectionProperties.putIfAbsent("solr.directoryFactory", (persistIndex ? "solr.StandardDirectoryFactory" : "solr.RAMDirectoryFactory"));
+
+ if (asyncId == null) {
+ CollectionAdminRequest.createCollection(collectionName, configName, NUM_SHARDS, REPLICATION_FACTOR)
+ .setCreateNodeSet(createNodeSet)
+ .setProperties(collectionProperties)
+ .process(miniCluster.getSolrClient());
+ }
+ else {
+ CollectionAdminRequest.createCollection(collectionName, configName, NUM_SHARDS, REPLICATION_FACTOR)
+ .setCreateNodeSet(createNodeSet)
+ .setProperties(collectionProperties)
+ .processAndWait(miniCluster.getSolrClient(), 30);
+ }
+ }
+
+
+ public void testSegmentTerminateEarly() throws Exception {
+
+ final String collectionName = "testSegmentTerminateEarlyCollection";
+
+ final SegmentTerminateEarlyTestState tstes = new SegmentTerminateEarlyTestState(random());
+
+ final CloudSolrClient cloudSolrClient = cluster.getSolrClient();
+ cloudSolrClient.setDefaultCollection(collectionName);
+
+ // create collection
+ {
+ final String asyncId = (random().nextBoolean() ? null : "asyncId("+collectionName+".create)="+random().nextInt());
+ final Map<String, String> collectionProperties = new HashMap<>();
+ collectionProperties.put(CoreDescriptor.CORE_CONFIG, "solrconfig-sortingmergepolicyfactory.xml");
+ createCollection(cluster, collectionName, null, asyncId, Boolean.TRUE, collectionProperties);
+ }
+
+ ZkStateReader zkStateReader = cloudSolrClient.getZkStateReader();
+ AbstractDistribZkTestBase.waitForRecoveriesToFinish(collectionName, zkStateReader, true, true, 330);
+
+ // add some documents, then optimize to get merged-sorted segments
+ tstes.addDocuments(cloudSolrClient, 10, 10, true);
+
+ // CommonParams.SEGMENT_TERMINATE_EARLY parameter intentionally absent
+ tstes.queryTimestampDescending(cloudSolrClient);
+
+ // add a few more documents, but don't optimize to have some not-merge-sorted segments
+ tstes.addDocuments(cloudSolrClient, 2, 10, false);
+
+ // CommonParams.SEGMENT_TERMINATE_EARLY parameter now present
+ tstes.queryTimestampDescendingSegmentTerminateEarlyYes(cloudSolrClient);
+ tstes.queryTimestampDescendingSegmentTerminateEarlyNo(cloudSolrClient);
+
+ // CommonParams.SEGMENT_TERMINATE_EARLY parameter present but it won't be used
+ tstes.queryTimestampDescendingSegmentTerminateEarlyYesGrouped(cloudSolrClient);
+ tstes.queryTimestampAscendingSegmentTerminateEarlyYes(cloudSolrClient); // uses a sort order that is _not_ compatible with the merge sort order
+
+ }
+}
[29/32] lucene-solr:jira/solr-5944: SOLR-9846:
OverseerAutoReplicaFailoverThread can take too long to stop and leak out of
unit tests.
Posted by ho...@apache.org.
SOLR-9846: OverseerAutoReplicaFailoverThread can take too long to stop and leak out of unit 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/7dec783b
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/7dec783b
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/7dec783b
Branch: refs/heads/jira/solr-5944
Commit: 7dec783b287ab554cc781622b4d6127e553fd2ae
Parents: e82399d
Author: markrmiller <ma...@apache.org>
Authored: Sun Dec 11 22:02:48 2016 -0500
Committer: markrmiller <ma...@apache.org>
Committed: Wed Dec 14 12:57:21 2016 -0500
----------------------------------------------------------------------
solr/CHANGES.txt | 2 ++
.../solr/cloud/OverseerAutoReplicaFailoverThread.java | 9 +++++++--
2 files changed, 9 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7dec783b/solr/CHANGES.txt
----------------------------------------------------------------------
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 946a04e..5f0357b 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -288,6 +288,8 @@ Other Changes
response (instead of a SolrException) and includes the remote error message as part of the exception message
(Tom�s Fern�ndez L�bbe)
+* SOLR-9846: OverseerAutoReplicaFailoverThread can take too long to stop and leak out of unit tests. (Mark Miller)
+
================== 6.3.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/7dec783b/solr/core/src/java/org/apache/solr/cloud/OverseerAutoReplicaFailoverThread.java
----------------------------------------------------------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerAutoReplicaFailoverThread.java b/solr/core/src/java/org/apache/solr/cloud/OverseerAutoReplicaFailoverThread.java
index 83679a5..10b4bf3 100644
--- a/solr/core/src/java/org/apache/solr/cloud/OverseerAutoReplicaFailoverThread.java
+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerAutoReplicaFailoverThread.java
@@ -89,6 +89,8 @@ public class OverseerAutoReplicaFailoverThread implements Runnable, Closeable {
private final int workLoopDelay;
private final int waitAfterExpiration;
+
+ private volatile Thread thread;
public OverseerAutoReplicaFailoverThread(CloudConfig config, ZkStateReader zkStateReader,
UpdateShardHandler updateShardHandler) {
@@ -118,7 +120,7 @@ public class OverseerAutoReplicaFailoverThread implements Runnable, Closeable {
@Override
public void run() {
-
+ this.thread = Thread.currentThread();
while (!this.isClosed) {
// work loop
log.debug("do " + this.getClass().getSimpleName() + " work loop");
@@ -136,7 +138,6 @@ public class OverseerAutoReplicaFailoverThread implements Runnable, Closeable {
try {
Thread.sleep(workLoopDelay);
} catch (InterruptedException e) {
- Thread.currentThread().interrupt();
return;
}
}
@@ -480,6 +481,10 @@ public class OverseerAutoReplicaFailoverThread implements Runnable, Closeable {
@Override
public void close() {
isClosed = true;
+ Thread lThread = thread;
+ if (lThread != null) {
+ lThread.interrupt();
+ }
}
public boolean isClosed() {
[26/32] lucene-solr:jira/solr-5944: LUCENE-7590: fix typo in method
parameter
Posted by ho...@apache.org.
LUCENE-7590: fix typo in method 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/85582dab
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/85582dab
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/85582dab
Branch: refs/heads/jira/solr-5944
Commit: 85582dabe4372085e1af5d01ebbfcfd0303b9f12
Parents: 770f1eb
Author: Shai Erera <sh...@apache.org>
Authored: Wed Dec 14 13:28:02 2016 +0200
Committer: Shai Erera <sh...@apache.org>
Committed: Wed Dec 14 13:28:02 2016 +0200
----------------------------------------------------------------------
.../misc/src/java/org/apache/lucene/search/DocValuesStats.java | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/85582dab/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
----------------------------------------------------------------------
diff --git a/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java b/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
index fad9f97..38158cf 100644
--- a/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
+++ b/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
@@ -51,7 +51,7 @@ public abstract class DocValuesStats<T> {
* Initializes this object with the given reader context. Returns whether stats can be computed for this segment (i.e.
* it does have the requested DocValues field).
*/
- protected abstract boolean init(LeafReaderContext contxt) throws IOException;
+ protected abstract boolean init(LeafReaderContext context) throws IOException;
/** Returns whether the given document has a value for the requested DocValues field. */
protected abstract boolean hasValue(int doc) throws IOException;
@@ -106,8 +106,8 @@ public abstract class DocValuesStats<T> {
}
@Override
- protected final boolean init(LeafReaderContext contxt) throws IOException {
- ndv = contxt.reader().getNumericDocValues(field);
+ protected final boolean init(LeafReaderContext context) throws IOException {
+ ndv = context.reader().getNumericDocValues(field);
return ndv != null;
}
[25/32] lucene-solr:jira/solr-5944: Fix
LeafReader.getNumericDocValues javadoc
Posted by ho...@apache.org.
Fix LeafReader.getNumericDocValues javadoc
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/770f1eb8
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/770f1eb8
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/770f1eb8
Branch: refs/heads/jira/solr-5944
Commit: 770f1eb8ad6af5cce55d1bdf52f1288216c9691f
Parents: ad7152a
Author: Shai Erera <sh...@apache.org>
Authored: Wed Dec 14 13:07:19 2016 +0200
Committer: Shai Erera <sh...@apache.org>
Committed: Wed Dec 14 13:07:19 2016 +0200
----------------------------------------------------------------------
lucene/core/src/java/org/apache/lucene/index/LeafReader.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/770f1eb8/lucene/core/src/java/org/apache/lucene/index/LeafReader.java
----------------------------------------------------------------------
diff --git a/lucene/core/src/java/org/apache/lucene/index/LeafReader.java b/lucene/core/src/java/org/apache/lucene/index/LeafReader.java
index acdd0d8..73394f2 100644
--- a/lucene/core/src/java/org/apache/lucene/index/LeafReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/LeafReader.java
@@ -242,7 +242,7 @@ public abstract class LeafReader extends IndexReader {
/** Returns {@link NumericDocValues} for this field, or
* null if no numeric doc values were indexed for
* this field. The returned instance should only be
- * used by a single thread. This will never return null. */
+ * used by a single thread. */
public abstract NumericDocValues getNumericDocValues(String field) throws IOException;
/** Returns {@link BinaryDocValues} for this field, or
[05/32] lucene-solr:jira/solr-5944: removed two unused imports in
TestPlainTextEntityProcessor.java
Posted by ho...@apache.org.
removed two unused imports in TestPlainTextEntityProcessor.java
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/d2ed42b8
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/d2ed42b8
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/d2ed42b8
Branch: refs/heads/jira/solr-5944
Commit: d2ed42b847b1114fe3d0befc788fba55255d4ee2
Parents: ca5e736
Author: Christine Poerschke <cp...@apache.org>
Authored: Wed Dec 7 18:39:04 2016 +0000
Committer: Christine Poerschke <cp...@apache.org>
Committed: Wed Dec 7 18:39:04 2016 +0000
----------------------------------------------------------------------
.../solr/handler/dataimport/TestPlainTextEntityProcessor.java | 2 --
1 file changed, 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d2ed42b8/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java
index a286d84..2385438 100644
--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java
+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java
@@ -21,10 +21,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
-import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.SQLException;
-import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
[18/32] lucene-solr:jira/solr-5944: Add .pydevproject to .gitignore
Posted by ho...@apache.org.
Add .pydevproject to .gitignore
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/25c7855b
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/25c7855b
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/25c7855b
Branch: refs/heads/jira/solr-5944
Commit: 25c7855bbae4eaa8700e72d094442811f0e8e1d9
Parents: d75abe1
Author: Shai Erera <sh...@apache.org>
Authored: Sun Dec 11 13:08:33 2016 +0200
Committer: Shai Erera <sh...@apache.org>
Committed: Sun Dec 11 13:08:33 2016 +0200
----------------------------------------------------------------------
.gitignore | 1 +
1 file changed, 1 insertion(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/25c7855b/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index 8091ecd..625cfa9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,6 +25,7 @@ parent.iml
**/pom.xml
/nbproject
/nb-build
+.pydevproject
/solr/package
[02/32] lucene-solr:jira/solr-5944: added an extra testcase
Posted by ho...@apache.org.
added an extra testcase
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/3f6164c7
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/3f6164c7
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/3f6164c7
Branch: refs/heads/jira/solr-5944
Commit: 3f6164c76e2fc581abe4408066e08cf9fc817260
Parents: bd8b191
Author: Noble Paul <no...@apache.org>
Authored: Wed Dec 7 18:42:07 2016 +0530
Committer: Noble Paul <no...@apache.org>
Committed: Wed Dec 7 18:42:07 2016 +0530
----------------------------------------------------------------------
.../TestPlainTextEntityProcessor.java | 108 +++++++++++++++++++
1 file changed, 108 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/3f6164c7/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java
index 82b757e..a286d84 100644
--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java
+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java
@@ -16,12 +16,23 @@
*/
package org.apache.solr.handler.dataimport;
+import java.io.ByteArrayInputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.sql.Blob;
+import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.Properties;
+import org.apache.solr.common.util.Utils;
import org.junit.Test;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
/**
* Test for PlainTextEntityProcessor
*
@@ -42,6 +53,103 @@ public class TestPlainTextEntityProcessor extends AbstractDataImportHandlerTestC
assertEquals(DS.s, sw.docs.get(0).getFieldValue("x"));
}
+ static class BlobImpl implements Blob{
+ private final byte[] bytes;
+
+ BlobImpl(byte[] bytes) {
+ this.bytes = bytes;
+ }
+
+ @Override
+ public long length() throws SQLException {
+ return 0;
+ }
+
+ @Override
+ public byte[] getBytes(long pos, int length) throws SQLException {
+ return bytes;
+ }
+
+ @Override
+ public InputStream getBinaryStream() throws SQLException {
+ return new ByteArrayInputStream(bytes);
+ }
+
+ @Override
+ public long position(byte[] pattern, long start) throws SQLException {
+ return 0;
+ }
+
+ @Override
+ public long position(Blob pattern, long start) throws SQLException {
+ return 0;
+ }
+
+ @Override
+ public int setBytes(long pos, byte[] bytes) throws SQLException {
+ return 0;
+ }
+
+ @Override
+ public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException {
+ return 0;
+ }
+
+ @Override
+ public OutputStream setBinaryStream(long pos) throws SQLException {
+ return null;
+ }
+
+ @Override
+ public void truncate(long len) throws SQLException {
+
+ }
+
+ @Override
+ public void free() throws SQLException {
+
+ }
+
+ @Override
+ public InputStream getBinaryStream(long pos, long length) throws SQLException {
+ return new ByteArrayInputStream(bytes);
+ }
+ }
+
+ @Test
+ public void testSimple2() throws IOException {
+ DataImporter di = new DataImporter();
+ MockDataSource.setIterator("select id, name, blob_field from lw_table4", Collections.singletonList(Utils.makeMap("blob_field",new BlobImpl(DS.s.getBytes(UTF_8)) ) ).iterator());
+
+ String dc =
+
+ " <dataConfig>" +
+ "<dataSource name=\"ds1\" type=\"MockDataSource\"/>\n" +
+ " <!-- dataSource for FieldReaderDataSource -->\n" +
+ " <dataSource dataField=\"root.blob_field\" name=\"fr\" type=\"FieldReaderDataSource\"/>\n" +
+ "\n" +
+ " <document name=\"items\">\n" +
+ " <entity dataSource=\"ds1\" name=\"root\" pk=\"id\" query=\"select id, name, blob_field from lw_table4\" transformer=\"TemplateTransformer\">\n" +
+ " <field column=\"id\" name=\"id\"/>\n" +
+ "\n" +
+ " <entity dataField=\"root.blob_field\" dataSource=\"fr\" format=\"text\" name=\"n1\" processor=\"PlainTextEntityProcessor\" url=\"blob_field\">\n" +
+ " <field column=\"plainText\" name=\"plainText\"/>\n" +
+ " </entity>\n" +
+ "\n" +
+ " </entity>\n" +
+ " </document>\n" +
+ "</dataConfig>";
+ System.out.println(dc);
+ di.loadAndInit(dc);
+ redirectTempProperties(di);
+
+ TestDocBuilder.SolrWriterImpl sw = new TestDocBuilder.SolrWriterImpl();
+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);
+ di.runCmd(rp, sw);
+ assertEquals(DS.s, sw.docs.get(0).getFieldValue("plainText"));
+ }
+
+
public static class DS extends DataSource {
static String s = "hello world";
[27/32] lucene-solr:jira/solr-5944: Rename constructor parameter name
Posted by ho...@apache.org.
Rename constructor parameter name
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/22d9af41
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/22d9af41
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/22d9af41
Branch: refs/heads/jira/solr-5944
Commit: 22d9af41a435feaa3307880b7c7ed4f5860faa21
Parents: 85582da
Author: Shai Erera <sh...@apache.org>
Authored: Wed Dec 14 13:49:42 2016 +0200
Committer: Shai Erera <sh...@apache.org>
Committed: Wed Dec 14 13:49:42 2016 +0200
----------------------------------------------------------------------
.../src/java/org/apache/lucene/search/DocValuesStats.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/22d9af41/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
----------------------------------------------------------------------
diff --git a/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java b/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
index 38158cf..998bef4 100644
--- a/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
+++ b/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
@@ -125,8 +125,8 @@ public abstract class DocValuesStats<T> {
/** Holds DocValues statistics for a numeric field storing {@code long} values. */
public static final class LongDocValuesStats extends NumericDocValuesStats<Long> {
- public LongDocValuesStats(String description) {
- super(description, Long.MAX_VALUE, Long.MIN_VALUE);
+ public LongDocValuesStats(String field) {
+ super(field, Long.MAX_VALUE, Long.MIN_VALUE);
}
@Override
@@ -145,8 +145,8 @@ public abstract class DocValuesStats<T> {
/** Holds DocValues statistics for a numeric field storing {@code double} values. */
public static final class DoubleDocValuesStats extends NumericDocValuesStats<Double> {
- public DoubleDocValuesStats(String description) {
- super(description, Double.MAX_VALUE, Double.MIN_VALUE);
+ public DoubleDocValuesStats(String field) {
+ super(field, Double.MAX_VALUE, Double.MIN_VALUE);
}
@Override
[23/32] lucene-solr:jira/solr-5944: fix RangeFieldQuery.scorer to
return null if no docs in a segment indexed the field
Posted by ho...@apache.org.
fix RangeFieldQuery.scorer to return null if no docs in a segment indexed the 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/9aa5b734
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/9aa5b734
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/9aa5b734
Branch: refs/heads/jira/solr-5944
Commit: 9aa5b734c38ed0b9327577bd2b1413d448230eab
Parents: 8c79ab2
Author: Nicholas Knize <nk...@gmail.com>
Authored: Tue Dec 13 15:07:06 2016 -0600
Committer: Nicholas Knize <nk...@gmail.com>
Committed: Tue Dec 13 15:07:06 2016 -0600
----------------------------------------------------------------------
.../src/java/org/apache/lucene/document/RangeFieldQuery.java | 1 +
.../test/org/apache/lucene/search/BaseRangeFieldQueryTestCase.java | 2 +-
2 files changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9aa5b734/lucene/sandbox/src/java/org/apache/lucene/document/RangeFieldQuery.java
----------------------------------------------------------------------
diff --git a/lucene/sandbox/src/java/org/apache/lucene/document/RangeFieldQuery.java b/lucene/sandbox/src/java/org/apache/lucene/document/RangeFieldQuery.java
index 7ebdec4..5249191 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/document/RangeFieldQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/document/RangeFieldQuery.java
@@ -165,6 +165,7 @@ abstract class RangeFieldQuery extends Query {
FieldInfo fieldInfo = reader.getFieldInfos().fieldInfo(field);
if (fieldInfo == null) {
// no docs in this segment indexed this field
+ return null;
}
checkFieldInfo(fieldInfo);
boolean allDocsMatch = true;
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/9aa5b734/lucene/sandbox/src/test/org/apache/lucene/search/BaseRangeFieldQueryTestCase.java
----------------------------------------------------------------------
diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/BaseRangeFieldQueryTestCase.java b/lucene/sandbox/src/test/org/apache/lucene/search/BaseRangeFieldQueryTestCase.java
index ff61ff6..ceafd53 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/search/BaseRangeFieldQueryTestCase.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/search/BaseRangeFieldQueryTestCase.java
@@ -93,7 +93,7 @@ public abstract class BaseRangeFieldQueryTestCase extends LuceneTestCase {
ranges[id] = new Range[] {nextRange(dimensions)};
}
if (x == 17) {
- // dome docs don't have a box:
+ // some docs don't have a box:
ranges[id][0].isMissing = true;
if (VERBOSE) {
System.out.println(" id=" + id + " is missing");
[24/32] lucene-solr:jira/solr-5944: LUCENE-7590: add
DocValuesStatsCollector
Posted by ho...@apache.org.
LUCENE-7590: add DocValuesStatsCollector
Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/ad7152ad
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/ad7152ad
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/ad7152ad
Branch: refs/heads/jira/solr-5944
Commit: ad7152ad4739a47aa2b45405ba1682b3dda18923
Parents: 9aa5b73
Author: Shai Erera <sh...@apache.org>
Authored: Sun Dec 11 12:49:50 2016 +0200
Committer: Shai Erera <sh...@apache.org>
Committed: Wed Dec 14 13:04:52 2016 +0200
----------------------------------------------------------------------
.../apache/lucene/search/DocValuesStats.java | 165 ++++++++++++++++++
.../lucene/search/DocValuesStatsCollector.java | 64 +++++++
.../search/TestDocValuesStatsCollector.java | 166 +++++++++++++++++++
3 files changed, 395 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ad7152ad/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
----------------------------------------------------------------------
diff --git a/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java b/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
new file mode 100644
index 0000000..fad9f97
--- /dev/null
+++ b/lucene/misc/src/java/org/apache/lucene/search/DocValuesStats.java
@@ -0,0 +1,165 @@
+/*
+ * 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.search;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.NumericDocValues;
+
+/** Holds statistics for a DocValues field. */
+public abstract class DocValuesStats<T> {
+
+ private int missing = 0;
+ private int count = 0;
+
+ protected final String field;
+
+ protected T min;
+ protected T max;
+
+ protected DocValuesStats(String field, T initialMin, T initialMax) {
+ this.field = field;
+ this.min = initialMin;
+ this.max = initialMax;
+ }
+
+ /**
+ * Called after #{@link DocValuesStats#accumulate(int)} was processed and verified that the document has a value for
+ * the field. Implementations should update the statistics based on the value of the current document.
+ *
+ * @param count
+ * the updated number of documents with value for this field.
+ */
+ protected abstract void doAccumulate(int count) throws IOException;
+
+ /**
+ * Initializes this object with the given reader context. Returns whether stats can be computed for this segment (i.e.
+ * it does have the requested DocValues field).
+ */
+ protected abstract boolean init(LeafReaderContext contxt) throws IOException;
+
+ /** Returns whether the given document has a value for the requested DocValues field. */
+ protected abstract boolean hasValue(int doc) throws IOException;
+
+ final void accumulate(int doc) throws IOException {
+ if (hasValue(doc)) {
+ ++count;
+ doAccumulate(count);
+ } else {
+ ++missing;
+ }
+ }
+
+ final void addMissing() {
+ ++missing;
+ }
+
+ /** The field for which these stats were computed. */
+ public final String field() {
+ return field;
+ }
+
+ /** The number of documents which have a value of the field. */
+ public final int count() {
+ return count;
+ }
+
+ /** The number of documents which do not have a value of the field. */
+ public final int missing() {
+ return missing;
+ }
+
+ /** The minimum value of the field. Undefined when {@link #count} is zero. */
+ public final T min() {
+ return min;
+ }
+
+ /** The maximum value of the field. Undefined when {@link #count} is zero. */
+ public final T max() {
+ return max;
+ }
+
+ /** Holds statistics for a numeric DocValues field. */
+ public static abstract class NumericDocValuesStats<T extends Number> extends DocValuesStats<T> {
+
+ protected double mean = 0.0;
+
+ protected NumericDocValues ndv;
+
+ protected NumericDocValuesStats(String field, T initialMin, T initialMax) {
+ super(field, initialMin, initialMax);
+ }
+
+ @Override
+ protected final boolean init(LeafReaderContext contxt) throws IOException {
+ ndv = contxt.reader().getNumericDocValues(field);
+ return ndv != null;
+ }
+
+ @Override
+ protected boolean hasValue(int doc) throws IOException {
+ return ndv.advanceExact(doc);
+ }
+
+ /** The mean of all values of the field. Undefined when {@link #count} is zero. */
+ public final double mean() {
+ return mean;
+ }
+ }
+
+ /** Holds DocValues statistics for a numeric field storing {@code long} values. */
+ public static final class LongDocValuesStats extends NumericDocValuesStats<Long> {
+
+ public LongDocValuesStats(String description) {
+ super(description, Long.MAX_VALUE, Long.MIN_VALUE);
+ }
+
+ @Override
+ protected void doAccumulate(int count) throws IOException {
+ long val = ndv.longValue();
+ if (val > max) {
+ max = val;
+ }
+ if (val < min) {
+ min = val;
+ }
+ mean += (val - mean) / count;
+ }
+ }
+
+ /** Holds DocValues statistics for a numeric field storing {@code double} values. */
+ public static final class DoubleDocValuesStats extends NumericDocValuesStats<Double> {
+
+ public DoubleDocValuesStats(String description) {
+ super(description, Double.MAX_VALUE, Double.MIN_VALUE);
+ }
+
+ @Override
+ protected void doAccumulate(int count) throws IOException {
+ double val = Double.longBitsToDouble(ndv.longValue());
+ if (Double.compare(val, max) > 0) {
+ max = val;
+ }
+ if (Double.compare(val, min) < 0) {
+ min = val;
+ }
+ mean += (val - mean) / count;
+ }
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ad7152ad/lucene/misc/src/java/org/apache/lucene/search/DocValuesStatsCollector.java
----------------------------------------------------------------------
diff --git a/lucene/misc/src/java/org/apache/lucene/search/DocValuesStatsCollector.java b/lucene/misc/src/java/org/apache/lucene/search/DocValuesStatsCollector.java
new file mode 100644
index 0000000..2b1fa4f
--- /dev/null
+++ b/lucene/misc/src/java/org/apache/lucene/search/DocValuesStatsCollector.java
@@ -0,0 +1,64 @@
+/*
+ * 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.search;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.LeafReaderContext;
+
+/** A {@link Collector} which computes statistics for a DocValues field. */
+public class DocValuesStatsCollector implements Collector {
+
+ private final DocValuesStats<?> stats;
+
+ /** Creates a collector to compute statistics for a DocValues field using the given {@code stats}. */
+ public DocValuesStatsCollector(DocValuesStats<?> stats) {
+ this.stats = stats;
+ }
+
+ @Override
+ public LeafCollector getLeafCollector(LeafReaderContext context) throws IOException {
+ boolean shouldProcess = stats.init(context);
+ if (!shouldProcess) {
+ // Stats cannot be computed for this segment, therefore consider all matching documents as a 'miss'.
+ return new LeafCollector() {
+ @Override public void setScorer(Scorer scorer) throws IOException {}
+
+ @Override
+ public void collect(int doc) throws IOException {
+ // All matching documents in this reader are missing a value
+ stats.addMissing();
+ }
+ };
+ }
+
+ return new LeafCollector() {
+ @Override public void setScorer(Scorer scorer) throws IOException {}
+
+ @Override
+ public void collect(int doc) throws IOException {
+ stats.accumulate(doc);
+ }
+ };
+ }
+
+ @Override
+ public boolean needsScores() {
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/ad7152ad/lucene/misc/src/test/org/apache/lucene/search/TestDocValuesStatsCollector.java
----------------------------------------------------------------------
diff --git a/lucene/misc/src/test/org/apache/lucene/search/TestDocValuesStatsCollector.java b/lucene/misc/src/test/org/apache/lucene/search/TestDocValuesStatsCollector.java
new file mode 100644
index 0000000..65f82e6
--- /dev/null
+++ b/lucene/misc/src/test/org/apache/lucene/search/TestDocValuesStatsCollector.java
@@ -0,0 +1,166 @@
+/*
+ * 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.search;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.stream.DoubleStream;
+import java.util.stream.LongStream;
+
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.DoubleDocValuesField;
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.document.NumericDocValuesField;
+import org.apache.lucene.document.StringField;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.DocValuesStats.DoubleDocValuesStats;
+import org.apache.lucene.search.DocValuesStats.LongDocValuesStats;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.TestUtil;
+
+/** Unit tests for {@link DocValuesStatsCollector}. */
+public class TestDocValuesStatsCollector extends LuceneTestCase {
+
+ public void testNoDocsWithField() throws IOException {
+ try (Directory dir = newDirectory();
+ IndexWriter indexWriter = new IndexWriter(dir, newIndexWriterConfig())) {
+ int numDocs = TestUtil.nextInt(random(), 1, 100);
+ for (int i = 0; i < numDocs; i++) {
+ indexWriter.addDocument(new Document());
+ }
+
+ try (DirectoryReader reader = DirectoryReader.open(indexWriter)) {
+ IndexSearcher searcher = new IndexSearcher(reader);
+ LongDocValuesStats stats = new LongDocValuesStats("foo");
+ searcher.search(new MatchAllDocsQuery(), new DocValuesStatsCollector(stats));
+
+ assertEquals(0, stats.count());
+ assertEquals(numDocs, stats.missing());
+ }
+ }
+ }
+
+ public void testRandomDocsWithLongValues() throws IOException {
+ try (Directory dir = newDirectory();
+ IndexWriter indexWriter = new IndexWriter(dir, newIndexWriterConfig())) {
+ String field = "numeric";
+ int numDocs = TestUtil.nextInt(random(), 1, 100);
+ long[] docValues = new long[numDocs];
+ int nextVal = 1;
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ if (random().nextBoolean()) { // not all documents have a value
+ doc.add(new NumericDocValuesField(field, nextVal));
+ doc.add(new StringField("id", "doc" + i, Store.NO));
+ docValues[i] = nextVal;
+ ++nextVal;
+ }
+ indexWriter.addDocument(doc);
+ }
+
+ // 20% of cases delete some docs
+ if (random().nextDouble() < 0.2) {
+ for (int i = 0; i < numDocs; i++) {
+ if (random().nextBoolean()) {
+ indexWriter.deleteDocuments(new Term("id", "doc" + i));
+ docValues[i] = 0;
+ }
+ }
+ }
+
+ try (DirectoryReader reader = DirectoryReader.open(indexWriter)) {
+ IndexSearcher searcher = new IndexSearcher(reader);
+ LongDocValuesStats stats = new LongDocValuesStats(field);
+ searcher.search(new MatchAllDocsQuery(), new DocValuesStatsCollector(stats));
+
+ int expCount = (int) Arrays.stream(docValues).filter(v -> v > 0).count();
+ assertEquals(expCount, stats.count());
+ assertEquals(getZeroValues(docValues).count() - reader.numDeletedDocs(), stats.missing());
+ if (stats.count() > 0) {
+ assertEquals(getPositiveValues(docValues).max().getAsLong(), stats.max().longValue());
+ assertEquals(getPositiveValues(docValues).min().getAsLong(), stats.min().longValue());
+ assertEquals(getPositiveValues(docValues).average().getAsDouble(), stats.mean(), 0.00001);
+ }
+ }
+ }
+ }
+
+ public void testRandomDocsWithDoubleValues() throws IOException {
+ try (Directory dir = newDirectory();
+ IndexWriter indexWriter = new IndexWriter(dir, newIndexWriterConfig())) {
+ String field = "numeric";
+ int numDocs = TestUtil.nextInt(random(), 1, 100);
+ double[] docValues = new double[numDocs];
+ double nextVal = 1.0;
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ if (random().nextBoolean()) { // not all documents have a value
+ doc.add(new DoubleDocValuesField(field, nextVal));
+ doc.add(new StringField("id", "doc" + i, Store.NO));
+ docValues[i] = nextVal;
+ ++nextVal;
+ }
+ indexWriter.addDocument(doc);
+ }
+
+ // 20% of cases delete some docs
+ if (random().nextDouble() < 0.2) {
+ for (int i = 0; i < numDocs; i++) {
+ if (random().nextBoolean()) {
+ indexWriter.deleteDocuments(new Term("id", "doc" + i));
+ docValues[i] = 0;
+ }
+ }
+ }
+
+ try (DirectoryReader reader = DirectoryReader.open(indexWriter)) {
+ IndexSearcher searcher = new IndexSearcher(reader);
+ DoubleDocValuesStats stats = new DoubleDocValuesStats(field);
+ searcher.search(new MatchAllDocsQuery(), new DocValuesStatsCollector(stats));
+
+ int expCount = (int) Arrays.stream(docValues).filter(v -> v > 0).count();
+ assertEquals(expCount, stats.count());
+ assertEquals(getZeroValues(docValues).count() - reader.numDeletedDocs(), stats.missing());
+ if (stats.count() > 0) {
+ assertEquals(getPositiveValues(docValues).max().getAsDouble(), stats.max().doubleValue(), 0.00001);
+ assertEquals(getPositiveValues(docValues).min().getAsDouble(), stats.min().doubleValue(), 0.00001);
+ assertEquals(getPositiveValues(docValues).average().getAsDouble(), stats.mean(), 0.00001);
+ }
+ }
+ }
+ }
+
+ private static LongStream getPositiveValues(long[] docValues) {
+ return Arrays.stream(docValues).filter(v -> v > 0);
+ }
+
+ private static DoubleStream getPositiveValues(double[] docValues) {
+ return Arrays.stream(docValues).filter(v -> v > 0);
+ }
+
+ private static LongStream getZeroValues(long[] docValues) {
+ return Arrays.stream(docValues).filter(v -> v == 0);
+ }
+
+ private static DoubleStream getZeroValues(double[] docValues) {
+ return Arrays.stream(docValues).filter(v -> v == 0);
+ }
+
+}