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 2012/12/10 17:37:54 UTC
svn commit: r1419570 [6/14] - in /lucene/dev/branches/lucene4547: ./
dev-tools/ dev-tools/eclipse/ dev-tools/idea/.idea/libraries/
dev-tools/idea/lucene/analysis/icu/
dev-tools/idea/solr/contrib/dataimporthandler/ dev-tools/maven/
dev-tools/maven/lucen...
Modified: lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyCombined.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyCombined.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyCombined.java (original)
+++ lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyCombined.java Mon Dec 10 16:36:47 2012
@@ -5,18 +5,18 @@ import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
+import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
+import org.apache.lucene.facet.taxonomy.directory.ParallelTaxonomyArrays;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
-import org.junit.Ignore;
-import org.junit.Test;
-
import org.apache.lucene.util.LuceneTestCase;
-import org.apache.lucene.facet.taxonomy.TaxonomyReader.ChildrenArrays;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
+import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
import org.apache.lucene.util.SlowRAMDirectory;
+import org.junit.Test;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -35,6 +35,8 @@ import org.apache.lucene.util.SlowRAMDir
* limitations under the License.
*/
+// TODO: remove this suppress if we fix the TaxoWriter Codec to a non-default (see todo in DirTW)
+@SuppressCodecs("SimpleText")
public class TestTaxonomyCombined extends LuceneTestCase {
/** The following categories will be added to the taxonomy by
@@ -544,7 +546,7 @@ public class TestTaxonomyCombined extend
fillTaxonomy(tw);
tw.close();
TaxonomyReader tr = new DirectoryTaxonomyReader(indexDir);
- int[] parents = tr.getParentArray();
+ int[] parents = tr.getParallelTaxonomyArrays().parents();
assertEquals(tr.getSize(), parents.length);
for (int i=0; i<tr.getSize(); i++) {
assertEquals(tr.getParent(i), parents[i]);
@@ -565,10 +567,10 @@ public class TestTaxonomyCombined extend
fillTaxonomy(tw);
tw.close();
TaxonomyReader tr = new DirectoryTaxonomyReader(indexDir);
- ChildrenArrays ca = tr.getChildrenArrays();
- int[] youngestChildArray = ca.getYoungestChildArray();
+ ParallelTaxonomyArrays ca = tr.getParallelTaxonomyArrays();
+ int[] youngestChildArray = ca.children();
assertEquals(tr.getSize(), youngestChildArray.length);
- int[] olderSiblingArray = ca.getOlderSiblingArray();
+ int[] olderSiblingArray = ca.siblings();
assertEquals(tr.getSize(), olderSiblingArray.length);
for (int i=0; i<expectedCategories.length; i++) {
// find expected children by looking at all expectedCategories
@@ -629,15 +631,15 @@ public class TestTaxonomyCombined extend
fillTaxonomy(tw);
tw.close();
TaxonomyReader tr = new DirectoryTaxonomyReader(indexDir);
- ChildrenArrays ca = tr.getChildrenArrays();
- int[] youngestChildArray = ca.getYoungestChildArray();
- assertEquals(tr.getSize(), youngestChildArray.length);
- int[] olderSiblingArray = ca.getOlderSiblingArray();
+ ParallelTaxonomyArrays ca = tr.getParallelTaxonomyArrays();
+ int[] children = ca.children();
+ assertEquals(tr.getSize(), children.length);
+ int[] olderSiblingArray = ca.siblings();
assertEquals(tr.getSize(), olderSiblingArray.length);
// test that the "youngest child" of every category is indeed a child:
for (int i=0; i<tr.getSize(); i++) {
- int youngestChild = youngestChildArray[i];
+ int youngestChild = children[i];
if (youngestChild != TaxonomyReader.INVALID_ORDINAL) {
assertEquals(i, tr.getParent(youngestChild));
}
@@ -675,7 +677,7 @@ public class TestTaxonomyCombined extend
if (j==i) { // no child found
j=TaxonomyReader.INVALID_ORDINAL;
}
- assertEquals(j, youngestChildArray[i]);
+ assertEquals(j, children[i]);
}
// test that the "older sibling" is indeed the least oldest one - and
@@ -709,42 +711,42 @@ public class TestTaxonomyCombined extend
tw.addCategory(new CategoryPath("hi", "there"));
tw.commit();
TaxonomyReader tr = new DirectoryTaxonomyReader(indexDir);
- ChildrenArrays ca = tr.getChildrenArrays();
+ ParallelTaxonomyArrays ca = tr.getParallelTaxonomyArrays();
assertEquals(3, tr.getSize());
- assertEquals(3, ca.getOlderSiblingArray().length);
- assertEquals(3, ca.getYoungestChildArray().length);
- assertTrue(Arrays.equals(new int[] { 1, 2, -1 }, ca.getYoungestChildArray()));
- assertTrue(Arrays.equals(new int[] { -1, -1, -1 }, ca.getOlderSiblingArray()));
+ assertEquals(3, ca.siblings().length);
+ assertEquals(3, ca.children().length);
+ assertTrue(Arrays.equals(new int[] { 1, 2, -1 }, ca.children()));
+ assertTrue(Arrays.equals(new int[] { -1, -1, -1 }, ca.siblings()));
tw.addCategory(new CategoryPath("hi", "ho"));
tw.addCategory(new CategoryPath("hello"));
tw.commit();
// Before refresh, nothing changed..
- ChildrenArrays newca = tr.getChildrenArrays();
+ ParallelTaxonomyArrays newca = tr.getParallelTaxonomyArrays();
assertSame(newca, ca); // we got exactly the same object
assertEquals(3, tr.getSize());
- assertEquals(3, ca.getOlderSiblingArray().length);
- assertEquals(3, ca.getYoungestChildArray().length);
+ assertEquals(3, ca.siblings().length);
+ assertEquals(3, ca.children().length);
// After the refresh, things change:
- tr.refresh();
- ca = tr.getChildrenArrays();
+ TaxonomyReader newtr = TaxonomyReader.openIfChanged(tr);
+ assertNotNull(newtr);
+ tr.close();
+ tr = newtr;
+ ca = tr.getParallelTaxonomyArrays();
assertEquals(5, tr.getSize());
- assertEquals(5, ca.getOlderSiblingArray().length);
- assertEquals(5, ca.getYoungestChildArray().length);
- assertTrue(Arrays.equals(new int[] { 4, 3, -1, -1, -1 }, ca.getYoungestChildArray()));
- assertTrue(Arrays.equals(new int[] { -1, -1, -1, 2, 1 }, ca.getOlderSiblingArray()));
+ assertEquals(5, ca.siblings().length);
+ assertEquals(5, ca.children().length);
+ assertTrue(Arrays.equals(new int[] { 4, 3, -1, -1, -1 }, ca.children()));
+ assertTrue(Arrays.equals(new int[] { -1, -1, -1, 2, 1 }, ca.siblings()));
tw.close();
tr.close();
indexDir.close();
}
- /**
- * Test that getParentArrays is valid when retrieved during refresh
- */
+ // Test that getParentArrays is valid when retrieved during refresh
@Test
- @Ignore
public void testTaxonomyReaderRefreshRaces() throws Exception {
// compute base child arrays - after first chunk, and after the other
- Directory indexDirBase = newDirectory();
+ Directory indexDirBase = newDirectory();
TaxonomyWriter twBase = new DirectoryTaxonomyWriter(indexDirBase);
twBase.addCategory(new CategoryPath("a", "0"));
final CategoryPath abPath = new CategoryPath("a", "b");
@@ -752,83 +754,93 @@ public class TestTaxonomyCombined extend
twBase.commit();
TaxonomyReader trBase = new DirectoryTaxonomyReader(indexDirBase);
- final ChildrenArrays ca1 = trBase.getChildrenArrays();
+ final ParallelTaxonomyArrays ca1 = trBase.getParallelTaxonomyArrays();
final int abOrd = trBase.getOrdinal(abPath);
- final int abYoungChildBase1 = ca1.getYoungestChildArray()[abOrd];
+ final int abYoungChildBase1 = ca1.children()[abOrd];
- for (int i=0; i < 1<<10; i++) { //1024 facets
+ final int numCategories = atLeast(800);
+ for (int i = 0; i < numCategories; i++) {
twBase.addCategory(new CategoryPath("a", "b", Integer.toString(i)));
}
- twBase.commit();
+ twBase.close();
- trBase.refresh();
+ TaxonomyReader newTaxoReader = TaxonomyReader.openIfChanged(trBase);
+ assertNotNull(newTaxoReader);
+ trBase.close();
+ trBase = newTaxoReader;
- final ChildrenArrays ca2 = trBase.getChildrenArrays();
- final int abYoungChildBase2 = ca2.getYoungestChildArray()[abOrd];
+ final ParallelTaxonomyArrays ca2 = trBase.getParallelTaxonomyArrays();
+ final int abYoungChildBase2 = ca2.children()[abOrd];
- for (int retry=0; retry<100; retry++) {
- assertConsistentYoungestChild(abPath, abOrd, abYoungChildBase1, abYoungChildBase2, retry);
+ int numRetries = atLeast(50);
+ for (int retry = 0; retry < numRetries; retry++) {
+ assertConsistentYoungestChild(abPath, abOrd, abYoungChildBase1, abYoungChildBase2, retry, numCategories);
}
+
+ trBase.close();
indexDirBase.close();
}
private void assertConsistentYoungestChild(final CategoryPath abPath,
- final int abOrd, final int abYoungChildBase1, final int abYoungChildBase2, final int retry)
+ final int abOrd, final int abYoungChildBase1, final int abYoungChildBase2, final int retry, int numCategories)
throws Exception {
- SlowRAMDirectory indexDir = new SlowRAMDirectory(-1,null); // no slowness for intialization
+ SlowRAMDirectory indexDir = new SlowRAMDirectory(-1, null); // no slowness for intialization
TaxonomyWriter tw = new DirectoryTaxonomyWriter(indexDir);
tw.addCategory(new CategoryPath("a", "0"));
tw.addCategory(abPath);
tw.commit();
- final TaxonomyReader tr = new DirectoryTaxonomyReader(indexDir);
- for (int i=0; i < 1<<10; i++) { //1024 facets
+ final DirectoryTaxonomyReader tr = new DirectoryTaxonomyReader(indexDir);
+ for (int i = 0; i < numCategories; i++) {
final CategoryPath cp = new CategoryPath("a", "b", Integer.toString(i));
tw.addCategory(cp);
assertEquals("Ordinal of "+cp+" must be invalid until Taxonomy Reader was refreshed", TaxonomyReader.INVALID_ORDINAL, tr.getOrdinal(cp));
}
- tw.commit();
+ tw.close();
- final boolean[] stop = new boolean[] { false };
+ final AtomicBoolean stop = new AtomicBoolean(false);
final Throwable[] error = new Throwable[] { null };
final int retrieval[] = { 0 };
Thread thread = new Thread("Child Arrays Verifier") {
@Override
public void run() {
- setPriority(1+getPriority());
+ setPriority(1 + getPriority());
try {
- while (!stop[0]) {
- int lastOrd = tr.getParentArray().length-1;
- assertNotNull("path of last-ord "+lastOrd+" is not found!",tr.getPath(lastOrd));
- assertChildrenArrays(tr.getChildrenArrays(),retry,retrieval[0]++);
+ while (!stop.get()) {
+ int lastOrd = tr.getParallelTaxonomyArrays().parents().length - 1;
+ assertNotNull("path of last-ord " + lastOrd + " is not found!", tr.getPath(lastOrd));
+ assertChildrenArrays(tr.getParallelTaxonomyArrays(), retry, retrieval[0]++);
+ sleep(10); // don't starve refresh()'s CPU, which sleeps every 50 bytes for 1 ms
}
} catch (Throwable e) {
error[0] = e;
- stop[0] = true;
+ stop.set(true);
}
}
- private void assertChildrenArrays(ChildrenArrays ca, int retry, int retrieval) {
- final int abYoungChild = ca.getYoungestChildArray()[abOrd];
+ private void assertChildrenArrays(ParallelTaxonomyArrays ca, int retry, int retrieval) {
+ final int abYoungChild = ca.children()[abOrd];
assertTrue(
"Retry "+retry+": retrieval: "+retrieval+": wrong youngest child for category "+abPath+" (ord="+abOrd+
") - must be either "+abYoungChildBase1+" or "+abYoungChildBase2+" but was: "+abYoungChild,
abYoungChildBase1==abYoungChild ||
- abYoungChildBase2==ca.getYoungestChildArray()[abOrd]);
+ abYoungChildBase2==ca.children()[abOrd]);
}
};
thread.start();
indexDir.setSleepMillis(1); // some delay for refresh
- tr.refresh();
+ TaxonomyReader newTaxoReader = TaxonomyReader.openIfChanged(tr);
+ if (newTaxoReader != null) {
+ newTaxoReader.close();
+ }
- stop[0] = true;
+ stop.set(true);
thread.join();
assertNull("Unexpcted exception at retry "+retry+" retrieval "+retrieval[0]+": \n"+stackTraceStr(error[0]), error[0]);
- tw.close();
tr.close();
}
@@ -885,7 +897,7 @@ public class TestTaxonomyCombined extend
// ok
}
assertEquals(1, tr.getSize()); // still root only...
- tr.refresh(); // this is not enough, because tw.commit() hasn't been done yet
+ assertNull(TaxonomyReader.openIfChanged(tr)); // this is not enough, because tw.commit() hasn't been done yet
try {
tr.getParent(author);
fail("Before commit() and refresh(), getParent for "+author+" should still throw exception");
@@ -901,7 +913,11 @@ public class TestTaxonomyCombined extend
// ok
}
assertEquals(1, tr.getSize()); // still root only...
- tr.refresh();
+ TaxonomyReader newTaxoReader = TaxonomyReader.openIfChanged(tr);
+ assertNotNull(newTaxoReader);
+ tr.close();
+ tr = newTaxoReader;
+
try {
assertEquals(TaxonomyReader.ROOT_ORDINAL, tr.getParent(author));
// ok
@@ -917,7 +933,10 @@ public class TestTaxonomyCombined extend
tw.addCategory(new CategoryPath("Author", "Richard Dawkins"));
int dawkins = 2;
tw.commit();
- tr.refresh();
+ newTaxoReader = TaxonomyReader.openIfChanged(tr);
+ assertNotNull(newTaxoReader);
+ tr.close();
+ tr = newTaxoReader;
assertEquals(author, tr.getParent(dawkins));
assertEquals(TaxonomyReader.ROOT_ORDINAL, tr.getParent(author));
assertEquals(TaxonomyReader.INVALID_ORDINAL, tr.getParent(TaxonomyReader.ROOT_ORDINAL));
@@ -943,16 +962,19 @@ public class TestTaxonomyCombined extend
// before commit and refresh, no change:
assertEquals(TaxonomyReader.INVALID_ORDINAL, tr.getOrdinal(author));
assertEquals(1, tr.getSize()); // still root only...
- tr.refresh(); // this is not enough, because tw.commit() hasn't been done yet
+ assertNull(TaxonomyReader.openIfChanged(tr)); // this is not enough, because tw.commit() hasn't been done yet
assertEquals(TaxonomyReader.INVALID_ORDINAL, tr.getOrdinal(author));
assertEquals(1, tr.getSize()); // still root only...
tw.commit();
// still not enough before refresh:
assertEquals(TaxonomyReader.INVALID_ORDINAL, tr.getOrdinal(author));
assertEquals(1, tr.getSize()); // still root only...
- tr.refresh(); // finally
+ TaxonomyReader newTaxoReader = TaxonomyReader.openIfChanged(tr);
+ assertNotNull(newTaxoReader);
+ tr.close();
+ tr = newTaxoReader;
assertEquals(1, tr.getOrdinal(author));
- assertEquals(2, tr.getSize()); // still root only...
+ assertEquals(2, tr.getSize());
tw.close();
tr.close();
indexDir.close();
@@ -977,7 +999,7 @@ public class TestTaxonomyCombined extend
// Try to open a second writer, with the first one locking the directory.
// We expect to get a LockObtainFailedException.
try {
- new DirectoryTaxonomyWriter(indexDir);
+ assertNull(new DirectoryTaxonomyWriter(indexDir));
fail("should have failed to write in locked directory");
} catch (LockObtainFailedException e) {
// this is what we expect to happen.
@@ -989,7 +1011,10 @@ public class TestTaxonomyCombined extend
tw2.addCategory(new CategoryPath("hey"));
tw2.close();
// See that the writer indeed wrote:
- tr.refresh();
+ TaxonomyReader newtr = TaxonomyReader.openIfChanged(tr);
+ assertNotNull(newtr);
+ tr.close();
+ tr = newtr;
assertEquals(3, tr.getOrdinal(new CategoryPath("hey")));
tr.close();
tw.close();
@@ -1086,6 +1111,27 @@ public class TestTaxonomyCombined extend
indexDir.close();
}
+ @Test
+ public void testNRT() throws Exception {
+ Directory dir = newDirectory();
+ DirectoryTaxonomyWriter writer = new DirectoryTaxonomyWriter(dir);
+ TaxonomyReader reader = new DirectoryTaxonomyReader(writer);
+
+ CategoryPath cp = new CategoryPath("a");
+ writer.addCategory(cp);
+ TaxonomyReader newReader = TaxonomyReader.openIfChanged(reader);
+ assertNotNull("expected a new instance", newReader);
+ assertEquals(2, newReader.getSize());
+ assertNotSame(TaxonomyReader.INVALID_ORDINAL, newReader.getOrdinal(cp));
+ reader.close();
+ reader = newReader;
+
+ writer.close();
+ reader.close();
+
+ dir.close();
+ }
+
// TODO (Facet): test multiple readers, one writer. Have the multiple readers
// using the same object (simulating threads) or different objects
// (simulating processes).
Modified: lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyReader.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyReader.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyReader.java (original)
+++ lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyReader.java Mon Dec 10 16:36:47 2012
@@ -1,14 +1,17 @@
package org.apache.lucene.facet.taxonomy.directory;
+import java.io.IOException;
import java.util.Random;
+import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.facet.taxonomy.CategoryPath;
-import org.apache.lucene.facet.taxonomy.InconsistentTaxonomyException;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.LogByteSizeMergePolicy;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
+import org.apache.lucene.index.LogMergePolicy;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
@@ -67,11 +70,8 @@ public class TestDirectoryTaxonomyReader
dir.close();
}
- /**
- * Test the boolean returned by TR.refresh
- */
@Test
- public void testReaderRefreshResult() throws Exception {
+ public void testOpenIfChangedResult() throws Exception {
Directory dir = null;
DirectoryTaxonomyWriter ltw = null;
DirectoryTaxonomyReader ltr = null;
@@ -84,13 +84,15 @@ public class TestDirectoryTaxonomyReader
ltw.commit();
ltr = new DirectoryTaxonomyReader(dir);
- assertFalse("Nothing has changed",ltr.refresh());
+ assertNull("Nothing has changed", TaxonomyReader.openIfChanged(ltr));
ltw.addCategory(new CategoryPath("b"));
ltw.commit();
- assertTrue("changes were committed",ltr.refresh());
- assertFalse("Nothing has changed",ltr.refresh());
+ DirectoryTaxonomyReader newtr = TaxonomyReader.openIfChanged(ltr);
+ assertNotNull("changes were committed", newtr);
+ assertNull("Nothing has changed", TaxonomyReader.openIfChanged(newtr));
+ newtr.close();
} finally {
IOUtils.close(ltw, ltr, dir);
}
@@ -119,18 +121,15 @@ public class TestDirectoryTaxonomyReader
*/
@Test
public void testFreshReadRecreatedTaxonomy() throws Exception {
- doTestReadRecreatedTaxono(random(), true);
+ doTestReadRecreatedTaxonomy(random(), true);
}
- /**
- * recreating a taxonomy should work well with a refreshed taxonomy reader
- */
@Test
- public void testRefreshReadRecreatedTaxonomy() throws Exception {
- doTestReadRecreatedTaxono(random(), false);
+ public void testOpenIfChangedReadRecreatedTaxonomy() throws Exception {
+ doTestReadRecreatedTaxonomy(random(), false);
}
- private void doTestReadRecreatedTaxono(Random random, boolean closeReader) throws Exception {
+ private void doTestReadRecreatedTaxonomy(Random random, boolean closeReader) throws Exception {
Directory dir = null;
TaxonomyWriter tw = null;
TaxonomyReader tr = null;
@@ -163,13 +162,10 @@ public class TestDirectoryTaxonomyReader
tr.close();
tr = new DirectoryTaxonomyReader(dir);
} else {
- try {
- tr.refresh();
- fail("Expected InconsistentTaxonomyException");
- } catch (InconsistentTaxonomyException e) {
- tr.close();
- tr = new DirectoryTaxonomyReader(dir);
- }
+ TaxonomyReader newtr = TaxonomyReader.openIfChanged(tr);
+ assertNotNull(newtr);
+ tr.close();
+ tr = newtr;
}
assertEquals("Wrong #categories in taxonomy (i="+i+", k="+k+")", baseNumCategories + 1 + k, tr.getSize());
}
@@ -179,14 +175,14 @@ public class TestDirectoryTaxonomyReader
}
@Test
- public void testRefreshAndRefCount() throws Exception {
+ public void testOpenIfChangedAndRefCount() throws Exception {
Directory dir = new RAMDirectory(); // no need for random directories here
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(dir);
taxoWriter.addCategory(new CategoryPath("a"));
taxoWriter.commit();
- DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(dir);
+ TaxonomyReader taxoReader = new DirectoryTaxonomyReader(dir);
assertEquals("wrong refCount", 1, taxoReader.getRefCount());
taxoReader.incRef();
@@ -194,12 +190,276 @@ public class TestDirectoryTaxonomyReader
taxoWriter.addCategory(new CategoryPath("a", "b"));
taxoWriter.commit();
- taxoReader.refresh();
- assertEquals("wrong refCount", 2, taxoReader.getRefCount());
+ TaxonomyReader newtr = TaxonomyReader.openIfChanged(taxoReader);
+ assertNotNull(newtr);
+ taxoReader.close();
+ taxoReader = newtr;
+ assertEquals("wrong refCount", 1, taxoReader.getRefCount());
taxoWriter.close();
taxoReader.close();
dir.close();
}
+ @Test
+ public void testOpenIfChangedManySegments() throws Exception {
+ // test openIfChanged() when the taxonomy contains many segments
+ Directory dir = newDirectory();
+
+ DirectoryTaxonomyWriter writer = new DirectoryTaxonomyWriter(dir) {
+ @Override
+ protected IndexWriterConfig createIndexWriterConfig(OpenMode openMode) {
+ IndexWriterConfig conf = super.createIndexWriterConfig(openMode);
+ LogMergePolicy lmp = (LogMergePolicy) conf.getMergePolicy();
+ lmp.setMergeFactor(2);
+ return conf;
+ }
+ };
+ TaxonomyReader reader = new DirectoryTaxonomyReader(writer);
+
+ int numRounds = random().nextInt(10) + 10;
+ int numCategories = 1; // one for root
+ for (int i = 0; i < numRounds; i++) {
+ int numCats = random().nextInt(4) + 1;
+ for (int j = 0; j < numCats; j++) {
+ writer.addCategory(new CategoryPath(Integer.toString(i), Integer.toString(j)));
+ }
+ numCategories += numCats + 1 /* one for round-parent */;
+ TaxonomyReader newtr = TaxonomyReader.openIfChanged(reader);
+ assertNotNull(newtr);
+ reader.close();
+ reader = newtr;
+
+ // assert categories
+ assertEquals(numCategories, reader.getSize());
+ int roundOrdinal = reader.getOrdinal(new CategoryPath(Integer.toString(i)));
+ int[] parents = reader.getParallelTaxonomyArrays().parents();
+ assertEquals(0, parents[roundOrdinal]); // round's parent is root
+ for (int j = 0; j < numCats; j++) {
+ int ord = reader.getOrdinal(new CategoryPath(Integer.toString(i), Integer.toString(j)));
+ assertEquals(roundOrdinal, parents[ord]); // round's parent is root
+ }
+ }
+
+ reader.close();
+ writer.close();
+ dir.close();
+ }
+
+ @Test
+ public void testOpenIfChangedMergedSegment() throws Exception {
+ // test openIfChanged() when all index segments were merged - used to be
+ // a bug in ParentArray, caught by testOpenIfChangedManySegments - only
+ // this test is not random
+ Directory dir = newDirectory();
+
+ // hold onto IW to forceMerge
+ // note how we don't close it, since DTW will close it.
+ final IndexWriter iw = new IndexWriter(dir,
+ new IndexWriterConfig(TEST_VERSION_CURRENT, new KeywordAnalyzer())
+ .setMergePolicy(new LogByteSizeMergePolicy()));
+ DirectoryTaxonomyWriter writer = new DirectoryTaxonomyWriter(dir) {
+ @Override
+ protected IndexWriter openIndexWriter(Directory directory,
+ IndexWriterConfig config) throws IOException {
+ return iw;
+ }
+ };
+
+ TaxonomyReader reader = new DirectoryTaxonomyReader(writer);
+ assertEquals(1, reader.getSize());
+ assertEquals(1, reader.getParallelTaxonomyArrays().parents().length);
+
+ // add category and call forceMerge -- this should flush IW and merge segments down to 1
+ // in ParentArray.initFromReader, this used to fail assuming there are no parents.
+ writer.addCategory(new CategoryPath("1"));
+ iw.forceMerge(1);
+
+ // now calling openIfChanged should trip on the bug
+ TaxonomyReader newtr = TaxonomyReader.openIfChanged(reader);
+ assertNotNull(newtr);
+ reader.close();
+ reader = newtr;
+ assertEquals(2, reader.getSize());
+ assertEquals(2, reader.getParallelTaxonomyArrays().parents().length);
+
+ reader.close();
+ writer.close();
+ dir.close();
+ }
+
+ @Test
+ public void testOpenIfChangedNoChangesButSegmentMerges() throws Exception {
+ // test openIfChanged() when the taxonomy hasn't really changed, but segments
+ // were merged. The NRT reader will be reopened, and ParentArray used to assert
+ // that the new reader contains more ordinals than were given from the old
+ // TaxReader version
+ Directory dir = newDirectory();
+
+ // hold onto IW to forceMerge
+ // note how we don't close it, since DTW will close it.
+ final IndexWriter iw = new IndexWriter(dir,
+ new IndexWriterConfig(TEST_VERSION_CURRENT, new KeywordAnalyzer())
+ .setMergePolicy(new LogByteSizeMergePolicy()));
+ DirectoryTaxonomyWriter writer = new DirectoryTaxonomyWriter(dir) {
+ @Override
+ protected IndexWriter openIndexWriter(Directory directory,
+ IndexWriterConfig config) throws IOException {
+ return iw;
+ }
+ };
+
+ // add a category so that the following DTR open will cause a flush and
+ // a new segment will be created
+ writer.addCategory(new CategoryPath("a"));
+
+ TaxonomyReader reader = new DirectoryTaxonomyReader(writer);
+ assertEquals(2, reader.getSize());
+ assertEquals(2, reader.getParallelTaxonomyArrays().parents().length);
+
+ // merge all the segments so that NRT reader thinks there's a change
+ iw.forceMerge(1);
+
+ // now calling openIfChanged should trip on the wrong assert in ParetArray's ctor
+ TaxonomyReader newtr = TaxonomyReader.openIfChanged(reader);
+ assertNotNull(newtr);
+ reader.close();
+ reader = newtr;
+ assertEquals(2, reader.getSize());
+ assertEquals(2, reader.getParallelTaxonomyArrays().parents().length);
+
+ reader.close();
+ writer.close();
+ dir.close();
+ }
+
+ @Test
+ public void testOpenIfChangedReuseAfterRecreate() throws Exception {
+ // tests that if the taxonomy is recreated, no data is reused from the previous taxonomy
+ Directory dir = newDirectory();
+ DirectoryTaxonomyWriter writer = new DirectoryTaxonomyWriter(dir);
+ CategoryPath cp_a = new CategoryPath("a");
+ writer.addCategory(cp_a);
+ writer.close();
+
+ DirectoryTaxonomyReader r1 = new DirectoryTaxonomyReader(dir);
+ // fill r1's caches
+ assertEquals(1, r1.getOrdinal(cp_a));
+ assertEquals(cp_a, r1.getPath(1));
+
+ // now recreate, add a different category
+ writer = new DirectoryTaxonomyWriter(dir, OpenMode.CREATE);
+ CategoryPath cp_b = new CategoryPath("b");
+ writer.addCategory(cp_b);
+ writer.close();
+
+ DirectoryTaxonomyReader r2 = TaxonomyReader.openIfChanged(r1);
+ assertNotNull(r2);
+
+ // fill r2's caches
+ assertEquals(1, r2.getOrdinal(cp_b));
+ assertEquals(cp_b, r2.getPath(1));
+
+ // check that r1 doesn't see cp_b
+ assertEquals(TaxonomyReader.INVALID_ORDINAL, r1.getOrdinal(cp_b));
+ assertEquals(cp_a, r1.getPath(1));
+
+ // check that r2 doesn't see cp_a
+ assertEquals(TaxonomyReader.INVALID_ORDINAL, r2.getOrdinal(cp_a));
+ assertEquals(cp_b, r2.getPath(1));
+
+ r2.close();
+ r1.close();
+ dir.close();
+ }
+
+ @Test
+ public void testOpenIfChangedReuse() throws Exception {
+ // test the reuse of data from the old DTR instance
+ for (boolean nrt : new boolean[] {false, true}) {
+ Directory dir = newDirectory();
+ DirectoryTaxonomyWriter writer = new DirectoryTaxonomyWriter(dir);
+
+ CategoryPath cp_a = new CategoryPath("a");
+ writer.addCategory(cp_a);
+ if (!nrt) writer.commit();
+
+ DirectoryTaxonomyReader r1 = nrt ? new DirectoryTaxonomyReader(writer) : new DirectoryTaxonomyReader(dir);
+ // fill r1's caches
+ assertEquals(1, r1.getOrdinal(cp_a));
+ assertEquals(cp_a, r1.getPath(1));
+
+ CategoryPath cp_b = new CategoryPath("b");
+ writer.addCategory(cp_b);
+ if (!nrt) writer.commit();
+
+ DirectoryTaxonomyReader r2 = TaxonomyReader.openIfChanged(r1);
+ assertNotNull(r2);
+
+ // add r2's categories to the caches
+ assertEquals(2, r2.getOrdinal(cp_b));
+ assertEquals(cp_b, r2.getPath(2));
+
+ // check that r1 doesn't see cp_b
+ assertEquals(TaxonomyReader.INVALID_ORDINAL, r1.getOrdinal(cp_b));
+ assertNull(r1.getPath(2));
+
+ r1.close();
+ r2.close();
+ writer.close();
+ dir.close();
+ }
+ }
+
+ @Test
+ public void testOpenIfChangedReplaceTaxonomy() throws Exception {
+ // test openIfChanged when replaceTaxonomy is called, which is equivalent to recreate
+ // only can work with NRT as well
+ Directory src = newDirectory();
+ DirectoryTaxonomyWriter w = new DirectoryTaxonomyWriter(src);
+ CategoryPath cp_b = new CategoryPath("b");
+ w.addCategory(cp_b);
+ w.close();
+
+ for (boolean nrt : new boolean[] {false, true}) {
+ Directory dir = newDirectory();
+ DirectoryTaxonomyWriter writer = new DirectoryTaxonomyWriter(dir);
+
+ CategoryPath cp_a = new CategoryPath("a");
+ writer.addCategory(cp_a);
+ if (!nrt) writer.commit();
+
+ DirectoryTaxonomyReader r1 = nrt ? new DirectoryTaxonomyReader(writer) : new DirectoryTaxonomyReader(dir);
+ // fill r1's caches
+ assertEquals(1, r1.getOrdinal(cp_a));
+ assertEquals(cp_a, r1.getPath(1));
+
+ // now replace taxonomy
+ writer.replaceTaxonomy(src);
+ if (!nrt) writer.commit();
+
+ DirectoryTaxonomyReader r2 = TaxonomyReader.openIfChanged(r1);
+ assertNotNull(r2);
+
+ // fill r2's caches
+ assertEquals(1, r2.getOrdinal(cp_b));
+ assertEquals(cp_b, r2.getPath(1));
+
+ // check that r1 doesn't see cp_b
+ assertEquals(TaxonomyReader.INVALID_ORDINAL, r1.getOrdinal(cp_b));
+ assertEquals(cp_a, r1.getPath(1));
+
+ // check that r2 doesn't see cp_a
+ assertEquals(TaxonomyReader.INVALID_ORDINAL, r2.getOrdinal(cp_a));
+ assertEquals(cp_b, r2.getPath(1));
+
+ r2.close();
+ r1.close();
+ writer.close();
+ dir.close();
+ }
+
+ src.close();
+ }
+
}
Modified: lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyWriter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyWriter.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyWriter.java (original)
+++ lucene/dev/branches/lucene4547/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyWriter.java Mon Dec 10 16:36:47 2012
@@ -8,7 +8,7 @@ import java.util.concurrent.ConcurrentHa
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.lucene.facet.taxonomy.CategoryPath;
-import org.apache.lucene.facet.taxonomy.InconsistentTaxonomyException;
+import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.writercache.TaxonomyWriterCache;
import org.apache.lucene.facet.taxonomy.writercache.cl2o.Cl2oTaxonomyWriterCache;
import org.apache.lucene.facet.taxonomy.writercache.lru.LruTaxonomyWriterCache;
@@ -87,9 +87,9 @@ public class TestDirectoryTaxonomyWriter
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(dir, OpenMode.CREATE_OR_APPEND, NO_OP_CACHE);
taxoWriter.addCategory(new CategoryPath("a"));
taxoWriter.addCategory(new CategoryPath("b"));
- Map <String, String> userCommitData = new HashMap<String, String>();
+ Map<String, String> userCommitData = new HashMap<String, String>();
userCommitData.put("testing", "1 2 3");
- taxoWriter.commit(userCommitData);
+ taxoWriter.setCommitData(userCommitData);
taxoWriter.close();
DirectoryReader r = DirectoryReader.open(dir);
assertEquals("2 categories plus root should have been committed to the underlying directory", 3, r.numDocs());
@@ -104,9 +104,14 @@ public class TestDirectoryTaxonomyWriter
// that the taxonomy index has been recreated.
taxoWriter = new DirectoryTaxonomyWriter(dir, OpenMode.CREATE_OR_APPEND, NO_OP_CACHE);
taxoWriter.addCategory(new CategoryPath("c")); // add a category so that commit will happen
- taxoWriter.commit(new HashMap<String, String>(){{
+ taxoWriter.setCommitData(new HashMap<String, String>(){{
put("just", "data");
}});
+ taxoWriter.commit();
+
+ // verify taxoWriter.getCommitData()
+ assertNotNull(DirectoryTaxonomyWriter.INDEX_EPOCH
+ + " not found in taoxWriter.commitData", taxoWriter.getCommitData().get(DirectoryTaxonomyWriter.INDEX_EPOCH));
taxoWriter.close();
r = DirectoryReader.open(dir);
@@ -163,9 +168,10 @@ public class TestDirectoryTaxonomyWriter
private void touchTaxo(DirectoryTaxonomyWriter taxoWriter, CategoryPath cp) throws IOException {
taxoWriter.addCategory(cp);
- taxoWriter.commit(new HashMap<String, String>(){{
+ taxoWriter.setCommitData(new HashMap<String, String>(){{
put("just", "data");
}});
+ taxoWriter.commit();
}
@Test
@@ -178,12 +184,14 @@ public class TestDirectoryTaxonomyWriter
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(dir, OpenMode.CREATE_OR_APPEND, NO_OP_CACHE);
touchTaxo(taxoWriter, new CategoryPath("a"));
- DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(dir);
+ TaxonomyReader taxoReader = new DirectoryTaxonomyReader(dir);
touchTaxo(taxoWriter, new CategoryPath("b"));
- // this should not fail
- taxoReader.refresh();
+ TaxonomyReader newtr = TaxonomyReader.openIfChanged(taxoReader);
+ taxoReader.close();
+ taxoReader = newtr;
+ assertEquals(1, Integer.parseInt(taxoReader.getCommitUserData().get(DirectoryTaxonomyWriter.INDEX_EPOCH)));
// now recreate the taxonomy, and check that the epoch is preserved after opening DirTW again.
taxoWriter.close();
@@ -195,14 +203,11 @@ public class TestDirectoryTaxonomyWriter
touchTaxo(taxoWriter, new CategoryPath("d"));
taxoWriter.close();
- // this should fail
- try {
- taxoReader.refresh();
- fail("IconsistentTaxonomyException should have been thrown");
- } catch (InconsistentTaxonomyException e) {
- // ok, expected
- }
-
+ newtr = TaxonomyReader.openIfChanged(taxoReader);
+ taxoReader.close();
+ taxoReader = newtr;
+ assertEquals(2, Integer.parseInt(taxoReader.getCommitUserData().get(DirectoryTaxonomyWriter.INDEX_EPOCH)));
+
taxoReader.close();
dir.close();
}
@@ -221,7 +226,7 @@ public class TestDirectoryTaxonomyWriter
DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(dir);
assertEquals(1, Integer.parseInt(taxoReader.getCommitUserData().get(DirectoryTaxonomyWriter.INDEX_EPOCH)));
- taxoReader.refresh();
+ assertNull(TaxonomyReader.openIfChanged(taxoReader));
taxoReader.close();
dir.close();
@@ -232,7 +237,7 @@ public class TestDirectoryTaxonomyWriter
final int range = ncats * 3; // affects the categories selection
final AtomicInteger numCats = new AtomicInteger(ncats);
final Directory dir = newDirectory();
- final ConcurrentHashMap<Integer,Integer> values = new ConcurrentHashMap<Integer,Integer>();
+ final ConcurrentHashMap<String,String> values = new ConcurrentHashMap<String,String>();
final double d = random().nextDouble();
final TaxonomyWriterCache cache;
if (d < 0.7) {
@@ -256,8 +261,18 @@ public class TestDirectoryTaxonomyWriter
while (numCats.decrementAndGet() > 0) {
try {
int value = random.nextInt(range);
- tw.addCategory(new CategoryPath("a", Integer.toString(value)));
- values.put(value, value);
+ CategoryPath cp = new CategoryPath(Integer.toString(value / 1000), Integer.toString(value / 10000),
+ Integer.toString(value / 100000), Integer.toString(value));
+ int ord = tw.addCategory(cp);
+ assertTrue("invalid parent for ordinal " + ord + ", category " + cp, tw.getParent(ord) != -1);
+ String l1 = cp.toString('/', 1);
+ String l2 = cp.toString('/', 2);
+ String l3 = cp.toString('/', 3);
+ String l4 = cp.toString('/', 4);
+ values.put(l1, l1);
+ values.put(l2, l2);
+ values.put(l3, l3);
+ values.put(l4, l4);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -271,9 +286,20 @@ public class TestDirectoryTaxonomyWriter
tw.close();
DirectoryTaxonomyReader dtr = new DirectoryTaxonomyReader(dir);
- assertEquals("mismatch number of categories", values.size() + 2, dtr.getSize()); // +2 for root category + "a"
- for (Integer value : values.keySet()) {
- assertTrue("category not found a/" + value, dtr.getOrdinal(new CategoryPath("a", value.toString())) > 0);
+ assertEquals("mismatch number of categories", values.size() + 1, dtr.getSize()); // +1 for root category
+ int[] parents = dtr.getParallelTaxonomyArrays().parents();
+ for (String cat : values.keySet()) {
+ CategoryPath cp = new CategoryPath(cat, '/');
+ assertTrue("category not found " + cp, dtr.getOrdinal(cp) > 0);
+ int level = cp.length();
+ int parentOrd = 0; // for root, parent is always virtual ROOT (ord=0)
+ CategoryPath path = new CategoryPath();
+ for (int i = 0; i < level; i++) {
+ path.add(cp.getComponent(i));
+ int ord = dtr.getOrdinal(path);
+ assertEquals("invalid parent for cp=" + path, parentOrd, parents[ord]);
+ parentOrd = ord; // next level should have this parent
+ }
}
dtr.close();
Modified: lucene/dev/branches/lucene4547/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java (original)
+++ lucene/dev/branches/lucene4547/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java Mon Dec 10 16:36:47 2012
@@ -210,7 +210,7 @@ public class GroupingSearch {
if (allGroupHeads || allGroups) {
List<Collector> collectors = new ArrayList<Collector>();
collectors.add(firstPassCollector);
- if (allGroupHeads) {
+ if (allGroups) {
collectors.add(allGroupsCollector);
}
if (allGroupHeads) {
@@ -403,7 +403,7 @@ public class GroupingSearch {
}
/**
- * Whether to also co0.0mpute all groups matching the query.
+ * Whether to also compute all groups matching the query.
* This can be used to determine the number of groups, which can be used for accurate pagination.
* <p/>
* When grouping by doc block the number of groups are automatically included in the {@link TopGroups} and this
Modified: lucene/dev/branches/lucene4547/lucene/grouping/src/test/org/apache/lucene/search/grouping/GroupingSearchTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/grouping/src/test/org/apache/lucene/search/grouping/GroupingSearchTest.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/grouping/src/test/org/apache/lucene/search/grouping/GroupingSearchTest.java (original)
+++ lucene/dev/branches/lucene4547/lucene/grouping/src/test/org/apache/lucene/search/grouping/GroupingSearchTest.java Mon Dec 10 16:36:47 2012
@@ -227,5 +227,29 @@ public class GroupingSearchTest extends
return groupingSearch;
}
-
+
+ public void testSetAllGroups() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(
+ random(),
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT,
+ new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
+ Document doc = new Document();
+ doc.add(newField("group", "foo", StringField.TYPE_NOT_STORED));
+ w.addDocument(doc);
+
+ IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
+ w.close();
+
+ GroupingSearch gs = new GroupingSearch("group");
+ gs.setAllGroups(true);
+ TopGroups<?> groups = gs.search(indexSearcher, null, new TermQuery(new Term("group", "foo")), 0, 10);
+ assertEquals(1, groups.totalHitCount);
+ //assertEquals(1, groups.totalGroupCount.intValue());
+ assertEquals(1, groups.totalGroupedHitCount);
+ assertEquals(1, gs.getAllMatchingGroups().size());
+ indexSearcher.getIndexReader().close();
+ dir.close();
+ }
}
Modified: lucene/dev/branches/lucene4547/lucene/queries/src/java/org/apache/lucene/queries/TermsFilter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/queries/src/java/org/apache/lucene/queries/TermsFilter.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/queries/src/java/org/apache/lucene/queries/TermsFilter.java (original)
+++ lucene/dev/branches/lucene4547/lucene/queries/src/java/org/apache/lucene/queries/TermsFilter.java Mon Dec 10 16:36:47 2012
@@ -253,17 +253,21 @@ public final class TermsFilter extends F
public String toString() {
StringBuilder builder = new StringBuilder();
BytesRef spare = new BytesRef(termsBytes);
+ boolean first = true;
for (int i = 0; i < termsAndFields.length; i++) {
TermsAndField current = termsAndFields[i];
for (int j = current.start; j < current.end; j++) {
spare.offset = offsets[j];
spare.length = offsets[j+1] - offsets[j];
+ if (!first) {
+ builder.append(' ');
+ }
+ first = false;
builder.append(current.field).append(':');
builder.append(spare.utf8ToString());
- builder.append(' ');
}
-
}
+
return builder.toString();
}
Modified: lucene/dev/branches/lucene4547/lucene/queries/src/test/org/apache/lucene/queries/BooleanFilterTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/queries/src/test/org/apache/lucene/queries/BooleanFilterTest.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/queries/src/test/org/apache/lucene/queries/BooleanFilterTest.java (original)
+++ lucene/dev/branches/lucene4547/lucene/queries/src/test/org/apache/lucene/queries/BooleanFilterTest.java Mon Dec 10 16:36:47 2012
@@ -332,4 +332,34 @@ public class BooleanFilterTest extends L
booleanFilter.add(getTermsFilter("accessRights", "admin"), Occur.MUST);
tstFilterCard(">0 shoulds with no matches should return no docs", 0, booleanFilter);
}
+
+ public void testToStringOfBooleanFilterContainingTermsFilter() {
+ BooleanFilter booleanFilter = new BooleanFilter();
+ booleanFilter.add(getTermsFilter("inStock", "N"), Occur.MUST);
+ booleanFilter.add(getTermsFilter("isFragile", "Y"), Occur.MUST);
+
+ assertEquals("BooleanFilter(+inStock:N +isFragile:Y)", booleanFilter.toString());
+ }
+
+ public void testToStringOfWrappedBooleanFilters() {
+ BooleanFilter orFilter = new BooleanFilter();
+
+ BooleanFilter stockFilter = new BooleanFilter();
+ stockFilter.add(new FilterClause(getTermsFilter("inStock", "Y"), Occur.MUST));
+ stockFilter.add(new FilterClause(getTermsFilter("barCode", "12345678"), Occur.MUST));
+
+ orFilter.add(new FilterClause(stockFilter,Occur.SHOULD));
+
+ BooleanFilter productPropertyFilter = new BooleanFilter();
+ productPropertyFilter.add(new FilterClause(getTermsFilter("isHeavy", "N"), Occur.MUST));
+ productPropertyFilter.add(new FilterClause(getTermsFilter("isDamaged", "Y"), Occur.MUST));
+
+ orFilter.add(new FilterClause(productPropertyFilter,Occur.SHOULD));
+
+ BooleanFilter composedFilter = new BooleanFilter();
+ composedFilter.add(new FilterClause(orFilter,Occur.MUST));
+
+ assertEquals("BooleanFilter(+BooleanFilter(BooleanFilter(+inStock:Y +barCode:12345678) BooleanFilter(+isHeavy:N +isDamaged:Y)))",
+ composedFilter.toString());
+ }
}
Modified: lucene/dev/branches/lucene4547/lucene/queries/src/test/org/apache/lucene/queries/TermsFilterTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/queries/src/test/org/apache/lucene/queries/TermsFilterTest.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/queries/src/test/org/apache/lucene/queries/TermsFilterTest.java (original)
+++ lucene/dev/branches/lucene4547/lucene/queries/src/test/org/apache/lucene/queries/TermsFilterTest.java Mon Dec 10 16:36:47 2012
@@ -320,4 +320,11 @@ public class TermsFilterTest extends Luc
fail("must fail - no terms!");
} catch (IllegalArgumentException e) {}
}
+
+ public void testToString() {
+ TermsFilter termsFilter = new TermsFilter(new Term("field1", "a"),
+ new Term("field1", "b"),
+ new Term("field1", "c"));
+ assertEquals("field1:a field1:b field1:c", termsFilter.toString());
+ }
}
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/PointPrefixTreeFieldCacheProvider.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/PointPrefixTreeFieldCacheProvider.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/PointPrefixTreeFieldCacheProvider.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/PointPrefixTreeFieldCacheProvider.java Mon Dec 10 16:36:47 2012
@@ -45,6 +45,8 @@ public class PointPrefixTreeFieldCachePr
@Override
protected Point readShape(BytesRef term) {
scanCell = grid.getNode(term.bytes, term.offset, term.length, scanCell);
- return scanCell.isLeaf() ? scanCell.getShape().getCenter() : null;
+ if (scanCell.getLevel() == grid.getMaxLevels() && !scanCell.isLeaf())
+ return scanCell.getCenter();
+ return null;
}
}
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/RecursivePrefixTreeFilter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/RecursivePrefixTreeFilter.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/RecursivePrefixTreeFilter.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/RecursivePrefixTreeFilter.java Mon Dec 10 16:36:47 2012
@@ -19,7 +19,11 @@ package org.apache.lucene.spatial.prefix
import com.spatial4j.core.shape.Shape;
import com.spatial4j.core.shape.SpatialRelation;
-import org.apache.lucene.index.*;
+import org.apache.lucene.index.AtomicReader;
+import org.apache.lucene.index.AtomicReaderContext;
+import org.apache.lucene.index.DocsEnum;
+import org.apache.lucene.index.Terms;
+import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Filter;
@@ -110,23 +114,28 @@ RE "scan" threshold:
while(!cells.isEmpty()) {
final Node cell = cells.removeFirst();
final BytesRef cellTerm = new BytesRef(cell.getTokenBytes());
- TermsEnum.SeekStatus seekStat = termsEnum.seekCeil(cellTerm);
- if (seekStat == TermsEnum.SeekStatus.END)
- break;
- if (seekStat == TermsEnum.SeekStatus.NOT_FOUND)
+ if (!termsEnum.seekExact(cellTerm, true))
continue;
if (cell.getLevel() == detailLevel || cell.isLeaf()) {
docsEnum = termsEnum.docs(acceptDocs, docsEnum, 0);
addDocs(docsEnum,bits);
} else {//any other intersection
- //If the next indexed term is the leaf marker, then add all of them
+ assert cell.getLevel() < detailLevel; //assertions help clarify logic
+ assert !cell.isLeaf();
+ //If the next indexed term just adds a leaf marker ('+') to cell,
+ // then add all of those docs
BytesRef nextCellTerm = termsEnum.next();
+ if (nextCellTerm == null)
+ break;
assert StringHelper.startsWith(nextCellTerm, cellTerm);
scanCell = grid.getNode(nextCellTerm.bytes, nextCellTerm.offset, nextCellTerm.length, scanCell);
- if (scanCell.isLeaf()) {
+ if (scanCell.getLevel() == cell.getLevel() && scanCell.isLeaf()) {
docsEnum = termsEnum.docs(acceptDocs, docsEnum, 0);
addDocs(docsEnum,bits);
- termsEnum.next();//move pointer to avoid potential redundant addDocs() below
+ //increment pointer to avoid potential redundant addDocs() below
+ nextCellTerm = termsEnum.next();
+ if (nextCellTerm == null)
+ break;
}
//Decide whether to continue to divide & conquer, or whether it's time to scan through terms beneath this cell.
@@ -144,8 +153,13 @@ RE "scan" threshold:
if (termLevel > detailLevel)
continue;
if (termLevel == detailLevel || scanCell.isLeaf()) {
- //TODO should put more thought into implications of box vs point
- Shape cShape = termLevel == grid.getMaxLevels() ? scanCell.getCenter() : scanCell.getShape();
+ Shape cShape;
+ //if this cell represents a point, use the cell center vs the box
+ // (points never have isLeaf())
+ if (termLevel == grid.getMaxLevels() && !scanCell.isLeaf())
+ cShape = scanCell.getCenter();
+ else
+ cShape = scanCell.getShape();
if(queryShape.relate(cShape) == SpatialRelation.DISJOINT)
continue;
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/GeohashPrefixTree.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/GeohashPrefixTree.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/GeohashPrefixTree.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/GeohashPrefixTree.java Mon Dec 10 16:36:47 2012
@@ -101,11 +101,11 @@ public class GeohashPrefixTree extends S
class GhCell extends Node {
GhCell(String token) {
- super(GeohashPrefixTree.this, token);
+ super(token);
}
GhCell(byte[] bytes, int off, int len) {
- super(GeohashPrefixTree.this, bytes, off, len);
+ super(bytes, off, len);
}
@Override
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/Node.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/Node.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/Node.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/Node.java Mon Dec 10 16:36:47 2012
@@ -44,11 +44,14 @@ public abstract class Node implements Co
private String token;//this is the only part of equality
- protected SpatialRelation shapeRel;//set in getSubCells(filter), and via setLeaf().
- private SpatialPrefixTree spatialPrefixTree;
+ /** When set via getSubCells(filter), it is the relationship between this
+ * cell and the given shape filter. If set via setLeaf() (to WITHIN), it is
+ * meant to indicate no further sub-cells are going to be provided because
+ * maxLevels or a detailLevel is hit. It's always null for points.
+ */
+ protected SpatialRelation shapeRel;
- protected Node(SpatialPrefixTree spatialPrefixTree, String token) {
- this.spatialPrefixTree = spatialPrefixTree;
+ protected Node(String token) {
this.token = token;
if (token.length() > 0 && token.charAt(token.length() - 1) == (char) LEAF_BYTE) {
this.token = token.substring(0, token.length() - 1);
@@ -59,8 +62,7 @@ public abstract class Node implements Co
getShape();//ensure any lazy instantiation completes to make this threadsafe
}
- protected Node(SpatialPrefixTree spatialPrefixTree, byte[] bytes, int off, int len) {
- this.spatialPrefixTree = spatialPrefixTree;
+ protected Node(byte[] bytes, int off, int len) {
this.bytes = bytes;
this.b_off = off;
this.b_len = len;
@@ -78,11 +80,10 @@ public abstract class Node implements Co
}
private void b_fixLeaf() {
+ //note that non-point shapes always have the maxLevels cell set with setLeaf
if (bytes[b_off + b_len - 1] == LEAF_BYTE) {
b_len--;
setLeaf();
- } else if (getLevel() == spatialPrefixTree.getMaxLevels()) {
- setLeaf();
}
}
@@ -90,6 +91,10 @@ public abstract class Node implements Co
return shapeRel;
}
+ /**
+ * For points, this is always false. Otherwise this is true if there are no
+ * further cells with this prefix for the shape (always true at maxLevels).
+ */
public boolean isLeaf() {
return shapeRel == SpatialRelation.WITHIN;
}
@@ -133,8 +138,14 @@ public abstract class Node implements Co
//public Cell getParent();
/**
- * Like {@link #getSubCells()} but with the results filtered by a shape. If that shape is a {@link com.spatial4j.core.shape.Point} then it
- * must call {@link #getSubCell(com.spatial4j.core.shape.Point)};
+ * Like {@link #getSubCells()} but with the results filtered by a shape. If
+ * that shape is a {@link com.spatial4j.core.shape.Point} then it
+ * must call {@link #getSubCell(com.spatial4j.core.shape.Point)}.
+ * The returned cells should have their {@link Node#shapeRel} set to their
+ * relation with {@code shapeFilter} for non-point. As such,
+ * {@link org.apache.lucene.spatial.prefix.tree.Node#isLeaf()} should be
+ * accurate.
+ * <p/>
* Precondition: Never called when getLevel() == maxLevel.
*
* @param shapeFilter an optional filter for the returned cells.
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/QuadPrefixTree.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/QuadPrefixTree.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/QuadPrefixTree.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/QuadPrefixTree.java Mon Dec 10 16:36:47 2012
@@ -228,16 +228,16 @@ public class QuadPrefixTree extends Spat
class QuadCell extends Node {
public QuadCell(String token) {
- super(QuadPrefixTree.this, token);
+ super(token);
}
public QuadCell(String token, SpatialRelation shapeRel) {
- super(QuadPrefixTree.this, token);
+ super(token);
this.shapeRel = shapeRel;
}
QuadCell(byte[] bytes, int off, int len) {
- super(QuadPrefixTree.this, bytes, off, len);
+ super(bytes, off, len);
}
@Override
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/SpatialPrefixTree.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/SpatialPrefixTree.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/SpatialPrefixTree.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/SpatialPrefixTree.java Mon Dec 10 16:36:47 2012
@@ -156,7 +156,7 @@ public abstract class SpatialPrefixTree
}
final Collection<Node> subCells = node.getSubCells(shape);
if (node.getLevel() == detailLevel - 1) {
- if (subCells.size() < node.getSubCellsSize()) {
+ if (subCells.size() < node.getSubCellsSize() || node.getLevel() == 0) {
if (inclParents)
result.add(node);
for (Node subCell : subCells) {
@@ -164,7 +164,7 @@ public abstract class SpatialPrefixTree
}
result.addAll(subCells);
} else {//a bottom level (i.e. detail level) optimization where all boxes intersect, so use parent cell.
- node.setLeaf();
+ node.setLeaf();//the cell may not be strictly within but its close
result.add(node);
}
} else {
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/query/SpatialOperation.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/query/SpatialOperation.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/query/SpatialOperation.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/java/org/apache/lucene/spatial/query/SpatialOperation.java Mon Dec 10 16:36:47 2012
@@ -17,6 +17,9 @@ package org.apache.lucene.spatial.query;
* limitations under the License.
*/
+import com.spatial4j.core.shape.Shape;
+import com.spatial4j.core.shape.SpatialRelation;
+
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
@@ -25,14 +28,16 @@ import java.util.Locale;
import java.util.Map;
/**
- * A clause that compares a stored geometry to a supplied geometry.
+ * A clause that compares a stored geometry to a supplied geometry. For more
+ * explanation of each operation, consider looking at the source implementation
+ * of {@link #evaluate(com.spatial4j.core.shape.Shape, com.spatial4j.core.shape.Shape)}.
*
* @see <a href="http://edndoc.esri.com/arcsde/9.1/general_topics/understand_spatial_relations.htm">
* ESRIs docs on spatial relations</a>
*
* @lucene.experimental
*/
-public class SpatialOperation implements Serializable {
+public abstract class SpatialOperation implements Serializable {
// Private registry
private static final Map<String, SpatialOperation> registry = new HashMap<String, SpatialOperation>();
private static final List<SpatialOperation> list = new ArrayList<SpatialOperation>();
@@ -40,15 +45,55 @@ public class SpatialOperation implements
// Geometry Operations
/** Bounding box of the *indexed* shape. */
- public static final SpatialOperation BBoxIntersects = new SpatialOperation("BBoxIntersects", true, false, false);
+ public static final SpatialOperation BBoxIntersects = new SpatialOperation("BBoxIntersects", true, false, false) {
+ @Override
+ public boolean evaluate(Shape indexedShape, Shape queryShape) {
+ return indexedShape.getBoundingBox().relate(queryShape).intersects();
+ }
+ };
/** Bounding box of the *indexed* shape. */
- public static final SpatialOperation BBoxWithin = new SpatialOperation("BBoxWithin", true, false, false);
- public static final SpatialOperation Contains = new SpatialOperation("Contains", true, true, false);
- public static final SpatialOperation Intersects = new SpatialOperation("Intersects", true, false, false);
- public static final SpatialOperation IsEqualTo = new SpatialOperation("IsEqualTo", false, false, false);
- public static final SpatialOperation IsDisjointTo = new SpatialOperation("IsDisjointTo", false, false, false);
- public static final SpatialOperation IsWithin = new SpatialOperation("IsWithin", true, false, true);
- public static final SpatialOperation Overlaps = new SpatialOperation("Overlaps", true, false, true);
+ public static final SpatialOperation BBoxWithin = new SpatialOperation("BBoxWithin", true, false, false) {
+ @Override
+ public boolean evaluate(Shape indexedShape, Shape queryShape) {
+ return indexedShape.getBoundingBox().relate(queryShape) == SpatialRelation.WITHIN;
+ }
+ };
+ public static final SpatialOperation Contains = new SpatialOperation("Contains", true, true, false) {
+ @Override
+ public boolean evaluate(Shape indexedShape, Shape queryShape) {
+ return indexedShape.hasArea() && indexedShape.relate(queryShape) == SpatialRelation.CONTAINS;
+ }
+ };
+ public static final SpatialOperation Intersects = new SpatialOperation("Intersects", true, false, false) {
+ @Override
+ public boolean evaluate(Shape indexedShape, Shape queryShape) {
+ return indexedShape.relate(queryShape).intersects();
+ }
+ };
+ public static final SpatialOperation IsEqualTo = new SpatialOperation("IsEqualTo", false, false, false) {
+ @Override
+ public boolean evaluate(Shape indexedShape, Shape queryShape) {
+ return indexedShape.equals(queryShape);
+ }
+ };
+ public static final SpatialOperation IsDisjointTo = new SpatialOperation("IsDisjointTo", false, false, false) {
+ @Override
+ public boolean evaluate(Shape indexedShape, Shape queryShape) {
+ return ! indexedShape.relate(queryShape).intersects();
+ }
+ };
+ public static final SpatialOperation IsWithin = new SpatialOperation("IsWithin", true, false, true) {
+ @Override
+ public boolean evaluate(Shape indexedShape, Shape queryShape) {
+ return queryShape.hasArea() && indexedShape.relate(queryShape) == SpatialRelation.WITHIN;
+ }
+ };
+ public static final SpatialOperation Overlaps = new SpatialOperation("Overlaps", true, false, true) {
+ @Override
+ public boolean evaluate(Shape indexedShape, Shape queryShape) {
+ return queryShape.hasArea() && indexedShape.relate(queryShape).intersects();
+ }
+ };
// Member variables
private final boolean scoreIsMeaningful;
@@ -90,6 +135,11 @@ public class SpatialOperation implements
return false;
}
+ /**
+ * Returns whether the relationship between indexedShape and queryShape is
+ * satisfied by this operation.
+ */
+ public abstract boolean evaluate(Shape indexedShape, Shape queryShape);
// ================================================= Getters / Setters =============================================
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java Mon Dec 10 16:36:47 2012
@@ -29,6 +29,7 @@ import org.apache.lucene.index.Directory
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.StoredDocument;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
@@ -54,6 +55,8 @@ import java.io.IOException;
*/
public class SpatialExample extends LuceneTestCase {
+ //Note: Test invoked via TestTestFramework.spatialExample()
+
public static void main(String[] args) throws IOException {
new SpatialExample().test();
}
@@ -148,14 +151,27 @@ public class SpatialExample extends Luce
Filter filter = strategy.makeFilter(args);
TopDocs docs = indexSearcher.search(new MatchAllDocsQuery(), filter, 10, idSort);
assertDocMatchedIds(indexSearcher, docs, 2);
+ //Now, lets get the distance for the 1st doc via computing from stored point value:
+ // (this computation is usually not redundant)
+ StoredDocument doc1 = indexSearcher.doc(docs.scoreDocs[0].doc);
+ String doc1Str = doc1.getField(strategy.getFieldName()).stringValue();
+ Point doc1Point = (Point) ctx.readShape(doc1Str);
+ double doc1DistDEG = ctx.getDistCalc().distance(args.getShape().getCenter(), doc1Point);
+ assertEquals(121.6d, DistanceUtils.degrees2Dist(doc1DistDEG, DistanceUtils.EARTH_MEAN_RADIUS_KM), 0.1);
}
- //--Match all, order by distance
+ //--Match all, order by distance ascending
{
Point pt = ctx.makePoint(60, -50);
ValueSource valueSource = strategy.makeDistanceValueSource(pt);//the distance (in degrees)
- Sort reverseDistSort = new Sort(valueSource.getSortField(false)).rewrite(indexSearcher);//true=asc dist
- TopDocs docs = indexSearcher.search(new MatchAllDocsQuery(), 10, reverseDistSort);
+ Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(indexSearcher);//false=asc dist
+ TopDocs docs = indexSearcher.search(new MatchAllDocsQuery(), 10, distSort);
assertDocMatchedIds(indexSearcher, docs, 4, 20, 2);
+ //To get the distance, we could compute from stored values like earlier.
+ // However in this example we sorted on it, and the distance will get
+ // computed redundantly. If the distance is only needed for the top-X
+ // search results then that's not a big deal. Alternatively, try wrapping
+ // the ValueSource with CachingDoubleValueSource then retrieve the value
+ // from the ValueSource now. See LUCENE-4541 for an example.
}
//demo arg parsing
{
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialTestCase.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialTestCase.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialTestCase.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialTestCase.java Mon Dec 10 16:36:47 2012
@@ -1,3 +1,5 @@
+package org.apache.lucene.spatial;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -15,8 +17,9 @@
* limitations under the License.
*/
-package org.apache.lucene.spatial;
-
+import com.spatial4j.core.context.SpatialContext;
+import com.spatial4j.core.shape.Point;
+import com.spatial4j.core.shape.Rectangle;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.RandomIndexWriter;
@@ -35,6 +38,10 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import static com.carrotsearch.randomizedtesting.RandomizedTest.randomGaussian;
+import static com.carrotsearch.randomizedtesting.RandomizedTest.randomIntBetween;
+
+/** A base test class for spatial lucene. It's mostly Lucene generic. */
public abstract class SpatialTestCase extends LuceneTestCase {
private DirectoryReader indexReader;
@@ -42,6 +49,8 @@ public abstract class SpatialTestCase ex
private Directory directory;
protected IndexSearcher indexSearcher;
+ protected SpatialContext ctx;//subclass must initialize
+
@Override
@Before
public void setUp() throws Exception {
@@ -100,6 +109,63 @@ public abstract class SpatialTestCase ex
}
}
+ protected Point randomPoint() {
+ final Rectangle WB = ctx.getWorldBounds();
+ return ctx.makePoint(
+ randomIntBetween((int) WB.getMinX(), (int) WB.getMaxX()),
+ randomIntBetween((int) WB.getMinY(), (int) WB.getMaxY()));
+ }
+
+ protected Rectangle randomRectangle() {
+ final Rectangle WB = ctx.getWorldBounds();
+ int rW = (int) randomGaussianMeanMax(10, WB.getWidth());
+ double xMin = randomIntBetween((int) WB.getMinX(), (int) WB.getMaxX() - rW);
+ double xMax = xMin + rW;
+
+ int yH = (int) randomGaussianMeanMax(Math.min(rW, WB.getHeight()), WB.getHeight());
+ double yMin = randomIntBetween((int) WB.getMinY(), (int) WB.getMaxY() - yH);
+ double yMax = yMin + yH;
+
+ return ctx.makeRectangle(xMin, xMax, yMin, yMax);
+ }
+
+ private double randomGaussianMinMeanMax(double min, double mean, double max) {
+ assert mean > min;
+ return randomGaussianMeanMax(mean - min, max - min) + min;
+ }
+
+ /**
+ * Within one standard deviation (68% of the time) the result is "close" to
+ * mean. By "close": when greater than mean, it's the lesser of 2*mean or half
+ * way to max, when lesser than mean, it's the greater of max-2*mean or half
+ * way to 0. The other 32% of the time it's in the rest of the range, touching
+ * either 0 or max but never exceeding.
+ */
+ private double randomGaussianMeanMax(double mean, double max) {
+ // DWS: I verified the results empirically
+ assert mean <= max && mean >= 0;
+ double g = randomGaussian();
+ double mean2 = mean;
+ double flip = 1;
+ if (g < 0) {
+ mean2 = max - mean;
+ flip = -1;
+ g *= -1;
+ }
+ // pivot is the distance from mean2 towards max where the boundary of
+ // 1 standard deviation alters the calculation
+ double pivotMax = max - mean2;
+ double pivot = Math.min(mean2, pivotMax / 2);//from 0 to max-mean2
+ assert pivot >= 0 && pivotMax >= pivot && g >= 0;
+ double pivotResult;
+ if (g <= 1)
+ pivotResult = pivot * g;
+ else
+ pivotResult = Math.min(pivotMax, (g - 1) * (pivotMax - pivot) + pivot);
+
+ return mean + flip * pivotResult;
+ }
+
// ================================================= Inner Classes =================================================
protected static class SearchResults {
@@ -116,7 +182,7 @@ public abstract class SpatialTestCase ex
StringBuilder str = new StringBuilder();
str.append("found: ").append(numFound).append('[');
for(SearchResult r : results) {
- String id = r.document.get("id");
+ String id = r.getId();
str.append(id).append(", ");
}
str.append(']');
@@ -138,6 +204,10 @@ public abstract class SpatialTestCase ex
this.score = score;
this.document = storedDocument;
}
+
+ public String getId() {
+ return document.get("id");
+ }
@Override
public String toString() {
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialTestQuery.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialTestQuery.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialTestQuery.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialTestQuery.java Mon Dec 10 16:36:47 2012
@@ -82,6 +82,8 @@ public class SpatialTestQuery {
@Override
public String toString() {
- return line;
+ if (line != null)
+ return line;
+ return args.toString()+" "+ids;
}
}
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/StrategyTestCase.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/StrategyTestCase.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/StrategyTestCase.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/StrategyTestCase.java Mon Dec 10 16:36:47 2012
@@ -31,8 +31,9 @@ import org.apache.lucene.queries.functio
import org.apache.lucene.search.CheckHits;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialArgsParser;
-import org.junit.Assert;
+import org.apache.lucene.spatial.query.SpatialOperation;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -42,6 +43,7 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
@@ -64,7 +66,6 @@ public abstract class StrategyTestCase e
protected final SpatialArgsParser argsParser = new SpatialArgsParser();
protected SpatialStrategy strategy;
- protected SpatialContext ctx;
protected boolean storeShape = true;
protected void executeQueries(SpatialMatchConcern concern, String... testQueryFile) throws IOException {
@@ -82,7 +83,10 @@ public abstract class StrategyTestCase e
}
protected List<Document> getDocuments(String testDataFile) throws IOException {
- Iterator<SampleData> sampleData = getSampleData(testDataFile);
+ return getDocuments(getSampleData(testDataFile));
+ }
+
+ protected List<Document> getDocuments(Iterator<SampleData> sampleData) {
List<Document> documents = new ArrayList<Document>();
while (sampleData.hasNext()) {
SampleData data = sampleData.next();
@@ -128,50 +132,52 @@ public abstract class StrategyTestCase e
SpatialMatchConcern concern) {
while (queries.hasNext()) {
SpatialTestQuery q = queries.next();
+ runTestQuery(concern, q);
+ }
+ }
+
+ public void runTestQuery(SpatialMatchConcern concern, SpatialTestQuery q) {
+ String msg = q.toString(); //"Query: " + q.args.toString(ctx);
+ SearchResults got = executeQuery(strategy.makeQuery(q.args), Math.max(100, q.ids.size()+1));
+ if (storeShape && got.numFound > 0) {
+ //check stored value is there & parses
+ assertNotNull(ctx.readShape(got.results.get(0).document.get(strategy.getFieldName())));
+ }
+ if (concern.orderIsImportant) {
+ Iterator<String> ids = q.ids.iterator();
+ for (SearchResult r : got.results) {
+ String id = r.document.get("id");
+ if (!ids.hasNext()) {
+ fail(msg + " :: Did not get enough results. Expect" + q.ids + ", got: " + got.toDebugString());
+ }
+ assertEquals("out of order: " + msg, ids.next(), id);
+ }
- String msg = q.line; //"Query: " + q.args.toString(ctx);
- SearchResults got = executeQuery(strategy.makeQuery(q.args), 100);
- if (storeShape && got.numFound > 0) {
- //check stored value is there & parses
- assertNotNull(ctx.readShape(got.results.get(0).document.get(strategy.getFieldName())));
+ if (ids.hasNext()) {
+ fail(msg + " :: expect more results then we got: " + ids.next());
}
- if (concern.orderIsImportant) {
- Iterator<String> ids = q.ids.iterator();
+ } else {
+ // We are looking at how the results overlap
+ if (concern.resultsAreSuperset) {
+ Set<String> found = new HashSet<String>();
for (SearchResult r : got.results) {
- String id = r.document.get("id");
- if(!ids.hasNext()) {
- Assert.fail(msg + " :: Did not get enough results. Expect" + q.ids+", got: "+got.toDebugString());
- }
- Assert.assertEquals( "out of order: " + msg, ids.next(), id);
+ found.add(r.document.get("id"));
}
-
- if (ids.hasNext()) {
- Assert.fail(msg + " :: expect more results then we got: " + ids.next());
+ for (String s : q.ids) {
+ if (!found.contains(s)) {
+ fail("Results are mising id: " + s + " :: " + found);
+ }
}
} else {
- // We are looking at how the results overlap
- if( concern.resultsAreSuperset ) {
- Set<String> found = new HashSet<String>();
- for (SearchResult r : got.results) {
- found.add(r.document.get("id"));
- }
- for( String s : q.ids ) {
- if( !found.contains( s ) ) {
- Assert.fail( "Results are mising id: "+s + " :: " + found );
- }
- }
+ List<String> found = new ArrayList<String>();
+ for (SearchResult r : got.results) {
+ found.add(r.document.get("id"));
}
- else {
- List<String> found = new ArrayList<String>();
- for (SearchResult r : got.results) {
- found.add(r.document.get("id"));
- }
- // sort both so that the order is not important
- Collections.sort(q.ids);
- Collections.sort(found);
- Assert.assertEquals(msg, q.ids.toString(), found.toString());
- }
+ // sort both so that the order is not important
+ Collections.sort(q.ids);
+ Collections.sort(found);
+ assertEquals(msg, q.ids.toString(), found.toString());
}
}
}
@@ -218,4 +224,19 @@ public abstract class StrategyTestCase e
CheckHits.checkExplanations(q, "", indexSearcher);
}
+ protected void assertOperation(Map<String,Shape> indexedDocs,
+ SpatialOperation operation, Shape queryShape) {
+ //Generate truth via brute force
+ Set<String> expectedIds = new HashSet<String>();
+ for (Map.Entry<String, Shape> stringShapeEntry : indexedDocs.entrySet()) {
+ if (operation.evaluate(stringShapeEntry.getValue(), queryShape))
+ expectedIds.add(stringShapeEntry.getKey());
+ }
+
+ SpatialTestQuery testQuery = new SpatialTestQuery();
+ testQuery.args = new SpatialArgs(operation, queryShape);
+ testQuery.ids = new ArrayList<String>(expectedIds);
+ runTestQuery(SpatialMatchConcern.FILTER, testQuery);
+ }
+
}
Modified: lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/TestTestFramework.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/TestTestFramework.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/TestTestFramework.java (original)
+++ lucene/dev/branches/lucene4547/lucene/spatial/src/test/org/apache/lucene/spatial/TestTestFramework.java Mon Dec 10 16:36:47 2012
@@ -59,4 +59,11 @@ public class TestTestFramework extends L
Assert.assertEquals( SpatialOperation.Intersects, sf.args.getOperation() );
}
+ @Test
+ public void spatialExample() throws IOException {
+ //kind of a hack so that SpatialExample is tested despite
+ // it not starting or ending with "Test".
+ SpatialExample.main(null);
+ }
+
}
Modified: lucene/dev/branches/lucene4547/lucene/suggest/src/java/org/apache/lucene/search/spell/WordBreakSpellChecker.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/lucene4547/lucene/suggest/src/java/org/apache/lucene/search/spell/WordBreakSpellChecker.java?rev=1419570&r1=1419569&r2=1419570&view=diff
==============================================================================
--- lucene/dev/branches/lucene4547/lucene/suggest/src/java/org/apache/lucene/search/spell/WordBreakSpellChecker.java (original)
+++ lucene/dev/branches/lucene4547/lucene/suggest/src/java/org/apache/lucene/search/spell/WordBreakSpellChecker.java Mon Dec 10 16:36:47 2012
@@ -180,35 +180,32 @@ public class WordBreakSpellChecker {
queueInitialCapacity, queueComparator);
int thisTimeEvaluations = 0;
- BytesRef reuse = new BytesRef();
for (int i = 0; i < terms.length - 1; i++) {
if (terms[i].equals(SEPARATOR_TERM)) {
continue;
- }
-
- int byteLength = terms[i].bytes().length;
- if (byteLength > maxCombineWordLength) {
- continue;
- }
-
- reuse.grow(byteLength);
- reuse.length = byteLength;
- System.arraycopy(terms[i].bytes().bytes, terms[i].bytes().offset,
- reuse.bytes, 0, byteLength);
-
+ }
+ String leftTermText = terms[i].text();
+ int leftTermLength = leftTermText.codePointCount(0, leftTermText.length());
+ if (leftTermLength > maxCombineWordLength) {
+ continue;
+ }
int maxFreq = 0;
int minFreq = Integer.MAX_VALUE;
if (origFreqs != null) {
maxFreq = origFreqs[i];
minFreq = origFreqs[i];
- }
-
+ }
+ String combinedTermText = leftTermText;
+ int combinedLength = leftTermLength;
for (int j = i + 1; j < terms.length && j - i <= maxChanges; j++) {
if (terms[j].equals(SEPARATOR_TERM)) {
break;
}
- byteLength += terms[j].bytes().length;
- if (byteLength > maxCombineWordLength) {
+ String rightTermText = terms[j].text();
+ int rightTermLength = rightTermText.codePointCount(0, rightTermText.length());
+ combinedTermText += rightTermText;
+ combinedLength +=rightTermLength;
+ if (combinedLength > maxCombineWordLength) {
break;
}
@@ -216,13 +213,8 @@ public class WordBreakSpellChecker {
maxFreq = Math.max(maxFreq, origFreqs[j]);
minFreq = Math.min(minFreq, origFreqs[j]);
}
-
- reuse.grow(byteLength);
- System.arraycopy(terms[j].bytes().bytes, terms[j].bytes().offset,
- reuse.bytes, reuse.length, terms[j].bytes().length);
- reuse.length = byteLength;
-
- Term combinedTerm = new Term(terms[0].field(), reuse);
+
+ Term combinedTerm = new Term(terms[0].field(), combinedTermText);
int combinedTermFreq = ir.docFreq(combinedTerm);
if (suggestMode != SuggestMode.SUGGEST_MORE_POPULAR
@@ -268,24 +260,25 @@ public class WordBreakSpellChecker {
SuggestWord[] prefix, Queue<SuggestWordArrayWrapper> suggestions,
int totalEvaluations, BreakSuggestionSortMethod sortMethod)
throws IOException {
- int termLength = term.bytes().length;
+ String termText = term.text();
+ int termLength = termText.codePointCount(0, termText.length());
int useMinBreakWordLength = minBreakWordLength;
if (useMinBreakWordLength < 1) {
useMinBreakWordLength = 1;
}
- if (termLength <= (useMinBreakWordLength * 2)) {
+ if (termLength < (useMinBreakWordLength * 2)) {
return 0;
- }
+ }
int thisTimeEvaluations = 0;
- BytesRef termBytes = term.bytes().clone();
- for (int i = useMinBreakWordLength; i < (termLength - useMinBreakWordLength); i++) {
- SuggestWord leftWord = generateSuggestWord(ir, termBytes, 0, i, term
- .field());
+ for (int i = useMinBreakWordLength; i <= (termLength - useMinBreakWordLength); i++) {
+ int end = termText.offsetByCodePoints(0, i);
+ String leftText = termText.substring(0, end);
+ String rightText = termText.substring(end);
+ SuggestWord leftWord = generateSuggestWord(ir, term.field(), leftText);
if (leftWord.freq >= useMinSuggestionFrequency) {
- SuggestWord rightWord = generateSuggestWord(ir, termBytes, i,
- termLength - i, term.field());
+ SuggestWord rightWord = generateSuggestWord(ir, term.field(), rightText);
if (rightWord.freq >= useMinSuggestionFrequency) {
SuggestWordArrayWrapper suggestion = new SuggestWordArrayWrapper(
newSuggestion(prefix, leftWord, rightWord));
@@ -293,8 +286,7 @@ public class WordBreakSpellChecker {
if (suggestions.size() > maxSuggestions) {
suggestions.poll();
}
- }
-
+ }
int newNumberBreaks = numberBreaks + 1;
if (newNumberBreaks <= maxChanges) {
int evaluations = generateBreakUpSuggestions(new Term(term.field(),
@@ -304,6 +296,7 @@ public class WordBreakSpellChecker {
totalEvaluations += evaluations;
}
}
+
thisTimeEvaluations++;
totalEvaluations++;
if (totalEvaluations >= maxEvaluations) {
@@ -338,16 +331,13 @@ public class WordBreakSpellChecker {
return newSuggestion;
}
- private SuggestWord generateSuggestWord(IndexReader ir, BytesRef bytes,
- int offset, int length, String fieldname) throws IOException {
- bytes.offset = offset;
- bytes.length = length;
- Term term = new Term(fieldname, bytes);
+ private SuggestWord generateSuggestWord(IndexReader ir, String fieldname, String text) throws IOException {
+ Term term = new Term(fieldname, text);
int freq = ir.docFreq(term);
SuggestWord word = new SuggestWord();
word.freq = freq;
word.score = 1;
- word.string = term.text();
+ word.string = text;
return word;
}