You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by dw...@apache.org on 2011/04/14 13:16:44 UTC
svn commit: r1092136 [3/3] - in /lucene/dev/trunk/solr: ./
src/java/org/apache/solr/handler/component/
src/java/org/apache/solr/spelling/suggest/
src/java/org/apache/solr/spelling/suggest/fst/ src/test-files/
src/test-files/solr/conf/ src/test/org/apac...
Modified: lucene/dev/trunk/solr/src/test-files/solr/conf/solrconfig-spellchecker.xml
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test-files/solr/conf/solrconfig-spellchecker.xml?rev=1092136&r1=1092135&r2=1092136&view=diff
==============================================================================
--- lucene/dev/trunk/solr/src/test-files/solr/conf/solrconfig-spellchecker.xml (original)
+++ lucene/dev/trunk/solr/src/test-files/solr/conf/solrconfig-spellchecker.xml Thu Apr 14 11:16:43 2011
@@ -31,7 +31,7 @@
<requestHandler name="standard" class="solr.StandardRequestHandler" />
<!-- Suggest component -->
- <searchComponent class="solr.SpellCheckComponent" name="suggest">
+ <searchComponent class="solr.SpellCheckComponent" name="suggest_jaspell">
<lst name="spellchecker">
<str name="name">suggest</str>
<str name="classname">org.apache.solr.spelling.suggest.Suggester</str>
@@ -45,6 +45,38 @@
</lst>
</searchComponent>
+ <!-- TSTLookup suggest component -->
+ <searchComponent class="solr.SpellCheckComponent" name="suggest_tst">
+ <lst name="spellchecker">
+ <str name="name">suggest_tst</str>
+ <str name="classname">org.apache.solr.spelling.suggest.Suggester</str>
+ <str name="lookupImpl">org.apache.solr.spelling.suggest.tst.TSTLookup</str>
+ <str name="field">suggest</str>
+ <str name="storeDir">suggest_tst</str>
+ <str name="buildOnCommit">true</str>
+
+ <!-- Suggester properties -->
+ <float name="threshold">0.0</float>
+ </lst>
+ </searchComponent>
+
+ <!-- FSTLookup suggest component -->
+ <searchComponent class="solr.SpellCheckComponent" name="suggest_fst">
+ <lst name="spellchecker">
+ <str name="name">suggest_fst</str>
+ <str name="classname">org.apache.solr.spelling.suggest.Suggester</str>
+ <str name="lookupImpl">org.apache.solr.spelling.suggest.fst.FSTLookup</str>
+ <str name="field">suggest</str>
+ <str name="storeDir">suggest_fst</str>
+ <str name="buildOnCommit">true</str>
+
+ <!-- Suggester properties -->
+ <int name="weightBuckets">5</int>
+ <bool name="exactMatchFirst">true</bool>
+ </lst>
+ </searchComponent>
+
+ <!-- The default (jaspell) -->
<requestHandler class="org.apache.solr.handler.component.SearchHandler" name="/suggest">
<lst name="defaults">
<str name="spellcheck">true</str>
@@ -52,8 +84,32 @@
<str name="spellcheck.collate">true</str>
</lst>
<arr name="components">
- <str>suggest</str>
+ <str>suggest_jaspell</str>
</arr>
</requestHandler>
+ <!-- tst (ternary tree based) -->
+ <requestHandler class="org.apache.solr.handler.component.SearchHandler" name="/suggest_tst">
+ <lst name="defaults">
+ <str name="spellcheck">true</str>
+ <str name="spellcheck.dictionary">suggest_tst</str>
+ <str name="spellcheck.collate">true</str>
+ </lst>
+ <arr name="components">
+ <str>suggest_tst</str>
+ </arr>
+ </requestHandler>
+
+ <!-- fst (finite state automaton based) -->
+ <requestHandler class="org.apache.solr.handler.component.SearchHandler" name="/suggest_fst">
+ <lst name="defaults">
+ <str name="spellcheck">true</str>
+ <str name="spellcheck.dictionary">suggest_fst</str>
+ <str name="spellcheck.collate">false</str>
+ </lst>
+ <arr name="components">
+ <str>suggest_fst</str>
+ </arr>
+ </requestHandler>
+
</config>
Added: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/Average.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/Average.java?rev=1092136&view=auto
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/Average.java (added)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/Average.java Thu Apr 14 11:16:43 2011
@@ -0,0 +1,52 @@
+package org.apache.solr.spelling.suggest;
+
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Average with standard deviation.
+ */
+final class Average
+{
+ /**
+ * Average (in milliseconds).
+ */
+ public final double avg;
+
+ /**
+ * Standard deviation (in milliseconds).
+ */
+ public final double stddev;
+
+ /**
+ *
+ */
+ Average(double avg, double stddev)
+ {
+ this.avg = avg;
+ this.stddev = stddev;
+ }
+
+ public String toString()
+ {
+ return String.format(Locale.ENGLISH, "%.0f [+- %.2f]",
+ avg, stddev);
+ }
+
+ static Average from(List<Double> values)
+ {
+ double sum = 0;
+ double sumSquares = 0;
+
+ for (double l : values)
+ {
+ sum += l;
+ sumSquares += l * l;
+ }
+
+ double avg = sum / (double) values.size();
+ return new Average(
+ (sum / (double) values.size()),
+ Math.sqrt(sumSquares / (double) values.size() - avg * avg));
+ }
+}
\ No newline at end of file
Added: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/LookupBenchmarkTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/LookupBenchmarkTest.java?rev=1092136&view=auto
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/LookupBenchmarkTest.java (added)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/LookupBenchmarkTest.java Thu Apr 14 11:16:43 2011
@@ -0,0 +1,230 @@
+package org.apache.solr.spelling.suggest;
+
+import java.net.URL;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.Random;
+import java.util.concurrent.Callable;
+
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.solr.spelling.suggest.fst.FSTLookup;
+import org.apache.solr.spelling.suggest.jaspell.JaspellLookup;
+import org.apache.solr.spelling.suggest.tst.TSTLookup;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import com.google.common.base.Charsets;
+import com.google.common.base.Function;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.io.Resources;
+
+/**
+ * Benchmarks tests for implementations of {@link Lookup} interface.
+ */
+@Ignore // COMMENT ME TO RUN BENCHMARKS!
+public class LookupBenchmarkTest {
+ @SuppressWarnings("unchecked")
+ private final List<Class<? extends Lookup>> benchmarkClasses = Lists.newArrayList(
+ JaspellLookup.class,
+ TSTLookup.class,
+ FSTLookup.class);
+
+ private final static int rounds = 15;
+ private final static int warmup = 5;
+
+ private final int num = 7;
+ private final boolean onlyMorePopular = true;
+
+ private final static Random random = new Random(0xdeadbeef);
+
+ /**
+ * Input term/weight pairs.
+ */
+ private static TermFreq [] dictionaryInput;
+
+ /**
+ * Benchmark term/weight pairs (randomized order).
+ */
+ private static List<TermFreq> benchmarkInput;
+
+ /**
+ * Loads terms and frequencies from Wikipedia (cached).
+ */
+ @BeforeClass
+ public static void setup() throws Exception {
+ List<TermFreq> input = readTop50KWiki();
+ Collections.shuffle(input, random);
+ LookupBenchmarkTest.dictionaryInput = input.toArray(new TermFreq [input.size()]);
+ Collections.shuffle(input, random);
+ LookupBenchmarkTest.benchmarkInput = input;
+ }
+
+ /**
+ * Collect the multilingual input for benchmarks/ tests.
+ */
+ public static List<TermFreq> readTop50KWiki() throws Exception {
+ List<TermFreq> input = Lists.newArrayList();
+ URL resource = Thread.currentThread().getContextClassLoader().getResource("Top50KWiki.utf8");
+ assert resource != null : "Resource missing: Top50KWiki.utf8";
+
+ for (String line : Resources.readLines(resource, Charsets.UTF_8)) {
+ int tab = line.indexOf('|');
+ Assert.assertTrue("No | separator?: " + line, tab >= 0);
+ float weight = Float.parseFloat(line.substring(tab + 1));
+ String key = line.substring(0, tab);
+ input.add(new TermFreq(key, weight));
+ }
+ return input;
+ }
+
+ /**
+ * Test construction time.
+ */
+ @Test
+ public void testConstructionTime() throws Exception {
+ System.err.println("-- construction time");
+ for (final Class<? extends Lookup> cls : benchmarkClasses) {
+ BenchmarkResult result = measure(new Callable<Integer>() {
+ public Integer call() throws Exception {
+ final Lookup lookup = buildLookup(cls, dictionaryInput);
+ return lookup.hashCode();
+ }
+ });
+
+ System.err.println(
+ String.format(Locale.ENGLISH, "%-15s input: %d, time[ms]: %s",
+ cls.getSimpleName(),
+ dictionaryInput.length,
+ result.average.toString()));
+ }
+ }
+
+ /**
+ * Test memory required for the storage.
+ */
+ @Test
+ public void testStorageNeeds() throws Exception {
+ System.err.println("-- RAM consumption");
+ final RamUsageEstimator rue = new RamUsageEstimator();
+ for (Class<? extends Lookup> cls : benchmarkClasses) {
+ Lookup lookup = buildLookup(cls, dictionaryInput);
+ System.err.println(
+ String.format(Locale.ENGLISH, "%-15s size[B]:%,13d",
+ lookup.getClass().getSimpleName(),
+ rue.estimateRamUsage(lookup)));
+ }
+ }
+
+ /**
+ * Create {@link Lookup} instance and populate it.
+ */
+ private Lookup buildLookup(Class<? extends Lookup> cls, TermFreq[] input) throws Exception {
+ Lookup lookup = cls.newInstance();
+ lookup.build(new TermFreqArrayIterator(input));
+ return lookup;
+ }
+
+ /**
+ * Test performance of lookup on full hits.
+ */
+ @Test
+ public void testPerformanceOnFullHits() throws Exception {
+ final int minPrefixLen = 100;
+ final int maxPrefixLen = 200;
+ runPerformanceTest(minPrefixLen, maxPrefixLen, num, onlyMorePopular);
+ }
+
+ /**
+ * Test performance of lookup on longer term prefixes (6-9 letters or shorter).
+ */
+ @Test
+ public void testPerformanceOnPrefixes6_9() throws Exception {
+ final int minPrefixLen = 6;
+ final int maxPrefixLen = 9;
+ runPerformanceTest(minPrefixLen, maxPrefixLen, num, onlyMorePopular);
+ }
+
+ /**
+ * Test performance of lookup on short term prefixes (2-4 letters or shorter).
+ */
+ @Test
+ public void testPerformanceOnPrefixes2_4() throws Exception {
+ final int minPrefixLen = 2;
+ final int maxPrefixLen = 4;
+ runPerformanceTest(minPrefixLen, maxPrefixLen, num, onlyMorePopular);
+ }
+
+ /**
+ * Run the actual benchmark.
+ */
+ public void runPerformanceTest(final int minPrefixLen, final int maxPrefixLen,
+ final int num, final boolean onlyMorePopular) throws Exception {
+ System.err.println(String.format(Locale.ENGLISH,
+ "-- prefixes: %d-%d, num: %d, onlyMorePopular: %s",
+ minPrefixLen, maxPrefixLen, num, onlyMorePopular));
+
+ for (Class<? extends Lookup> cls : benchmarkClasses) {
+ final Lookup lookup = buildLookup(cls, dictionaryInput);
+
+ final List<String> input = Lists.newArrayList(Iterables.transform(benchmarkInput, new Function<TermFreq, String>() {
+ public String apply(TermFreq tf) {
+ return tf.term.substring(0, Math.min(tf.term.length(),
+ minPrefixLen + random.nextInt(maxPrefixLen - minPrefixLen + 1)));
+ }
+ }));
+
+ BenchmarkResult result = measure(new Callable<Integer>() {
+ public Integer call() throws Exception {
+ int v = 0;
+ for (String term : input) {
+ v += lookup.lookup(term, onlyMorePopular, num).size();
+ }
+ return v;
+ }
+ });
+
+ System.err.println(
+ String.format(Locale.ENGLISH, "%-15s queries: %d, time[ms]: %s, ~qps: %.0f",
+ lookup.getClass().getSimpleName(),
+ input.size(),
+ result.average.toString(),
+ input.size() / result.average.avg));
+ }
+ }
+
+ /**
+ * Do the measurements.
+ */
+ private BenchmarkResult measure(Callable<Integer> callable) {
+ final double NANOS_PER_MS = 1000000;
+
+ try {
+ List<Double> times = Lists.newArrayList();
+ for (int i = 0; i < warmup + rounds; i++) {
+ final long start = System.nanoTime();
+ guard = callable.call().intValue();
+ times.add((System.nanoTime() - start) / NANOS_PER_MS);
+ }
+ return new BenchmarkResult(times, warmup, rounds);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /** Guard against opts. */
+ @SuppressWarnings("unused")
+ private static volatile int guard;
+
+ private static class BenchmarkResult {
+ /** Average time per round (ms). */
+ public final Average average;
+
+ public BenchmarkResult(List<Double> times, int warmup, int rounds) {
+ this.average = Average.from(times.subList(warmup, times.size()));
+ }
+ }
+}
\ No newline at end of file
Modified: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/PersistenceTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/PersistenceTest.java?rev=1092136&r1=1092135&r2=1092136&view=diff
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/PersistenceTest.java (original)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/PersistenceTest.java Thu Apr 14 11:16:43 2011
@@ -19,62 +19,74 @@ package org.apache.solr.spelling.suggest
import java.io.File;
import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.spelling.suggest.fst.FSTLookup;
import org.apache.solr.spelling.suggest.jaspell.JaspellLookup;
import org.apache.solr.spelling.suggest.tst.TSTLookup;
import org.junit.Test;
public class PersistenceTest extends SolrTestCaseJ4 {
-
- public static final String[] keys = new String[] {
- "one",
- "two",
- "three",
- "four",
- "oneness",
- "onerous",
- "onesimus",
- "twofold",
- "twonk",
- "thrive",
- "through",
- "threat",
- "foundation",
- "fourier",
- "fourty"
- };
+ public final String[] keys = new String[] {
+ "one",
+ "two",
+ "three",
+ "four",
+ "oneness",
+ "onerous",
+ "onesimus",
+ "twofold",
+ "twonk",
+ "thrive",
+ "through",
+ "threat",
+ "foundation",
+ "fourier",
+ "fourty"};
@Test
public void testTSTPersistence() throws Exception {
- TSTLookup lookup = new TSTLookup();
- for (String k : keys) {
- lookup.add(k, new Float(k.length()));
- }
- File storeDir = new File(TEST_HOME());
- lookup.store(storeDir);
- lookup = new TSTLookup();
- lookup.load(storeDir);
- for (String k : keys) {
- Float val = (Float)lookup.get(k);
- assertNotNull(k, val);
- assertEquals(k, k.length(), val.intValue());
- }
+ runTest(TSTLookup.class, true);
}
@Test
public void testJaspellPersistence() throws Exception {
- JaspellLookup lookup = new JaspellLookup();
- for (String k : keys) {
- lookup.add(k, new Float(k.length()));
- }
+ runTest(JaspellLookup.class, true);
+ }
+
+ @Test
+ public void testFSTPersistence() throws Exception {
+ runTest(FSTLookup.class, false);
+ }
+
+ private void runTest(Class<? extends Lookup> lookupClass,
+ boolean supportsExactWeights) throws Exception {
+
+ // Add all input keys.
+ Lookup lookup = lookupClass.newInstance();
+ TermFreq[] keys = new TermFreq[this.keys.length];
+ for (int i = 0; i < keys.length; i++)
+ keys[i] = new TermFreq(this.keys[i], (float) i);
+ lookup.build(new TermFreqArrayIterator(keys));
+
+ // Store the suggester.
File storeDir = new File(TEST_HOME());
lookup.store(storeDir);
- lookup = new JaspellLookup();
+
+ // Re-read it from disk.
+ lookup = lookupClass.newInstance();
lookup.load(storeDir);
- for (String k : keys) {
- Float val = (Float)lookup.get(k);
- assertNotNull(k, val);
- assertEquals(k, k.length(), val.intValue());
+
+ // Assert validity.
+ float previous = Float.NEGATIVE_INFINITY;
+ for (TermFreq k : keys) {
+ Float val = (Float) lookup.get(k.term);
+ assertNotNull(k.term, val);
+
+ if (supportsExactWeights) {
+ assertEquals(k.term, Float.valueOf(k.v), val);
+ } else {
+ assertTrue(val + ">=" + previous, val >= previous);
+ previous = val.floatValue();
+ }
}
}
-
}
Added: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterFSTTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterFSTTest.java?rev=1092136&view=auto
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterFSTTest.java (added)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterFSTTest.java Thu Apr 14 11:16:43 2011
@@ -0,0 +1,7 @@
+package org.apache.solr.spelling.suggest;
+
+public class SuggesterFSTTest extends SuggesterTest {
+ public SuggesterFSTTest() {
+ super.requestUri = "/suggest_fst";
+ }
+}
Added: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterTSTTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterTSTTest.java?rev=1092136&view=auto
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterTSTTest.java (added)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterTSTTest.java Thu Apr 14 11:16:43 2011
@@ -0,0 +1,7 @@
+package org.apache.solr.spelling.suggest;
+
+public class SuggesterTSTTest extends SuggesterTest {
+ public SuggesterTSTTest() {
+ super.requestUri = "/suggest_tst";
+ }
+}
Modified: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterTest.java?rev=1092136&r1=1092135&r2=1092136&view=diff
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterTest.java (original)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/SuggesterTest.java Thu Apr 14 11:16:43 2011
@@ -17,28 +17,19 @@
package org.apache.solr.spelling.suggest;
-import org.apache.lucene.util.RamUsageEstimator;
+import java.io.File;
+
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.params.SpellingParams;
-import org.apache.solr.spelling.suggest.Lookup.LookupResult;
-import org.apache.solr.spelling.suggest.jaspell.JaspellLookup;
-import org.apache.solr.spelling.suggest.tst.TSTLookup;
-import org.apache.solr.util.TermFreqIterator;
import org.junit.BeforeClass;
-import org.junit.Ignore;
import org.junit.Test;
-import com.google.common.collect.Lists;
-
-import java.io.File;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Random;
-
public class SuggesterTest extends SolrTestCaseJ4 {
+ /**
+ * Expected URI at which the given suggester will live.
+ */
+ protected String requestUri = "/suggest";
+
@BeforeClass
public static void beforeClass() throws Exception {
initCore("solrconfig-spellchecker.xml","schema-spellchecker.xml");
@@ -59,10 +50,9 @@ public class SuggesterTest extends SolrT
@Test
public void testSuggestions() throws Exception {
addDocs();
-
assertU(commit()); // configured to do a rebuild on commit
- assertQ(req("qt","/suggest", "q","ac", SpellingParams.SPELLCHECK_COUNT, "2", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
+ assertQ(req("qt", requestUri, "q", "ac", SpellingParams.SPELLCHECK_COUNT, "2", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/int[@name='numFound'][.='2']",
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/arr[@name='suggestion']/str[1][.='acquire']",
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/arr[@name='suggestion']/str[2][.='accommodate']"
@@ -82,12 +72,12 @@ public class SuggesterTest extends SolrT
dataDir = data;
configString = config;
initCore();
- assertQ(req("qt","/suggest", "q","ac", SpellingParams.SPELLCHECK_COUNT, "2", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
+ assertQ(req("qt", requestUri, "q", "ac", SpellingParams.SPELLCHECK_COUNT, "2", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/int[@name='numFound'][.='2']",
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/arr[@name='suggestion']/str[1][.='acquire']",
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/arr[@name='suggestion']/str[2][.='accommodate']"
);
-
+
// restore the property
System.setProperty("solr.test.leavedatadir", leaveData);
}
@@ -96,132 +86,13 @@ public class SuggesterTest extends SolrT
public void testRebuild() throws Exception {
addDocs();
assertU(commit());
- assertQ(req("qt","/suggest", "q","ac", SpellingParams.SPELLCHECK_COUNT, "2", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
- "//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/int[@name='numFound'][.='2']");
+ assertQ(req("qt", requestUri, "q", "ac", SpellingParams.SPELLCHECK_COUNT, "2", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
+ "//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/int[@name='numFound'][.='2']");
assertU(adoc("id", "4",
"text", "actually"
));
assertU(commit());
- assertQ(req("qt","/suggest", "q","ac", SpellingParams.SPELLCHECK_COUNT, "2", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
- "//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/int[@name='numFound'][.='2']");
- }
-
-
- private TermFreqIterator getTFIT() {
- final int count = 100000;
- TermFreqIterator tfit = new TermFreqIterator() {
- Random r = new Random(1234567890L);
- Random r1 = new Random(1234567890L);
- int pos;
-
- public float freq() {
- return r1.nextInt(4);
- }
-
- public boolean hasNext() {
- return pos < count;
- }
-
- public String next() {
- pos++;
- return Long.toString(r.nextLong());
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- };
- return tfit;
- }
-
- static class Bench {
- long buildTime;
- long lookupTime;
- }
-
- @Test @Ignore
- public void testBenchmark() throws Exception {
- final List<Class<? extends Lookup>> benchmarkClasses = Lists.newArrayList();
- benchmarkClasses.add(JaspellLookup.class);
- benchmarkClasses.add(TSTLookup.class);
-
- // Run a single pass just to see if everything works fine and provide size estimates.
- final RamUsageEstimator rue = new RamUsageEstimator();
- for (Class<? extends Lookup> cls : benchmarkClasses) {
- Lookup lookup = singleBenchmark(cls, null);
- System.err.println(
- String.format(Locale.ENGLISH,
- "%20s, size[B]=%,d",
- lookup.getClass().getSimpleName(),
- rue.estimateRamUsage(lookup)));
- }
-
- int warmupCount = 10;
- int measuredCount = 100;
- for (Class<? extends Lookup> cls : benchmarkClasses) {
- Bench b = fullBenchmark(cls, warmupCount, measuredCount);
- System.err.println(String.format(Locale.ENGLISH,
- "%s: buildTime[ms]=%,d lookupTime[ms]=%,d",
- cls.getSimpleName(),
- (b.buildTime / measuredCount),
- (b.lookupTime / measuredCount / 1000000)));
- }
- }
-
- private Lookup singleBenchmark(Class<? extends Lookup> cls, Bench bench) throws Exception {
- Lookup lookup = cls.newInstance();
-
- long start = System.currentTimeMillis();
- lookup.build(getTFIT());
- long buildTime = System.currentTimeMillis() - start;
-
- TermFreqIterator tfit = getTFIT();
- long elapsed = 0;
- while (tfit.hasNext()) {
- String key = tfit.next();
- // take only the first part of the key
- int len = key.length() > 4 ? key.length() / 3 : 2;
- String prefix = key.substring(0, len);
- start = System.nanoTime();
- List<LookupResult> res = lookup.lookup(prefix, true, 10);
- elapsed += System.nanoTime() - start;
- assertTrue(res.size() > 0);
- for (LookupResult lr : res) {
- assertTrue(lr.key.startsWith(prefix));
- }
- }
-
- if (bench != null) {
- bench.buildTime += buildTime;
- bench.lookupTime += elapsed;
- }
-
- return lookup;
- }
-
- private Bench fullBenchmark(Class<? extends Lookup> cls, int warmupCount, int measuredCount) throws Exception {
- System.err.println("* Running " + measuredCount + " iterations for " + cls.getSimpleName() + " ...");
- System.err.println(" - warm-up " + warmupCount + " iterations...");
- for (int i = 0; i < warmupCount; i++) {
- System.runFinalization();
- System.gc();
- singleBenchmark(cls, null);
- }
-
- Bench b = new Bench();
- System.err.print(" - main iterations:"); System.err.flush();
- for (int i = 0; i < measuredCount; i++) {
- System.runFinalization();
- System.gc();
- singleBenchmark(cls, b);
- if (i > 0 && (i % 10 == 0)) {
- System.err.print(" " + i);
- System.err.flush();
- }
- }
-
- System.err.println();
- return b;
+ assertQ(req("qt", requestUri, "q", "ac", SpellingParams.SPELLCHECK_COUNT, "2", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
+ "//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='ac']/int[@name='numFound'][.='2']");
}
}
Added: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/TermFreq.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/TermFreq.java?rev=1092136&view=auto
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/TermFreq.java (added)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/TermFreq.java Thu Apr 14 11:16:43 2011
@@ -0,0 +1,11 @@
+package org.apache.solr.spelling.suggest;
+
+public final class TermFreq {
+ public final String term;
+ public final float v;
+
+ public TermFreq(String term, float v) {
+ this.term = term;
+ this.v = v;
+ }
+}
\ No newline at end of file
Added: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/TermFreqArrayIterator.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/TermFreqArrayIterator.java?rev=1092136&view=auto
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/TermFreqArrayIterator.java (added)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/TermFreqArrayIterator.java Thu Apr 14 11:16:43 2011
@@ -0,0 +1,40 @@
+package org.apache.solr.spelling.suggest;
+
+import java.util.Arrays;
+import java.util.Iterator;
+
+import org.apache.solr.util.TermFreqIterator;
+
+/**
+ * A {@link TermFreqIterator} over a sequence of {@link TermFreq}s.
+ */
+public final class TermFreqArrayIterator implements TermFreqIterator {
+ private final Iterator<TermFreq> i;
+ private TermFreq current;
+
+ public TermFreqArrayIterator(Iterator<TermFreq> i) {
+ this.i = i;
+ }
+
+ public TermFreqArrayIterator(TermFreq [] i) {
+ this(Arrays.asList(i));
+ }
+
+ public TermFreqArrayIterator(Iterable<TermFreq> i) {
+ this(i.iterator());
+ }
+
+ public float freq() {
+ return current.v;
+ }
+
+ public boolean hasNext() {
+ return i.hasNext();
+ }
+
+ public String next() {
+ return (current = i.next()).term;
+ }
+
+ public void remove() { throw new UnsupportedOperationException(); }
+}
\ No newline at end of file
Added: lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/fst/FSTLookupTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/fst/FSTLookupTest.java?rev=1092136&view=auto
==============================================================================
--- lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/fst/FSTLookupTest.java (added)
+++ lucene/dev/trunk/solr/src/test/org/apache/solr/spelling/suggest/fst/FSTLookupTest.java Thu Apr 14 11:16:43 2011
@@ -0,0 +1,155 @@
+package org.apache.solr.spelling.suggest.fst;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Random;
+
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.solr.spelling.suggest.Lookup.LookupResult;
+import org.apache.solr.spelling.suggest.LookupBenchmarkTest;
+import org.apache.solr.spelling.suggest.TermFreq;
+import org.apache.solr.spelling.suggest.TermFreqArrayIterator;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Unit tests for {@link FSTLookup}.
+ */
+public class FSTLookupTest extends LuceneTestCase {
+ public static TermFreq tf(String t, float v) {
+ return new TermFreq(t, v);
+ }
+
+ private FSTLookup lookup;
+
+ @Before
+ public void prepare() throws Exception {
+ final TermFreq[] keys = new TermFreq[] {
+ tf("one", 0.5f),
+ tf("oneness", 1),
+ tf("onerous", 1),
+ tf("onesimus", 1),
+ tf("two", 1),
+ tf("twofold", 1),
+ tf("twonk", 1),
+ tf("thrive", 1),
+ tf("through", 1),
+ tf("threat", 1),
+ tf("three", 1),
+ tf("foundation", 1),
+ tf("fourier", 1),
+ tf("four", 1),
+ tf("fourty", 1),
+ tf("xo", 1),
+ };
+
+ lookup = new FSTLookup();
+ lookup.build(new TermFreqArrayIterator(keys));
+ }
+
+ @Test
+ public void testExactMatchHighPriority() throws Exception {
+ assertMatchEquals(lookup.lookup("two", true, 1), "two/1.0");
+ }
+
+ @Test
+ public void testExactMatchLowPriority() throws Exception {
+ assertMatchEquals(lookup.lookup("one", true, 2),
+ "one/0.0",
+ "oneness/1.0");
+ }
+
+ @Test
+ public void testMiss() throws Exception {
+ assertMatchEquals(lookup.lookup("xyz", true, 1));
+ }
+
+ @Test
+ public void testAlphabeticWithWeights() throws Exception {
+ assertEquals(0, lookup.lookup("xyz", false, 1).size());
+ }
+
+ @Test
+ public void testFullMatchList() throws Exception {
+ assertMatchEquals(lookup.lookup("one", true, Integer.MAX_VALUE),
+ "oneness/1.0",
+ "onerous/1.0",
+ "onesimus/1.0",
+ "one/0.0");
+ }
+
+ @Test
+ public void testMultilingualInput() throws Exception {
+ List<TermFreq> input = LookupBenchmarkTest.readTop50KWiki();
+
+ lookup = new FSTLookup();
+ lookup.build(new TermFreqArrayIterator(input));
+
+ for (TermFreq tf : input) {
+ assertTrue("Not found: " + tf.term, lookup.get(tf.term) != null);
+ assertEquals(tf.term, lookup.lookup(tf.term, true, 1).get(0).key);
+ }
+ }
+
+ @Test
+ public void testEmptyInput() throws Exception {
+ lookup = new FSTLookup();
+ lookup.build(new TermFreqArrayIterator(new TermFreq[0]));
+
+ assertMatchEquals(lookup.lookup("", true, 10));
+ }
+
+ @Test
+ public void testRandom() throws Exception {
+ List<TermFreq> freqs = Lists.newArrayList();
+ Random rnd = random;
+ for (int i = 0; i < 5000; i++) {
+ freqs.add(new TermFreq("" + rnd.nextLong(), rnd.nextInt(100)));
+ }
+ lookup = new FSTLookup();
+ lookup.build(new TermFreqArrayIterator(freqs.toArray(new TermFreq[freqs.size()])));
+
+ for (TermFreq tf : freqs) {
+ final String term = tf.term;
+ for (int i = 1; i < term.length(); i++) {
+ String prefix = term.substring(0, i);
+ for (LookupResult lr : lookup.lookup(prefix, true, 10)) {
+ Assert.assertTrue(lr.key.startsWith(prefix));
+ }
+ }
+ }
+ }
+
+ private void assertMatchEquals(List<LookupResult> res, String... expected) {
+ String [] result = new String [res.size()];
+ for (int i = 0; i < res.size(); i++)
+ result[i] = res.get(i).toString();
+
+ if (!Arrays.equals(expected, result)) {
+ int colLen = Math.max(maxLen(expected), maxLen(result));
+
+ StringBuilder b = new StringBuilder();
+ String format = "%" + colLen + "s " + "%" + colLen + "s\n";
+ b.append(String.format(Locale.ENGLISH, format, "Expected", "Result"));
+ for (int i = 0; i < Math.max(result.length, expected.length); i++) {
+ b.append(String.format(Locale.ENGLISH, format,
+ i < expected.length ? expected[i] : "--",
+ i < result.length ? result[i] : "--"));
+ }
+
+ System.err.println(b.toString());
+ fail("Expected different output:\n" + b.toString());
+ }
+ }
+
+ private int maxLen(String[] result) {
+ int len = 0;
+ for (String s : result)
+ len = Math.max(len, s.length());
+ return len;
+ }
+}