You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by rm...@apache.org on 2011/06/16 22:34:04 UTC
svn commit: r1136656 [3/4] - in /lucene/dev/branches/flexscoring: ./
dev-tools/idea/.idea/ dev-tools/idea/lucene/ dev-tools/idea/lucene/contrib/
dev-tools/maven/ lucene/ lucene/backwards/ lucene/contrib/
lucene/contrib/misc/src/java/org/apache/lucene/i...
Modified: lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/TestSort.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/TestSort.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/TestSort.java (original)
+++ lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/TestSort.java Thu Jun 16 20:33:59 2011
@@ -511,7 +511,7 @@ public class TestSort extends LuceneTest
assertMatches (empty, queryX, sort, "");
}
- static class MyFieldComparator extends FieldComparator {
+ static class MyFieldComparator extends FieldComparator<Integer> {
int[] docValues;
int[] slotValues;
int bottomValue;
@@ -527,6 +527,7 @@ public class TestSort extends LuceneTest
@Override
public int compare(int slot1, int slot2) {
+ // values are small enough that overflow won't happen
return slotValues[slot1] - slotValues[slot2];
}
@@ -553,7 +554,7 @@ public class TestSort extends LuceneTest
}
@Override
- public Comparable<?> value(int slot) {
+ public Integer value(int slot) {
return Integer.valueOf(slotValues[slot]);
}
}
Modified: lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/TestTermScorer.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/TestTermScorer.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/TestTermScorer.java (original)
+++ lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/TestTermScorer.java Thu Jun 16 20:33:59 2011
@@ -73,7 +73,7 @@ public class TestTermScorer extends Luce
Term allTerm = new Term(FIELD, "all");
TermQuery termQuery = new TermQuery(allTerm);
- Weight weight = termQuery.weight(indexSearcher);
+ Weight weight = indexSearcher.createNormalizedWeight(termQuery);
assertTrue(indexSearcher.getTopReaderContext().isAtomic);
Scorer ts = weight.scorer((AtomicReaderContext)indexSearcher.getTopReaderContext(), ScorerContext.def().scoreDocsInOrder(true).topScorer(true));
// we have 2 documents with the term all in them, one document for all the
@@ -134,7 +134,7 @@ public class TestTermScorer extends Luce
Term allTerm = new Term(FIELD, "all");
TermQuery termQuery = new TermQuery(allTerm);
- Weight weight = termQuery.weight(indexSearcher);
+ Weight weight = indexSearcher.createNormalizedWeight(termQuery);
assertTrue(indexSearcher.getTopReaderContext().isAtomic);
Scorer ts = weight.scorer((AtomicReaderContext) indexSearcher.getTopReaderContext(), ScorerContext.def().scoreDocsInOrder(true).topScorer(true));
assertTrue("next did not return a doc",
@@ -152,7 +152,7 @@ public class TestTermScorer extends Luce
Term allTerm = new Term(FIELD, "all");
TermQuery termQuery = new TermQuery(allTerm);
- Weight weight = termQuery.weight(indexSearcher);
+ Weight weight = indexSearcher.createNormalizedWeight(termQuery);
assertTrue(indexSearcher.getTopReaderContext().isAtomic);
Scorer ts = weight.scorer((AtomicReaderContext) indexSearcher.getTopReaderContext(), ScorerContext.def().scoreDocsInOrder(true).topScorer(true));
Modified: lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/spans/TestNearSpansOrdered.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/spans/TestNearSpansOrdered.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/spans/TestNearSpansOrdered.java (original)
+++ lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/spans/TestNearSpansOrdered.java Thu Jun 16 20:33:59 2011
@@ -170,22 +170,20 @@ public class TestNearSpansOrdered extend
*/
public void testSpanNearScorerSkipTo1() throws Exception {
SpanNearQuery q = makeQuery();
- Weight w = q.weight(searcher);
+ Weight w = searcher.createNormalizedWeight(q);
ReaderContext topReaderContext = searcher.getTopReaderContext();
AtomicReaderContext[] leaves = ReaderUtil.leaves(topReaderContext);
Scorer s = w.scorer(leaves[0], ScorerContext.def());
assertEquals(1, s.advance(1));
}
+
/**
* not a direct test of NearSpans, but a demonstration of how/when
* this causes problems
*/
public void testSpanNearScorerExplain() throws Exception {
SpanNearQuery q = makeQuery();
- ReaderContext topReaderContext = searcher.getTopReaderContext();
- AtomicReaderContext[] leaves = ReaderUtil.leaves(topReaderContext);
-
- Explanation e = q.weight(searcher).explain(leaves[0], 1);
+ Explanation e = searcher.explain(q, 1);
assertTrue("Scorer explanation value for doc#1 isn't positive: "
+ e.toString(),
0.0f < e.getValue());
Modified: lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/spans/TestSpans.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/spans/TestSpans.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/spans/TestSpans.java (original)
+++ lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/search/spans/TestSpans.java Thu Jun 16 20:33:59 2011
@@ -434,7 +434,7 @@ public class TestSpans extends LuceneTes
slop,
ordered);
- spanScorer = snq.weight(searcher).scorer(leaves[i], ScorerContext.def());
+ spanScorer = searcher.createNormalizedWeight(snq).scorer(leaves[i], ScorerContext.def());
} finally {
searcher.setSimilarityProvider(oldSim);
}
Modified: lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/store/TestMultiMMap.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/store/TestMultiMMap.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/store/TestMultiMMap.java (original)
+++ lucene/dev/branches/flexscoring/lucene/src/test/org/apache/lucene/store/TestMultiMMap.java Thu Jun 16 20:33:59 2011
@@ -25,6 +25,7 @@ import org.apache.lucene.document.Docume
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.RandomIndexWriter;
+import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
@@ -40,9 +41,68 @@ public class TestMultiMMap extends Lucen
@Override
public void setUp() throws Exception {
- super.setUp();
- workDir = _TestUtil.getTempDir("TestMultiMMap");
- workDir.mkdirs();
+ super.setUp();
+ assumeTrue("test requires a jre that supports unmapping", MMapDirectory.UNMAP_SUPPORTED);
+ workDir = _TestUtil.getTempDir("TestMultiMMap");
+ workDir.mkdirs();
+ }
+
+ public void testSeekZero() throws Exception {
+ for (int i = 0; i < 31; i++) {
+ MMapDirectory mmapDir = new MMapDirectory(_TestUtil.getTempDir("testSeekZero"));
+ mmapDir.setMaxChunkSize(1<<i);
+ IndexOutput io = mmapDir.createOutput("zeroBytes");
+ io.close();
+ IndexInput ii = mmapDir.openInput("zeroBytes");
+ ii.seek(0L);
+ ii.close();
+ mmapDir.close();
+ }
+ }
+
+ public void testSeekEnd() throws Exception {
+ for (int i = 0; i < 17; i++) {
+ MMapDirectory mmapDir = new MMapDirectory(_TestUtil.getTempDir("testSeekEnd"));
+ mmapDir.setMaxChunkSize(1<<i);
+ IndexOutput io = mmapDir.createOutput("bytes");
+ byte bytes[] = new byte[1<<i];
+ random.nextBytes(bytes);
+ io.writeBytes(bytes, bytes.length);
+ io.close();
+ IndexInput ii = mmapDir.openInput("bytes");
+ byte actual[] = new byte[1<<i];
+ ii.readBytes(actual, 0, actual.length);
+ assertEquals(new BytesRef(bytes), new BytesRef(actual));
+ ii.seek(1<<i);
+ ii.close();
+ mmapDir.close();
+ }
+ }
+
+ public void testSeeking() throws Exception {
+ for (int i = 0; i < 10; i++) {
+ MMapDirectory mmapDir = new MMapDirectory(_TestUtil.getTempDir("testSeeking"));
+ mmapDir.setMaxChunkSize(1<<i);
+ IndexOutput io = mmapDir.createOutput("bytes");
+ byte bytes[] = new byte[1<<(i+1)]; // make sure we switch buffers
+ random.nextBytes(bytes);
+ io.writeBytes(bytes, bytes.length);
+ io.close();
+ IndexInput ii = mmapDir.openInput("bytes");
+ byte actual[] = new byte[1<<(i+1)]; // first read all bytes
+ ii.readBytes(actual, 0, actual.length);
+ assertEquals(new BytesRef(bytes), new BytesRef(actual));
+ for (int sliceStart = 0; sliceStart < bytes.length; sliceStart++) {
+ for (int sliceLength = 0; sliceLength < bytes.length - sliceStart; sliceLength++) {
+ byte slice[] = new byte[sliceLength];
+ ii.seek(sliceStart);
+ ii.readBytes(slice, 0, slice.length);
+ assertEquals(new BytesRef(bytes, sliceStart, sliceLength), new BytesRef(slice));
+ }
+ }
+ ii.close();
+ mmapDir.close();
+ }
}
public void testRandomChunkSizes() throws Exception {
@@ -55,11 +115,12 @@ public class TestMultiMMap extends Lucen
File path = _TestUtil.createTempFile("mmap" + chunkSize, "tmp", workDir);
path.delete();
path.mkdirs();
- MMapDirectory dir = new MMapDirectory(path);
- dir.setMaxChunkSize(chunkSize);
+ MMapDirectory mmapDir = new MMapDirectory(path);
+ mmapDir.setMaxChunkSize(chunkSize);
// we will map a lot, try to turn on the unmap hack
if (MMapDirectory.UNMAP_SUPPORTED)
- dir.setUseUnmap(true);
+ mmapDir.setUseUnmap(true);
+ MockDirectoryWrapper dir = new MockDirectoryWrapper(random, mmapDir);
RandomIndexWriter writer = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
Document doc = new Document();
Field docid = newField("docid", "0", Field.Store.YES, Field.Index.NOT_ANALYZED);
Modified: lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/AbstractFirstPassGroupingCollector.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/AbstractFirstPassGroupingCollector.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/AbstractFirstPassGroupingCollector.java (original)
+++ lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/AbstractFirstPassGroupingCollector.java Thu Jun 16 20:33:59 2011
@@ -122,7 +122,7 @@ abstract public class AbstractFirstPassG
SearchGroup<GROUP_VALUE_TYPE> searchGroup = new SearchGroup<GROUP_VALUE_TYPE>();
searchGroup.groupValue = group.groupValue;
if (fillFields) {
- searchGroup.sortValues = new Comparable[sortFieldCount];
+ searchGroup.sortValues = new Object[sortFieldCount];
for(int sortFieldIDX=0;sortFieldIDX<sortFieldCount;sortFieldIDX++) {
searchGroup.sortValues[sortFieldIDX] = comparators[sortFieldIDX].value(group.comparatorSlot);
}
Modified: lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java (original)
+++ lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java Thu Jun 16 20:33:59 2011
@@ -348,7 +348,7 @@ public class BlockGroupingCollector exte
}
totalGroupedHitCount += og.count;
- final Comparable[] groupSortValues;
+ final Object[] groupSortValues;
if (fillSortFields) {
groupSortValues = new Comparable[comparators.length];
Modified: lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/GroupDocs.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/GroupDocs.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/GroupDocs.java (original)
+++ lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/GroupDocs.java Thu Jun 16 20:33:59 2011
@@ -40,13 +40,13 @@ public class GroupDocs<GROUP_VALUE_TYPE>
/** Matches the groupSort passed to {@link
* AbstractFirstPassGroupingCollector}. */
- public final Comparable[] groupSortValues;
+ public final Object[] groupSortValues;
public GroupDocs(float maxScore,
int totalHits,
ScoreDoc[] scoreDocs,
GROUP_VALUE_TYPE groupValue,
- Comparable[] groupSortValues) {
+ Object[] groupSortValues) {
this.maxScore = maxScore;
this.totalHits = totalHits;
this.scoreDocs = scoreDocs;
Modified: lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/SearchGroup.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/SearchGroup.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/SearchGroup.java (original)
+++ lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/SearchGroup.java Thu Jun 16 20:33:59 2011
@@ -17,6 +17,14 @@ package org.apache.lucene.search.groupin
* limitations under the License.
*/
+import java.io.IOException;
+import java.util.*;
+
+import org.apache.lucene.search.FieldComparator;
+import org.apache.lucene.search.Sort;
+import org.apache.lucene.search.SortField;
+import org.apache.lucene.util.BytesRef;
+
/**
* Represents a group that is found during the first pass search.
*
@@ -27,6 +35,287 @@ public class SearchGroup<GROUP_VALUE_TYP
/** The value that defines this group */
public GROUP_VALUE_TYPE groupValue;
- /** The sort values used during sorting. Can be <code>null</code>. */
- public Comparable[] sortValues;
+ /** The sort values used during sorting. These are the
+ * groupSort field values of the highest rank document
+ * (by the groupSort) within the group. Can be
+ * <code>null</code> if <code>fillFields=false</code> had
+ * been passed to {@link AbstractFirstPassGroupingCollector#getTopGroups} */
+ public Object[] sortValues;
+
+ @Override
+ public String toString() {
+ return("SearchGroup(groupValue=" + groupValue + " sortValues=" + Arrays.toString(sortValues) + ")");
+ }
+
+ private static class ShardIter<T> {
+ public final Iterator<SearchGroup<T>> iter;
+ public final int shardIndex;
+
+ public ShardIter(Collection<SearchGroup<T>> shard, int shardIndex) {
+ this.shardIndex = shardIndex;
+ iter = shard.iterator();
+ assert iter.hasNext();
+ }
+
+ public SearchGroup<T> next() {
+ assert iter.hasNext();
+ final SearchGroup<T> group = iter.next();
+ if (group.sortValues == null) {
+ throw new IllegalArgumentException("group.sortValues is null; you must pass fillFields=true to the first pass collector");
+ }
+ return group;
+ }
+
+ @Override
+ public String toString() {
+ return "ShardIter(shard=" + shardIndex + ")";
+ }
+ }
+
+ // Holds all shards currently on the same group
+ private static class MergedGroup<T> {
+
+ // groupValue may be null!
+ public final T groupValue;
+
+ public Object[] topValues;
+ public final List<ShardIter<T>> shards = new ArrayList<ShardIter<T>>();
+ public int minShardIndex;
+ public boolean processed;
+ public boolean inQueue;
+
+ public MergedGroup(T groupValue) {
+ this.groupValue = groupValue;
+ }
+
+ // Only for assert
+ private boolean neverEquals(Object _other) {
+ if (_other instanceof MergedGroup) {
+ MergedGroup other = (MergedGroup) _other;
+ if (groupValue == null) {
+ assert other.groupValue != null;
+ } else {
+ assert !groupValue.equals(other.groupValue);
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean equals(Object _other) {
+ // We never have another MergedGroup instance with
+ // same groupValue
+ assert neverEquals(_other);
+
+ if (_other instanceof MergedGroup) {
+ MergedGroup other = (MergedGroup) _other;
+ if (groupValue == null) {
+ return other == null;
+ } else {
+ return groupValue.equals(other);
+ }
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ if (groupValue == null) {
+ return 0;
+ } else {
+ return groupValue.hashCode();
+ }
+ }
+ }
+
+ private static class GroupComparator<T> implements Comparator<MergedGroup<T>> {
+
+ public final FieldComparator[] comparators;
+ public final int[] reversed;
+
+ public GroupComparator(Sort groupSort) throws IOException {
+ final SortField[] sortFields = groupSort.getSort();
+ comparators = new FieldComparator[sortFields.length];
+ reversed = new int[sortFields.length];
+ for (int compIDX = 0; compIDX < sortFields.length; compIDX++) {
+ final SortField sortField = sortFields[compIDX];
+ comparators[compIDX] = sortField.getComparator(1, compIDX);
+ reversed[compIDX] = sortField.getReverse() ? -1 : 1;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public int compare(MergedGroup<T> group, MergedGroup<T> other) {
+ if (group == other) {
+ return 0;
+ }
+ //System.out.println("compare group=" + group + " other=" + other);
+ final Object[] groupValues = group.topValues;
+ final Object[] otherValues = other.topValues;
+ //System.out.println(" groupValues=" + groupValues + " otherValues=" + otherValues);
+ for (int compIDX = 0;compIDX < comparators.length; compIDX++) {
+ final int c = reversed[compIDX] * comparators[compIDX].compareValues(groupValues[compIDX],
+ otherValues[compIDX]);
+ if (c != 0) {
+ return c;
+ }
+ }
+
+ // Tie break by min shard index:
+ assert group.minShardIndex != other.minShardIndex;
+ return group.minShardIndex - other.minShardIndex;
+ }
+ }
+
+ private static class GroupMerger<T> {
+
+ private final GroupComparator<T> groupComp;
+ private final SortedSet<MergedGroup<T>> queue;
+ private final Map<T,MergedGroup<T>> groupsSeen;
+
+ public GroupMerger(Sort groupSort) throws IOException {
+ groupComp = new GroupComparator<T>(groupSort);
+ queue = new TreeSet<MergedGroup<T>>(groupComp);
+ groupsSeen = new HashMap<T,MergedGroup<T>>();
+ }
+
+ @SuppressWarnings("unchecked")
+ private void updateNextGroup(int topN, ShardIter<T> shard) {
+ while(shard.iter.hasNext()) {
+ final SearchGroup<T> group = shard.next();
+ MergedGroup<T> mergedGroup = groupsSeen.get(group.groupValue);
+ final boolean isNew = mergedGroup == null;
+ //System.out.println(" next group=" + (group.groupValue == null ? "null" : ((BytesRef) group.groupValue).utf8ToString()) + " sort=" + Arrays.toString(group.sortValues));
+
+ if (isNew) {
+ // Start a new group:
+ //System.out.println(" new");
+ mergedGroup = new MergedGroup<T>(group.groupValue);
+ mergedGroup.minShardIndex = shard.shardIndex;
+ assert group.sortValues != null;
+ mergedGroup.topValues = group.sortValues;
+ groupsSeen.put(group.groupValue, mergedGroup);
+ mergedGroup.inQueue = true;
+ queue.add(mergedGroup);
+ } else if (mergedGroup.processed) {
+ // This shard produced a group that we already
+ // processed; move on to next group...
+ continue;
+ } else {
+ //System.out.println(" old");
+ boolean competes = false;
+ for(int compIDX=0;compIDX<groupComp.comparators.length;compIDX++) {
+ final int cmp = groupComp.reversed[compIDX] * groupComp.comparators[compIDX].compareValues(group.sortValues[compIDX],
+ mergedGroup.topValues[compIDX]);
+ if (cmp < 0) {
+ // Definitely competes
+ competes = true;
+ break;
+ } else if (cmp > 0) {
+ // Definitely does not compete
+ break;
+ } else if (compIDX == groupComp.comparators.length-1) {
+ if (shard.shardIndex < mergedGroup.minShardIndex) {
+ competes = true;
+ }
+ }
+ }
+
+ //System.out.println(" competes=" + competes);
+
+ if (competes) {
+ // Group's sort changed -- remove & re-insert
+ if (mergedGroup.inQueue) {
+ queue.remove(mergedGroup);
+ }
+ mergedGroup.topValues = group.sortValues;
+ mergedGroup.minShardIndex = shard.shardIndex;
+ queue.add(mergedGroup);
+ mergedGroup.inQueue = true;
+ }
+ }
+
+ mergedGroup.shards.add(shard);
+ break;
+ }
+
+ // Prune un-competitive groups:
+ while(queue.size() > topN) {
+ // TODO java 1.6: .pollLast
+ final MergedGroup<T> group = queue.last();
+ //System.out.println("PRUNE: " + group);
+ queue.remove(group);
+ group.inQueue = false;
+ }
+ }
+
+ public Collection<SearchGroup<T>> merge(List<Collection<SearchGroup<T>>> shards, int offset, int topN) {
+
+ final int maxQueueSize = offset + topN;
+
+ //System.out.println("merge");
+ // Init queue:
+ for(int shardIDX=0;shardIDX<shards.size();shardIDX++) {
+ final Collection<SearchGroup<T>> shard = shards.get(shardIDX);
+ if (!shard.isEmpty()) {
+ //System.out.println(" insert shard=" + shardIDX);
+ updateNextGroup(maxQueueSize, new ShardIter<T>(shard, shardIDX));
+ }
+ }
+
+ // Pull merged topN groups:
+ final List<SearchGroup<T>> newTopGroups = new ArrayList<SearchGroup<T>>();
+
+ int count = 0;
+
+ while(queue.size() != 0) {
+ // TODO Java 1.6: pollFirst()
+ final MergedGroup<T> group = queue.first();
+ queue.remove(group);
+ group.processed = true;
+ //System.out.println(" pop: shards=" + group.shards + " group=" + (group.groupValue == null ? "null" : (((BytesRef) group.groupValue).utf8ToString())) + " sortValues=" + Arrays.toString(group.topValues));
+ if (count++ >= offset) {
+ final SearchGroup<T> newGroup = new SearchGroup<T>();
+ newGroup.groupValue = group.groupValue;
+ newGroup.sortValues = group.topValues;
+ newTopGroups.add(newGroup);
+ if (newTopGroups.size() == topN) {
+ break;
+ }
+ //} else {
+ // System.out.println(" skip < offset");
+ }
+
+ // Advance all iters in this group:
+ for(ShardIter<T> shardIter : group.shards) {
+ updateNextGroup(maxQueueSize, shardIter);
+ }
+ }
+
+ if (newTopGroups.size() == 0) {
+ return null;
+ } else {
+ return newTopGroups;
+ }
+ }
+ }
+
+ /** Merges multiple collections of top groups, for example
+ * obtained from separate index shards. The provided
+ * groupSort must match how the groups were sorted, and
+ * the provided SearchGroups must have been computed
+ * with fillFields=true passed to {@link
+ * AbstractFirstPassGroupingCollector#getTopGroups}.
+ *
+ * <p>NOTE: this returns null if the topGroups is empty.
+ */
+ public static <T> Collection<SearchGroup<T>> merge(List<Collection<SearchGroup<T>>> topGroups, int offset, int topN, Sort groupSort)
+ throws IOException {
+ if (topGroups.size() == 0) {
+ return null;
+ } else {
+ return new GroupMerger<T>(groupSort).merge(topGroups, offset, topN);
+ }
+ }
}
Modified: lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/TopGroups.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/TopGroups.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/TopGroups.java (original)
+++ lucene/dev/branches/flexscoring/modules/grouping/src/java/org/apache/lucene/search/grouping/TopGroups.java Thu Jun 16 20:33:59 2011
@@ -1,7 +1,5 @@
package org.apache.lucene.search.grouping;
-import org.apache.lucene.search.SortField;
-
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -19,6 +17,13 @@ import org.apache.lucene.search.SortFiel
* limitations under the License.
*/
+import java.io.IOException;
+
+import org.apache.lucene.search.ScoreDoc;
+import org.apache.lucene.search.Sort;
+import org.apache.lucene.search.SortField;
+import org.apache.lucene.search.TopDocs;
+
/** Represents result returned by a grouping search.
*
* @lucene.experimental */
@@ -58,4 +63,103 @@ public class TopGroups<GROUP_VALUE_TYPE>
this.groups = oldTopGroups.groups;
this.totalGroupCount = totalGroupCount;
}
+
+ /** Merges an array of TopGroups, for example obtained
+ * from the second-pass collector across multiple
+ * shards. Each TopGroups must have been sorted by the
+ * same groupSort and docSort, and the top groups passed
+ * to all second-pass collectors must be the same.
+ *
+ * <b>NOTE</b>: this cannot merge totalGroupCount; ie the
+ * returned TopGroups will have null totalGroupCount.
+ *
+ * <b>NOTE</b>: the topDocs in each GroupDocs is actually
+ * an instance of TopDocsAndShards
+ */
+ public static <T> TopGroups<T> merge(TopGroups<T>[] shardGroups, Sort groupSort, Sort docSort, int docOffset, int docTopN)
+ throws IOException {
+
+ //System.out.println("TopGroups.merge");
+
+ if (shardGroups.length == 0) {
+ return null;
+ }
+
+ int totalHitCount = 0;
+ int totalGroupedHitCount = 0;
+
+ final int numGroups = shardGroups[0].groups.length;
+ for(TopGroups<T> shard : shardGroups) {
+ if (numGroups != shard.groups.length) {
+ throw new IllegalArgumentException("number of groups differs across shards; you must pass same top groups to all shards' second-pass collector");
+ }
+ totalHitCount += shard.totalHitCount;
+ totalGroupedHitCount += shard.totalGroupedHitCount;
+ }
+
+ @SuppressWarnings("unchecked")
+ final GroupDocs<T>[] mergedGroupDocs = new GroupDocs[numGroups];
+
+ final TopDocs[] shardTopDocs = new TopDocs[shardGroups.length];
+
+ for(int groupIDX=0;groupIDX<numGroups;groupIDX++) {
+ final T groupValue = shardGroups[0].groups[groupIDX].groupValue;
+ //System.out.println(" merge groupValue=" + groupValue + " sortValues=" + Arrays.toString(shardGroups[0].groups[groupIDX].groupSortValues));
+ float maxScore = Float.MIN_VALUE;
+ int totalHits = 0;
+ for(int shardIDX=0;shardIDX<shardGroups.length;shardIDX++) {
+ //System.out.println(" shard=" + shardIDX);
+ final TopGroups<T> shard = shardGroups[shardIDX];
+ final GroupDocs shardGroupDocs = shard.groups[groupIDX];
+ if (groupValue == null) {
+ if (shardGroupDocs.groupValue != null) {
+ throw new IllegalArgumentException("group values differ across shards; you must pass same top groups to all shards' second-pass collector");
+ }
+ } else if (!groupValue.equals(shardGroupDocs.groupValue)) {
+ throw new IllegalArgumentException("group values differ across shards; you must pass same top groups to all shards' second-pass collector");
+ }
+
+ /*
+ for(ScoreDoc sd : shardGroupDocs.scoreDocs) {
+ System.out.println(" doc=" + sd.doc);
+ }
+ */
+
+ shardTopDocs[shardIDX] = new TopDocs(shardGroupDocs.totalHits,
+ shardGroupDocs.scoreDocs,
+ shardGroupDocs.maxScore);
+ maxScore = Math.max(maxScore, shardGroupDocs.maxScore);
+ totalHits += shardGroupDocs.totalHits;
+ }
+
+ final TopDocs mergedTopDocs = TopDocs.merge(docSort, docOffset + docTopN, shardTopDocs);
+
+ // Slice;
+ final ScoreDoc[] mergedScoreDocs;
+ if (docOffset == 0) {
+ mergedScoreDocs = mergedTopDocs.scoreDocs;
+ } else if (docOffset >= mergedTopDocs.scoreDocs.length) {
+ mergedScoreDocs = new ScoreDoc[0];
+ } else {
+ mergedScoreDocs = new ScoreDoc[mergedTopDocs.scoreDocs.length - docOffset];
+ System.arraycopy(mergedTopDocs.scoreDocs,
+ docOffset,
+ mergedScoreDocs,
+ 0,
+ mergedTopDocs.scoreDocs.length - docOffset);
+ }
+ //System.out.println("SHARDS=" + Arrays.toString(mergedTopDocs.shardIndex));
+ mergedGroupDocs[groupIDX] = new GroupDocs<T>(maxScore,
+ totalHits,
+ mergedScoreDocs,
+ groupValue,
+ shardGroups[0].groups[groupIDX].groupSortValues);
+ }
+
+ return new TopGroups<T>(groupSort.getSort(),
+ docSort == null ? null : docSort.getSort(),
+ totalHitCount,
+ totalGroupedHitCount,
+ mergedGroupDocs);
+ }
}
Modified: lucene/dev/branches/flexscoring/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java (original)
+++ lucene/dev/branches/flexscoring/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java Thu Jun 16 20:33:59 2011
@@ -17,6 +17,9 @@
package org.apache.lucene.search.grouping;
+import java.io.IOException;
+import java.util.*;
+
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
@@ -28,11 +31,9 @@ import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.ReaderUtil;
import org.apache.lucene.util._TestUtil;
-import java.io.IOException;
-import java.util.*;
-
// TODO
// - should test relevance sort too
// - test null
@@ -244,7 +245,6 @@ public class TestGrouping extends Lucene
return fields;
}
- /*
private String groupToString(BytesRef b) {
if (b == null) {
return "null";
@@ -252,7 +252,6 @@ public class TestGrouping extends Lucene
return b.utf8ToString();
}
}
- */
private TopGroups<BytesRef> slowGrouping(GroupDoc[] groupDocs,
String searchTerm,
@@ -418,6 +417,38 @@ public class TestGrouping extends Lucene
return r;
}
+ private static class ShardState {
+
+ public final ShardSearcher[] subSearchers;
+ public final int[] docStarts;
+
+ public ShardState(IndexSearcher s) {
+ IndexReader[] subReaders = s.getIndexReader().getSequentialSubReaders();
+ if (subReaders == null) {
+ subReaders = new IndexReader[] {s.getIndexReader()};
+ }
+ subSearchers = new ShardSearcher[subReaders.length];
+ final IndexReader.ReaderContext ctx = s.getTopReaderContext();
+ if (ctx instanceof IndexReader.AtomicReaderContext) {
+ assert subSearchers.length == 1;
+ subSearchers[0] = new ShardSearcher((IndexReader.AtomicReaderContext) ctx, ctx);
+ } else {
+ final IndexReader.CompositeReaderContext compCTX = (IndexReader.CompositeReaderContext) ctx;
+ for(int searcherIDX=0;searcherIDX<subSearchers.length;searcherIDX++) {
+ subSearchers[searcherIDX] = new ShardSearcher(compCTX.leaves[searcherIDX], compCTX);
+ }
+ }
+
+ docStarts = new int[subSearchers.length];
+ int docBase = 0;
+ for(int subIDX=0;subIDX<docStarts.length;subIDX++) {
+ docStarts[subIDX] = docBase;
+ docBase += subReaders[subIDX].maxDoc();
+ //System.out.println("docStarts[" + subIDX + "]=" + docStarts[subIDX]);
+ }
+ }
+ }
+
public void testRandom() throws Exception {
for(int iter=0;iter<3;iter++) {
@@ -525,7 +556,8 @@ public class TestGrouping extends Lucene
Directory dir2 = null;
try {
- final IndexSearcher s = new IndexSearcher(r);
+ final IndexSearcher s = newSearcher(r);
+ final ShardState shards = new ShardState(s);
for(int contentID=0;contentID<3;contentID++) {
final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
@@ -549,7 +581,8 @@ public class TestGrouping extends Lucene
final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x"))));
final int[] docIDToID2 = FieldCache.DEFAULT.getInts(r2, "id");
- final IndexSearcher s2 = new IndexSearcher(r2);
+ final IndexSearcher s2 = newSearcher(r2);
+ final ShardState shards2 = new ShardState(s2);
// Reader2 only increases maxDoc() vs reader, which
// means a monotonic shift in scores, so we can
@@ -604,7 +637,7 @@ public class TestGrouping extends Lucene
}
final int topNGroups = _TestUtil.nextInt(random, 1, 30);
- //final int topNGroups = 4;
+ //final int topNGroups = 10;
final int docsPerGroup = _TestUtil.nextInt(random, 1, 50);
final int groupOffset = _TestUtil.nextInt(random, 0, (topNGroups-1)/2);
@@ -658,7 +691,9 @@ public class TestGrouping extends Lucene
}
}
- s.search(new TermQuery(new Term("content", searchTerm)), c);
+ // Search top reader:
+ final Query q = new TermQuery(new Term("content", searchTerm));
+ s.search(q, c);
if (doCache && !useWrappingCollector) {
if (cCache.isCached()) {
@@ -679,6 +714,18 @@ public class TestGrouping extends Lucene
final Collection<SearchGroup<BytesRef>> topGroups = c1.getTopGroups(groupOffset, fillFields);
final TopGroups groupsResult;
+ if (VERBOSE) {
+ System.out.println("TEST: topGroups:");
+ if (topGroups == null) {
+ System.out.println(" null");
+ } else {
+ for(SearchGroup<BytesRef> groupx : topGroups) {
+ System.out.println(" " + groupToString(groupx.groupValue) + " sort=" + Arrays.toString(groupx.sortValues));
+ }
+ }
+ }
+
+ final TopGroups<BytesRef> topGroupsShards = searchShards(s, shards.subSearchers, q, groupSort, docSort, groupOffset, topNGroups, docOffset, docsPerGroup, getScores, getMaxScores);
if (topGroups != null) {
@@ -734,7 +781,13 @@ public class TestGrouping extends Lucene
}
}
}
- assertEquals(docIDToID, expectedGroups, groupsResult, true, getScores);
+ assertEquals(docIDToID, expectedGroups, groupsResult, true, true, true, getScores);
+
+ // Confirm merged shards match:
+ assertEquals(docIDToID, expectedGroups, topGroupsShards, true, false, fillFields, getScores);
+ if (topGroupsShards != null) {
+ verifyShards(shards.docStarts, topGroupsShards);
+ }
final boolean needsScores = getScores || getMaxScores || docSort == null;
final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock);
@@ -758,6 +811,8 @@ public class TestGrouping extends Lucene
groupsResult2 = tempTopGroups2;
}
+ final TopGroups<BytesRef> topGroupsBlockShards = searchShards(s2, shards2.subSearchers, q, groupSort, docSort, groupOffset, topNGroups, docOffset, docsPerGroup, getScores, getMaxScores);
+
if (expectedGroups != null) {
// Fixup scores for reader2
for (GroupDocs groupDocsHits : expectedGroups.groups) {
@@ -799,8 +854,11 @@ public class TestGrouping extends Lucene
}
}
- assertEquals(docIDToID2, expectedGroups, groupsResult2, false, getScores);
+ assertEquals(docIDToID2, expectedGroups, groupsResult2, false, true, true, getScores);
+ assertEquals(docIDToID2, expectedGroups, topGroupsBlockShards, false, false, fillFields, getScores);
}
+ s.close();
+ s2.close();
} finally {
FieldCache.DEFAULT.purge(r);
if (r2 != null) {
@@ -816,7 +874,93 @@ public class TestGrouping extends Lucene
}
}
- private void assertEquals(int[] docIDtoID, TopGroups expected, TopGroups actual, boolean verifyGroupValues, boolean testScores) {
+ private void verifyShards(int[] docStarts, TopGroups<BytesRef> topGroups) {
+ for(GroupDocs group : topGroups.groups) {
+ for(int hitIDX=0;hitIDX<group.scoreDocs.length;hitIDX++) {
+ final ScoreDoc sd = group.scoreDocs[hitIDX];
+ assertEquals("doc=" + sd.doc + " wrong shard",
+ ReaderUtil.subIndex(sd.doc, docStarts),
+ sd.shardIndex);
+ }
+ }
+ }
+
+ private void assertEquals(Collection<SearchGroup<BytesRef>> groups1, Collection<SearchGroup<BytesRef>> groups2, boolean doSortValues) {
+ assertEquals(groups1.size(), groups2.size());
+ final Iterator<SearchGroup<BytesRef>> iter1 = groups1.iterator();
+ final Iterator<SearchGroup<BytesRef>> iter2 = groups2.iterator();
+
+ while(iter1.hasNext()) {
+ assertTrue(iter2.hasNext());
+
+ SearchGroup<BytesRef> group1 = iter1.next();
+ SearchGroup<BytesRef> group2 = iter2.next();
+
+ assertEquals(group1.groupValue, group2.groupValue);
+ if (doSortValues) {
+ assertEquals(group1.sortValues, group2.sortValues);
+ }
+ }
+ assertFalse(iter2.hasNext());
+ }
+
+ private TopGroups<BytesRef> searchShards(IndexSearcher topSearcher, ShardSearcher[] subSearchers, Query query, Sort groupSort, Sort docSort, int groupOffset, int topNGroups, int docOffset,
+ int topNDocs, boolean getScores, boolean getMaxScores) throws Exception {
+
+ // TODO: swap in caching, all groups collector here
+ // too...
+ if (VERBOSE) {
+ System.out.println("TEST: " + subSearchers.length + " shards: " + Arrays.toString(subSearchers));
+ }
+ // Run 1st pass collector to get top groups per shard
+ final Weight w = topSearcher.createNormalizedWeight(query);
+ final List<Collection<SearchGroup<BytesRef>>> shardGroups = new ArrayList<Collection<SearchGroup<BytesRef>>>();
+ for(int shardIDX=0;shardIDX<subSearchers.length;shardIDX++) {
+ final TermFirstPassGroupingCollector c = new TermFirstPassGroupingCollector("group", groupSort, groupOffset+topNGroups);
+ subSearchers[shardIDX].search(w, c);
+ final Collection<SearchGroup<BytesRef>> topGroups = c.getTopGroups(0, true);
+ if (topGroups != null) {
+ if (VERBOSE) {
+ System.out.println(" shard " + shardIDX + " s=" + subSearchers[shardIDX] + " " + topGroups.size() + " groups:");
+ for(SearchGroup<BytesRef> group : topGroups) {
+ System.out.println(" " + groupToString(group.groupValue) + " sort=" + Arrays.toString(group.sortValues));
+ }
+ }
+ shardGroups.add(topGroups);
+ }
+ }
+
+ final Collection<SearchGroup<BytesRef>> mergedTopGroups = SearchGroup.merge(shardGroups, groupOffset, topNGroups, groupSort);
+ if (VERBOSE) {
+ System.out.println(" merged:");
+ if (mergedTopGroups == null) {
+ System.out.println(" null");
+ } else {
+ for(SearchGroup<BytesRef> group : mergedTopGroups) {
+ System.out.println(" " + groupToString(group.groupValue) + " sort=" + Arrays.toString(group.sortValues));
+ }
+ }
+ }
+
+ if (mergedTopGroups != null) {
+
+ // Now 2nd pass:
+ @SuppressWarnings("unchecked")
+ final TopGroups<BytesRef>[] shardTopGroups = new TopGroups[subSearchers.length];
+ for(int shardIDX=0;shardIDX<subSearchers.length;shardIDX++) {
+ final TermSecondPassGroupingCollector c = new TermSecondPassGroupingCollector("group", mergedTopGroups, groupSort, docSort,
+ docOffset + topNDocs, getScores, getMaxScores, true);
+ subSearchers[shardIDX].search(w, c);
+ shardTopGroups[shardIDX] = c.getTopGroups(0);
+ }
+
+ return TopGroups.merge(shardTopGroups, groupSort, docSort, docOffset, topNDocs);
+ } else {
+ return null;
+ }
+ }
+
+ private void assertEquals(int[] docIDtoID, TopGroups expected, TopGroups actual, boolean verifyGroupValues, boolean verifyTotalGroupCount, boolean verifySortValues, boolean testScores) {
if (expected == null) {
assertNull(actual);
return;
@@ -826,7 +970,7 @@ public class TestGrouping extends Lucene
assertEquals(expected.groups.length, actual.groups.length);
assertEquals(expected.totalHitCount, actual.totalHitCount);
assertEquals(expected.totalGroupedHitCount, actual.totalGroupedHitCount);
- if (expected.totalGroupCount != null) {
+ if (expected.totalGroupCount != null && verifyTotalGroupCount) {
assertEquals(expected.totalGroupCount, actual.totalGroupCount);
}
@@ -839,7 +983,9 @@ public class TestGrouping extends Lucene
if (verifyGroupValues) {
assertEquals(expectedGroup.groupValue, actualGroup.groupValue);
}
- assertArrayEquals(expectedGroup.groupSortValues, actualGroup.groupSortValues);
+ if (verifySortValues) {
+ assertArrayEquals(expectedGroup.groupSortValues, actualGroup.groupSortValues);
+ }
// TODO
// assertEquals(expectedGroup.maxScore, actualGroup.maxScore);
@@ -860,8 +1006,32 @@ public class TestGrouping extends Lucene
// TODO: too anal for now
//assertEquals(Float.NaN, actualFD.score);
}
- assertArrayEquals(expectedFD.fields, actualFD.fields);
+ if (verifySortValues) {
+ assertArrayEquals(expectedFD.fields, actualFD.fields);
+ }
}
}
}
+
+ private static class ShardSearcher extends IndexSearcher {
+ private final IndexReader.AtomicReaderContext[] ctx;
+
+ public ShardSearcher(IndexReader.AtomicReaderContext ctx, IndexReader.ReaderContext parent) {
+ super(parent);
+ this.ctx = new IndexReader.AtomicReaderContext[] {ctx};
+ }
+
+ public void search(Weight weight, Collector collector) throws IOException {
+ search(ctx, weight, null, collector);
+ }
+
+ public TopDocs search(Weight weight, int topN) throws IOException {
+ return search(ctx, weight, null, topN);
+ }
+
+ @Override
+ public String toString() {
+ return "ShardSearcher(" + ctx[0] + ")";
+ }
+ }
}
Modified: lucene/dev/branches/flexscoring/modules/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTLookup.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/modules/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTLookup.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/modules/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTLookup.java (original)
+++ lucene/dev/branches/flexscoring/modules/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTLookup.java Thu Jun 16 20:33:59 2011
@@ -24,6 +24,8 @@ import org.apache.lucene.util.fst.Output
import org.apache.lucene.search.suggest.Lookup;
import org.apache.lucene.search.suggest.tst.TSTLookup;
import org.apache.lucene.search.spell.TermFreqIterator;
+import org.apache.lucene.store.InputStreamDataInput;
+import org.apache.lucene.store.OutputStreamDataOutput;
/**
* Finite state automata based implementation of {@link Lookup} query
Modified: lucene/dev/branches/flexscoring/solr/CHANGES.txt
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/CHANGES.txt?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/CHANGES.txt (original)
+++ lucene/dev/branches/flexscoring/solr/CHANGES.txt Thu Jun 16 20:33:59 2011
@@ -268,7 +268,16 @@ Other Changes
* SOLR-2576: Remove deprecated SpellingResult.add(Token, int).
(James Dyer via rmuir)
-
+
+* LUCENE-3204: The maven-ant-tasks jar is now included in the source tree;
+ users of the generate-maven-artifacts target no longer have to manually
+ place this jar in the Ant classpath. NOTE: when Ant looks for the
+ maven-ant-tasks jar, it looks first in its pre-existing classpath, so
+ any copies it finds will be used instead of the copy included in the
+ Lucene/Solr source tree. For this reason, it is recommeded to remove
+ any copies of the maven-ant-tasks jar in the Ant classpath, e.g. under
+ ~/.ant/lib/ or under the Ant installation's lib/ directory. (Steve Rowe)
+
Documentation
----------------------
@@ -285,6 +294,12 @@ New Features
compared to ternary trees and jaspell and very fast lookups at runtime.
(Dawid Weiss)
+* SOLR-2400: Field- and DocumentAnalysisRequestHandler now provide a position
+ history for each token, so you can follow the token through all analysis stages.
+ The output contains a separate int[] attribute containing all positions from
+ previous Tokenizers/TokenFilters (called "positionHistory").
+ (Uwe Schindler)
+
Optimizations
----------------------
Modified: lucene/dev/branches/flexscoring/solr/build.xml
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/build.xml?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/build.xml (original)
+++ lucene/dev/branches/flexscoring/solr/build.xml Thu Jun 16 20:33:59 2011
@@ -996,7 +996,10 @@
<target name="stage" depends="prepare-release, copy-to-stage"/>
- <target name="generate-maven-artifacts" depends="maven.ant.tasks-check,dist,dist-src,dist-javadoc">
+ <target name="generate-maven-artifacts" depends="dist,dist-src,dist-javadoc">
+ <taskdef uri="antlib:org.apache.maven.artifact.ant"
+ resource="org/apache/maven/artifact/ant/antlib.xml"
+ classpathref="maven-ant-tasks.classpath" />
<sequential>
<ant target="get-maven-poms" dir=".."/>
Modified: lucene/dev/branches/flexscoring/solr/common-build.xml
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/common-build.xml?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/common-build.xml (original)
+++ lucene/dev/branches/flexscoring/solr/common-build.xml Thu Jun 16 20:33:59 2011
@@ -133,7 +133,7 @@
<property name="javadoc.link.junit"
value="http://junit.sourceforge.net/javadoc/"/>
<property name="javadoc.link.lucene"
- value="https://hudson.apache.org/hudson/job/Lucene-trunk/javadoc/all/"/>
+ value="https://builds.apache.org/job/Lucene-trunk/javadoc/all/"/>
<property name="javadoc.packages" value="org.apache.solr.*"/>
<property name="build.docs" value="${dest}/docs"/>
<property name="build.javadoc" value="${common-solr.dir}/${build.docs}/api"/>
@@ -168,7 +168,11 @@
<property name="m2.repository.url" value="file://${maven.dist.dir}"/>
<property name="m2.repository.private.key" value="${user.home}/.ssh/id_dsa"/>
- <available property="maven.ant.tasks.present" classname="org.apache.maven.artifact.ant.Pom" />
+ <path id="maven-ant-tasks.classpath">
+ <fileset dir="${common-solr.dir}/../lucene/lib">
+ <include name="maven-ant-tasks-*.jar"/>
+ </fileset>
+ </path>
<!-- End Maven Properties -->
@@ -587,19 +591,6 @@
</manifest>
</target>
- <target name="maven.ant.tasks-check">
- <fail unless="maven.ant.tasks.present">#
- ##########################################################################
- Maven ant tasks not found.
-
- Please download the Maven ant tasks JAR (maven-ant-tasks-2.1.1.jar)
- from http://maven.apache.org/ant-tasks/download.html and add it to your
- $$HOME/.ant/lib/ directory, or to your $$ANT_HOME/lib/ directory, or
- to your $$CLASSPATH, or add "-lib /path/to/maven-ant-tasks-2.1.1.jar"
- to the ant command.
- ##########################################################################
- </fail>
- </target>
<!-- Validation -->
<target name="validate" depends="validate-solr"/>
<target name="validate-solr" depends="check-legal-solr" unless="validated-solr"/>
Modified: lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/CHANGES.txt
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/CHANGES.txt?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/CHANGES.txt (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/CHANGES.txt Thu Jun 16 20:33:59 2011
@@ -14,7 +14,8 @@ $Id$
================== 3.3.0-dev ==============
-(No Changes)
+* SOLR-2551: Check dataimport.properties for write access (if delta-import is supported
+ in DIH configuration) before starting an import (C S, shalin)
================== 3.2.0 ==================
Modified: lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/extras/main/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/extras/main/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/extras/main/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/extras/main/java/org/apache/solr/handler/dataimport/MailEntityProcessor.java Thu Jun 16 20:33:59 2011
@@ -90,7 +90,9 @@ public class MailEntityProcessor extends
fetchSize = getIntFromContext("fetchSize", 32 * 1024);
cTimeout = getIntFromContext("connectTimeout", 30 * 1000);
rTimeout = getIntFromContext("readTimeout", 60 * 1000);
- processAttachment = getBoolFromContext("processAttachement", true);
+ processAttachment = getBoolFromContext(
+ getStringFromContext("processAttachment",null) == null ? "processAttachement":"processAttachment"
+ , true);
logConfig();
}
Modified: lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/DataImporter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/DataImporter.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/DataImporter.java (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/DataImporter.java Thu Jun 16 20:33:59 2011
@@ -39,6 +39,7 @@ import org.apache.commons.io.IOUtils;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
+import java.io.File;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.*;
@@ -84,6 +85,8 @@ public class DataImporter {
private final Map<String , Object> coreScopeSession;
+ private boolean isDeltaImportSupported = false;
+
/**
* Only for testing purposes
*/
@@ -112,7 +115,9 @@ public class DataImporter {
initEntity(e, fields, false);
verifyWithSchema(fields);
identifyPk(e);
- }
+ if (e.allAttributes.containsKey(SqlEntityProcessor.DELTA_QUERY))
+ isDeltaImportSupported = true;
+ }
}
private void verifyWithSchema(Map<String, DataConfig.Field> fields) {
@@ -349,6 +354,7 @@ public class DataImporter {
try {
docBuilder = new DocBuilder(this, writer, requestParams);
+ checkWritablePersistFile(writer);
docBuilder.execute();
if (!requestParams.debug)
cumulativeStatistics.add(docBuilder.importStatistics);
@@ -363,6 +369,15 @@ public class DataImporter {
}
+ private void checkWritablePersistFile(SolrWriter writer) {
+ File persistFile = writer.getPersistFile();
+ boolean isWritable = persistFile.exists() ? persistFile.canWrite() : persistFile.getParentFile().canWrite();
+ if (isDeltaImportSupported && !isWritable) {
+ throw new DataImportHandlerException(SEVERE, persistFile.getAbsolutePath() +
+ " is not writable. Delta imports are supported by data config but will not work.");
+ }
+ }
+
public void doDeltaImport(SolrWriter writer, RequestParams requestParams) {
LOG.info("Starting Delta Import");
setStatus(Status.RUNNING_DELTA_DUMP);
@@ -370,6 +385,7 @@ public class DataImporter {
try {
setIndexStartTime(new Date());
docBuilder = new DocBuilder(this, writer, requestParams);
+ checkWritablePersistFile(writer);
docBuilder.execute();
if (!requestParams.debug)
cumulativeStatistics.add(docBuilder.importStatistics);
Modified: lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/SolrWriter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/SolrWriter.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/SolrWriter.java (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/SolrWriter.java Thu Jun 16 20:33:59 2011
@@ -99,13 +99,10 @@ public class SolrWriter {
try {
props.putAll(p);
- String filePath = configDir;
- if (configDir != null && !configDir.endsWith(File.separator))
- filePath += File.separator;
- filePath += persistFilename;
- propOutput = new FileOutputStream(filePath);
+ File persistFile = getPersistFile();
+ propOutput = new FileOutputStream(persistFile);
props.store(propOutput, null);
- log.info("Wrote last indexed time to " + persistFilename);
+ log.info("Wrote last indexed time to " + persistFile.getAbsolutePath());
} catch (FileNotFoundException e) {
throw new DataImportHandlerException(DataImportHandlerException.SEVERE,
"Unable to persist Index Start Time", e);
@@ -122,6 +119,14 @@ public class SolrWriter {
}
}
+ File getPersistFile() {
+ String filePath = configDir;
+ if (configDir != null && !configDir.endsWith(File.separator))
+ filePath += File.separator;
+ filePath += persistFilename;
+ return new File(filePath);
+ }
+
void finish() {
try {
processor.finish();
Modified: lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/TestSqlEntityProcessorDelta.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/TestSqlEntityProcessorDelta.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/TestSqlEntityProcessorDelta.java (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/TestSqlEntityProcessorDelta.java Thu Jun 16 20:33:59 2011
@@ -20,6 +20,8 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
+import java.io.File;
+import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -92,7 +94,37 @@ public class TestSqlEntityProcessorDelta
public void testCompositePk_FullImport() throws Exception {
add1document();
}
-
+
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testNonWritablePersistFile() throws Exception {
+ // See SOLR-2551
+ String configDir = h.getCore().getResourceLoader().getConfigDir();
+ String filePath = configDir;
+ if (configDir != null && !configDir.endsWith(File.separator))
+ filePath += File.separator;
+ filePath += "dataimport.properties";
+ File f = new File(filePath);
+ // execute the test only if we are able to set file to read only mode
+ if ((f.exists() || f.createNewFile()) && f.setReadOnly()) {
+ try {
+ List parentRow = new ArrayList();
+ parentRow.add(createMap("id", "1"));
+ MockDataSource.setIterator(FULLIMPORT_QUERY, parentRow.iterator());
+
+ List childRow = new ArrayList();
+ childRow.add(createMap("desc", "hello"));
+ MockDataSource.setIterator("select * from y where y.A='1'", childRow
+ .iterator());
+
+ runFullImport(dataConfig_delta);
+ assertQ(req("id:1"), "//*[@numFound='0']");
+ } finally {
+ f.setWritable(true);
+ }
+ }
+ }
+
// WORKS
@Test
Modified: lucene/dev/branches/flexscoring/solr/contrib/uima/CHANGES.txt
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/uima/CHANGES.txt?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/uima/CHANGES.txt (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/uima/CHANGES.txt Thu Jun 16 20:33:59 2011
@@ -24,6 +24,12 @@ $Id$
(No Changes)
================== 3.3.0-dev ==============
+
+New Features
+----------------------
+
+* SOLR-2582: Use uniqueKey for error log in UIMAUpdateRequestProcessor.
+ (Tommaso Teofili via koji)
Bug Fixes
----------------------
@@ -31,6 +37,9 @@ Bug Fixes
* SOLR-2579: UIMAUpdateRequestProcessor ignore error fails if text.length() < 100.
(Elmer Garduno via koji)
+* SOLR-2581: UIMAToSolrMapper wrongly instantiates Type with reflection.
+ (Tommaso Teofili via koji)
+
================== 3.2.0 ==================
Upgrading from Solr 3.1
Modified: lucene/dev/branches/flexscoring/solr/contrib/uima/README.txt
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/uima/README.txt?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/uima/README.txt (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/uima/README.txt Thu Jun 16 20:33:59 2011
@@ -35,8 +35,9 @@ To start using Solr UIMA Metadata Extrac
never indexed documents entirely in your session. -->
<bool name="ignoreErrors">true</bool>
<!-- This is optional. It is used for logging when text processing fails.
- Usually, set uniqueKey field name -->
+ If logField is not specified, uniqueKey will be used as logField.
<str name="logField">id</str>
+ -->
<lst name="analyzeFields">
<bool name="merge">false</bool>
<arr name="fields">
Modified: lucene/dev/branches/flexscoring/solr/contrib/uima/src/main/java/org/apache/solr/uima/processor/UIMAToSolrMapper.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/uima/src/main/java/org/apache/solr/uima/processor/UIMAToSolrMapper.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/uima/src/main/java/org/apache/solr/uima/processor/UIMAToSolrMapper.java (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/uima/src/main/java/org/apache/solr/uima/processor/UIMAToSolrMapper.java Thu Jun 16 20:33:59 2011
@@ -21,6 +21,7 @@ import java.util.Map;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.uima.processor.SolrUIMAConfiguration.MapField;
+import org.apache.solr.uima.processor.exception.FieldMappingException;
import org.apache.uima.cas.FSIterator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.Type;
@@ -49,27 +50,24 @@ public class UIMAToSolrMapper {
/**
* map features of a certain UIMA type to corresponding Solr fields based on the mapping
- *
- * @param typeName
- * name of UIMA type to map
+ *
+ * @param typeName name of UIMA type to map
* @param featureFieldsmapping
*/
- public void map(String typeName, Map<String, MapField> featureFieldsmapping) {
+ public void map(String typeName, Map<String, MapField> featureFieldsmapping) throws FieldMappingException {
try {
- FeatureStructure fsMock = (FeatureStructure) Class.forName(typeName).getConstructor(
- JCas.class).newInstance(cas);
- Type type = fsMock.getType();
+ Type type = cas.getTypeSystem().getType(typeName);
for (FSIterator<FeatureStructure> iterator = cas.getFSIndexRepository().getAllIndexedFS(type); iterator
- .hasNext();) {
+ .hasNext(); ) {
FeatureStructure fs = iterator.next();
for (String featureName : featureFieldsmapping.keySet()) {
MapField mapField = featureFieldsmapping.get(featureName);
String fieldNameFeature = mapField.getFieldNameFeature();
String fieldNameFeatureValue = fieldNameFeature == null ? null :
- fs.getFeatureValueAsString(type.getFeatureByBaseName(fieldNameFeature));
+ fs.getFeatureValueAsString(type.getFeatureByBaseName(fieldNameFeature));
String fieldName = mapField.getFieldName(fieldNameFeatureValue);
log.info(new StringBuffer("mapping ").append(typeName).append("@").append(featureName)
- .append(" to ").append(fieldName).toString());
+ .append(" to ").append(fieldName).toString());
String featureValue = null;
if (fs instanceof Annotation && "coveredText".equals(featureName)) {
featureValue = ((Annotation) fs).getCoveredText();
@@ -77,12 +75,13 @@ public class UIMAToSolrMapper {
featureValue = fs.getFeatureValueAsString(type.getFeatureByBaseName(featureName));
}
log.info(new StringBuffer("writing ").append(featureValue).append(" in ").append(
- fieldName).toString());
+ fieldName).toString());
document.addField(fieldName, featureValue, 1.0f);
}
}
} catch (Exception e) {
- log.error(e.getLocalizedMessage());
+ throw new FieldMappingException(e);
}
}
+
}
Modified: lucene/dev/branches/flexscoring/solr/contrib/uima/src/main/java/org/apache/solr/uima/processor/UIMAUpdateRequestProcessor.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/uima/src/main/java/org/apache/solr/uima/processor/UIMAUpdateRequestProcessor.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/uima/src/main/java/org/apache/solr/uima/processor/UIMAUpdateRequestProcessor.java (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/uima/src/main/java/org/apache/solr/uima/processor/UIMAUpdateRequestProcessor.java Thu Jun 16 20:33:59 2011
@@ -17,24 +17,24 @@ package org.apache.solr.uima.processor;
* limitations under the License.
*/
-import java.io.IOException;
-import java.util.Map;
-
import org.apache.solr.common.SolrException;
-import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrException.ErrorCode;
+import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.core.SolrCore;
+import org.apache.solr.schema.SchemaField;
import org.apache.solr.uima.processor.SolrUIMAConfiguration.MapField;
import org.apache.solr.uima.processor.ae.AEProvider;
import org.apache.solr.uima.processor.ae.AEProviderFactory;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.processor.UpdateRequestProcessor;
-import org.apache.uima.UIMAException;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
+import java.io.IOException;
+import java.util.Map;
+
/**
* Update document(s) to be indexed with UIMA extracted information
*
@@ -45,6 +45,8 @@ public class UIMAUpdateRequestProcessor
SolrUIMAConfiguration solrUIMAConfiguration;
private AEProvider aeProvider;
+
+ private SolrCore solrCore;
public UIMAUpdateRequestProcessor(UpdateRequestProcessor next, SolrCore solrCore,
SolrUIMAConfiguration config) {
@@ -53,6 +55,7 @@ public class UIMAUpdateRequestProcessor
}
private void initialize(SolrCore solrCore, SolrUIMAConfiguration config) {
+ this.solrCore = solrCore;
solrUIMAConfiguration = config;
aeProvider = AEProviderFactory.getInstance().getAEProvider(solrCore.getName(),
solrUIMAConfiguration.getAePath(), solrUIMAConfiguration.getRuntimeParameters());
@@ -69,7 +72,7 @@ public class UIMAUpdateRequestProcessor
String[] texts = getTextsToAnalyze(solrInputDocument);
for (int i = 0; i < texts.length; i++) {
text = texts[i];
- if (text != null && !"".equals(text)) {
+ if (text != null && text.length()>0) {
/* process the text value */
JCas jcas = processText(text);
@@ -83,8 +86,14 @@ public class UIMAUpdateRequestProcessor
}
}
}
- } catch (UIMAException e) {
+ } catch (Exception e) {
String logField = solrUIMAConfiguration.getLogField();
+ if(logField == null){
+ SchemaField uniqueKeyField = solrCore.getSchema().getUniqueKeyField();
+ if(uniqueKeyField != null){
+ logField = uniqueKeyField.getName();
+ }
+ }
String optionalFieldInfo = logField == null ? "." :
new StringBuilder(". ").append(logField).append("=")
.append((String)cmd.getSolrInputDocument().getField(logField).getValue())
@@ -110,7 +119,7 @@ public class UIMAUpdateRequestProcessor
private String[] getTextsToAnalyze(SolrInputDocument solrInputDocument) {
String[] fieldsToAnalyze = solrUIMAConfiguration.getFieldsToAnalyze();
boolean merge = solrUIMAConfiguration.isFieldsMerging();
- String[] textVals = null;
+ String[] textVals;
if (merge) {
StringBuilder unifiedText = new StringBuilder("");
for (int i = 0; i < fieldsToAnalyze.length; i++) {
Modified: lucene/dev/branches/flexscoring/solr/contrib/uima/src/test/resources/solr-uima/conf/solrconfig.xml
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/contrib/uima/src/test/resources/solr-uima/conf/solrconfig.xml?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/contrib/uima/src/test/resources/solr-uima/conf/solrconfig.xml (original)
+++ lucene/dev/branches/flexscoring/solr/contrib/uima/src/test/resources/solr-uima/conf/solrconfig.xml Thu Jun 16 20:33:59 2011
@@ -24,9 +24,7 @@
https://issues.apache.org/jira/browse/SOLR-1167
-->
<config xmlns:xi="http://www.w3.org/2001/XInclude">
-
- <luceneMatchVersion>LUCENE_40</luceneMatchVersion>
-
+ <luceneMatchVersion>${tests.luceneMatchVersion:LUCENE_CURRENT}</luceneMatchVersion>
<!--
lib directives can be used to instruct Solr to load an Jars
identified and use them to resolve any "plugins" specified in your
@@ -1064,8 +1062,6 @@
</lst>
<str name="analysisEngine">/TestExceptionAE.xml</str>
<bool name="ignoreErrors">true</bool>
- <!-- This is optional. It is used for logging when text processing fails. Usually, set uniqueKey field name -->
- <str name="logField">id</str>
<lst name="analyzeFields">
<bool name="merge">false</bool>
<arr name="fields">
Modified: lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java (original)
+++ lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java Thu Jun 16 20:33:59 2011
@@ -25,10 +25,11 @@ import org.apache.lucene.analysis.tokena
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.index.Payload;
import org.apache.lucene.util.Attribute;
+import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.AttributeReflector;
import org.apache.lucene.util.CharsRef;
-import org.apache.lucene.util.SorterTemplate;
+import org.apache.lucene.util.ArrayUtil;
import org.apache.solr.analysis.CharFilterFactory;
import org.apache.solr.analysis.TokenFilterFactory;
import org.apache.solr.analysis.TokenizerChain;
@@ -43,6 +44,7 @@ import org.apache.solr.schema.FieldType;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
+import org.apache.commons.lang.ArrayUtils;
/**
* A base class for all analysis request handlers.
@@ -120,10 +122,13 @@ public abstract class AnalysisRequestHan
ListBasedTokenStream listBasedTokenStream = new ListBasedTokenStream(tokens);
for (TokenFilterFactory tokenFilterFactory : filtfacs) {
+ for (final AttributeSource tok : tokens) {
+ tok.getAttribute(TokenTrackingAttribute.class).freezeStage();
+ }
tokenStream = tokenFilterFactory.create(listBasedTokenStream);
- List<AttributeSource> tokenList = analyzeTokenStream(tokenStream);
- namedList.add(tokenStream.getClass().getName(), convertTokensToNamedLists(tokenList, context));
- listBasedTokenStream = new ListBasedTokenStream(tokenList);
+ tokens = analyzeTokenStream(tokenStream);
+ namedList.add(tokenStream.getClass().getName(), convertTokensToNamedLists(tokens, context));
+ listBasedTokenStream = new ListBasedTokenStream(tokens);
}
return namedList;
@@ -160,15 +165,19 @@ public abstract class AnalysisRequestHan
* @return List of tokens produced from the TokenStream
*/
private List<AttributeSource> analyzeTokenStream(TokenStream tokenStream) {
- List<AttributeSource> tokens = new ArrayList<AttributeSource>();
+ final List<AttributeSource> tokens = new ArrayList<AttributeSource>();
+ final PositionIncrementAttribute posIncrAtt = tokenStream.addAttribute(PositionIncrementAttribute.class);
+ final TokenTrackingAttribute trackerAtt = tokenStream.addAttribute(TokenTrackingAttribute.class);
// for backwards compatibility, add all "common" attributes
- tokenStream.addAttribute(PositionIncrementAttribute.class);
tokenStream.addAttribute(OffsetAttribute.class);
tokenStream.addAttribute(TypeAttribute.class);
final BytesRef bytes = new BytesRef();
try {
tokenStream.reset();
+ int position = 0;
while (tokenStream.incrementToken()) {
+ position += posIncrAtt.getPositionIncrement();
+ trackerAtt.setActPosition(position);
tokens.add(tokenStream.cloneAttributes());
}
} catch (IOException ioe) {
@@ -183,6 +192,8 @@ public abstract class AnalysisRequestHan
put(OffsetAttribute.class.getName() + "#startOffset", "start");
put(OffsetAttribute.class.getName() + "#endOffset", "end");
put(TypeAttribute.class.getName() + "#type", "type");
+ put(TokenTrackingAttribute.class.getName() + "#position", "position");
+ put(TokenTrackingAttribute.class.getName() + "#positionHistory", "positionHistory");
}});
/**
@@ -193,49 +204,35 @@ public abstract class AnalysisRequestHan
*
* @return List of NamedLists containing the relevant information taken from the tokens
*/
- private List<NamedList> convertTokensToNamedLists(final List<AttributeSource> tokens, AnalysisContext context) {
+ private List<NamedList> convertTokensToNamedLists(final List<AttributeSource> tokenList, AnalysisContext context) {
final List<NamedList> tokensNamedLists = new ArrayList<NamedList>();
-
- final int[] positions = new int[tokens.size()];
- int position = 0;
- for (int i = 0, c = tokens.size(); i < c; i++) {
- AttributeSource token = tokens.get(i);
- position += token.addAttribute(PositionIncrementAttribute.class).getPositionIncrement();
- positions[i] = position;
- }
+ final FieldType fieldType = context.getFieldType();
+ final AttributeSource[] tokens = tokenList.toArray(new AttributeSource[tokenList.size()]);
// sort the tokens by absoulte position
- new SorterTemplate() {
- @Override
- protected void swap(int i, int j) {
- final int p = positions[i];
- positions[i] = positions[j];
- positions[j] = p;
- Collections.swap(tokens, i, j);
+ ArrayUtil.mergeSort(tokens, new Comparator<AttributeSource>() {
+ public int compare(AttributeSource a, AttributeSource b) {
+ return arrayCompare(
+ a.getAttribute(TokenTrackingAttribute.class).getPositions(),
+ b.getAttribute(TokenTrackingAttribute.class).getPositions()
+ );
}
- @Override
- protected int compare(int i, int j) {
- return positions[i] - positions[j];
- }
-
- @Override
- protected void setPivot(int i) {
- pivot = positions[i];
- }
-
- @Override
- protected int comparePivot(int j) {
- return pivot - positions[j];
+ private int arrayCompare(int[] a, int[] b) {
+ int p = 0;
+ final int stop = Math.min(a.length, b.length);
+ while(p < stop) {
+ int diff = a[p] - b[p];
+ if (diff != 0) return diff;
+ p++;
+ }
+ // One is a prefix of the other, or, they are equal:
+ return a.length - b.length;
}
-
- private int pivot;
- }.mergeSort(0, tokens.size() - 1);
+ });
- FieldType fieldType = context.getFieldType();
-
- for (int i = 0, c = tokens.size(); i < c; i++) {
- AttributeSource token = tokens.get(i);
+ for (int i = 0; i < tokens.length; i++) {
+ AttributeSource token = tokens[i];
final NamedList<Object> tokenNamedList = new SimpleOrderedMap<Object>();
final TermToBytesRefAttribute termAtt = token.getAttribute(TermToBytesRefAttribute.class);
BytesRef rawBytes = termAtt.getBytesRef();
@@ -256,8 +253,6 @@ public abstract class AnalysisRequestHan
tokenNamedList.add("match", true);
}
- tokenNamedList.add("position", positions[i]);
-
token.reflectWith(new AttributeReflector() {
public void reflect(Class<? extends Attribute> attClass, String key, Object value) {
// leave out position and bytes term
@@ -312,8 +307,8 @@ public abstract class AnalysisRequestHan
/**
* TokenStream that iterates over a list of pre-existing Tokens
+ * @lucene.internal
*/
- // TODO refactor to support custom attributes
protected final static class ListBasedTokenStream extends TokenStream {
private final List<AttributeSource> tokens;
private Iterator<AttributeSource> tokenIterator;
@@ -350,6 +345,68 @@ public abstract class AnalysisRequestHan
}
}
+ /** This is an {@link Attribute} used to track the positions of tokens
+ * in the analysis chain.
+ * @lucene.internal This class is only public for usage by the {@link AttributeSource} API.
+ */
+ public interface TokenTrackingAttribute extends Attribute {
+ void freezeStage();
+ void setActPosition(int pos);
+ int[] getPositions();
+ void reset(int[] basePositions, int position);
+ }
+
+ /** Implementation of {@link TokenTrackingAttribute}.
+ * @lucene.internal This class is only public for usage by the {@link AttributeSource} API.
+ */
+ public static final class TokenTrackingAttributeImpl extends AttributeImpl implements TokenTrackingAttribute {
+ private int[] basePositions = new int[0];
+ private int position = 0;
+ private transient int[] cachedPositions = null;
+
+ public void freezeStage() {
+ this.basePositions = getPositions();
+ this.position = 0;
+ this.cachedPositions = null;
+ }
+
+ public void setActPosition(int pos) {
+ this.position = pos;
+ this.cachedPositions = null;
+ }
+
+ public int[] getPositions() {
+ if (cachedPositions == null) {
+ cachedPositions = ArrayUtils.add(basePositions, position);
+ }
+ return cachedPositions;
+ }
+
+ public void reset(int[] basePositions, int position) {
+ this.basePositions = basePositions;
+ this.position = position;
+ this.cachedPositions = null;
+ }
+
+ @Override
+ public void clear() {
+ // we do nothing here, as all attribute values are controlled externally by consumer
+ }
+
+ @Override
+ public void reflectWith(AttributeReflector reflector) {
+ reflector.reflect(TokenTrackingAttribute.class, "position", position);
+ // convert to Integer[] array, as only such one can be serialized by ResponseWriters
+ reflector.reflect(TokenTrackingAttribute.class, "positionHistory", ArrayUtils.toObject(getPositions()));
+ }
+
+ @Override
+ public void copyTo(AttributeImpl target) {
+ final TokenTrackingAttribute t = (TokenTrackingAttribute) target;
+ t.reset(basePositions, position);
+ }
+ }
+
/**
* Serves as the context of an analysis process. This context contains the following constructs
*/
Modified: lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/component/QueryElevationComponent.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/component/QueryElevationComponent.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/component/QueryElevationComponent.java (original)
+++ lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/component/QueryElevationComponent.java Thu Jun 16 20:33:59 2011
@@ -476,8 +476,8 @@ class ElevationComparatorSource extends
}
@Override
- public FieldComparator newComparator(final String fieldname, final int numHits, int sortPos, boolean reversed) throws IOException {
- return new FieldComparator() {
+ public FieldComparator<Integer> newComparator(final String fieldname, final int numHits, int sortPos, boolean reversed) throws IOException {
+ return new FieldComparator<Integer>() {
FieldCache.DocTermsIndex idIndex;
private final int[] values = new int[numHits];
@@ -517,7 +517,7 @@ class ElevationComparatorSource extends
}
@Override
- public Comparable value(int slot) {
+ public Integer value(int slot) {
return values[slot];
}
};
Modified: lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/component/StatsComponent.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/component/StatsComponent.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/component/StatsComponent.java (original)
+++ lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/handler/component/StatsComponent.java Thu Jun 16 20:33:59 2011
@@ -24,7 +24,6 @@ import java.util.Map;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
-import org.apache.noggit.CharArr;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.StatsParams;
import org.apache.solr.common.params.ShardParams;
Modified: lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/response/transform/ValueSourceAugmenter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/response/transform/ValueSourceAugmenter.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/response/transform/ValueSourceAugmenter.java (original)
+++ lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/response/transform/ValueSourceAugmenter.java Thu Jun 16 20:33:59 2011
@@ -59,12 +59,17 @@ public class ValueSourceAugmenter extend
@Override
public void setContext( TransformContext context ) {
- IndexReader reader = qparser.getReq().getSearcher().getIndexReader();
- readerContexts = reader.getTopReaderContext().leaves();
- docValuesArr = new DocValues[readerContexts.length];
-
- searcher = qparser.getReq().getSearcher();
- this.fcontext = ValueSource.newContext(searcher);
+ try {
+ IndexReader reader = qparser.getReq().getSearcher().getIndexReader();
+ readerContexts = reader.getTopReaderContext().leaves();
+ docValuesArr = new DocValues[readerContexts.length];
+
+ searcher = qparser.getReq().getSearcher();
+ fcontext = ValueSource.newContext(searcher);
+ this.valueSource.createWeight(fcontext, searcher);
+ } catch (IOException e) {
+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
+ }
}
Modified: lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/schema/RandomSortField.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/schema/RandomSortField.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/schema/RandomSortField.java (original)
+++ lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/schema/RandomSortField.java Thu Jun 16 20:33:59 2011
@@ -102,8 +102,8 @@ public class RandomSortField extends Fie
private static FieldComparatorSource randomComparatorSource = new FieldComparatorSource() {
@Override
- public FieldComparator newComparator(final String fieldname, final int numHits, int sortPos, boolean reversed) throws IOException {
- return new FieldComparator() {
+ public FieldComparator<Integer> newComparator(final String fieldname, final int numHits, int sortPos, boolean reversed) throws IOException {
+ return new FieldComparator<Integer>() {
int seed;
private final int[] values = new int[numHits];
int bottomVal;
@@ -135,7 +135,7 @@ public class RandomSortField extends Fie
}
@Override
- public Comparable value(int slot) {
+ public Integer value(int slot) {
return values[slot];
}
};
Modified: lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java?rev=1136656&r1=1136655&r2=1136656&view=diff
==============================================================================
--- lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java (original)
+++ lucene/dev/branches/flexscoring/solr/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java Thu Jun 16 20:33:59 2011
@@ -56,7 +56,7 @@ public class MissingStringLastComparator
// Copied from Lucene's TermOrdValComparator and modified since the Lucene version couldn't
// be extended.
-class TermOrdValComparator_SML extends FieldComparator {
+class TermOrdValComparator_SML extends FieldComparator<BytesRef> {
private static final int NULL_ORD = Integer.MAX_VALUE;
private final int[] ords;
@@ -98,7 +98,7 @@ class TermOrdValComparator_SML extends F
}
@Override
- public Comparable<?> value(int slot) {
+ public BytesRef value(int slot) {
throw new UnsupportedOperationException();
}
@@ -111,7 +111,7 @@ class TermOrdValComparator_SML extends F
// ords) per-segment comparator. NOTE: this is messy;
// we do this only because hotspot can't reliably inline
// the underlying array access when looking up doc->ord
- private static abstract class PerSegmentComparator extends FieldComparator {
+ private static abstract class PerSegmentComparator extends FieldComparator<BytesRef> {
protected TermOrdValComparator_SML parent;
protected final int[] ords;
protected final BytesRef[] values;
@@ -199,7 +199,7 @@ class TermOrdValComparator_SML extends F
}
@Override
- public Comparable<?> value(int slot) {
+ public BytesRef value(int slot) {
return values==null ? parent.NULL_VAL : values[slot];
}
}