Index: lucene/contrib/join/src/java/org/apache/lucene/search/join/JoinUtil.java
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- lucene/contrib/join/src/java/org/apache/lucene/search/join/JoinUtil.java	(revision )
+++ lucene/contrib/join/src/java/org/apache/lucene/search/join/JoinUtil.java	(revision )
@@ -0,0 +1,62 @@
+package org.apache.lucene.search.join;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+
+import java.io.IOException;
+
+/**
+ * Utility for query time joining using {@link TermsQuery} and {@link TermsCollector}.
+ *
+ * @lucene.experimental
+ */
+public final class JoinUtil {
+
+  // No instances allowed
+  private JoinUtil() {
+  }
+
+  /**
+   * Method for query time joining.
+   * <p/>
+   * Execute the returned query with a {@link org.apache.lucene.search.IndexSearcher} to retrieve all documents that have the same terms in the
+   * to field that match with documents matching the specified fromQuery and have the same terms in the from field.
+   *
+   * Notice: Can't join documents with fromField that holds more then one term.
+   *
+   *
+   * @param fromField                 The from field to join from
+   * @param toField                   The to field to join to
+   * @param fromQuery                 The query to match documents on the from side
+   * @param fromSearcher              The searcher that executed the specified fromQuery
+   * @return a {@link org.apache.lucene.search.Query} instance that can be used to join documents based on the
+   *         terms in the from and to field
+   * @throws java.io.IOException If I/O related errors occur
+   */
+  public static Query createJoinQuery(String fromField,
+                                      String toField,
+                                      Query fromQuery,
+                                      IndexSearcher fromSearcher) throws IOException {
+    TermsCollector termsCollector = new TermsCollector(fromField);
+    fromSearcher.search(fromQuery, termsCollector);
+    return new TermsQuery(toField, termsCollector.getCollectorTerms());
+  }
+
+}
Index: lucene/contrib/join/src/test/org/apache/lucene/search/TestJoinUtil.java
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- lucene/contrib/join/src/test/org/apache/lucene/search/TestJoinUtil.java	(revision )
+++ lucene/contrib/join/src/test/org/apache/lucene/search/TestJoinUtil.java	(revision )
@@ -0,0 +1,342 @@
+package org.apache.lucene.search;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.lucene.analysis.MockAnalyzer;
+import org.apache.lucene.analysis.MockTokenizer;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.index.*;
+import org.apache.lucene.search.join.JoinUtil;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.util.FixedBitSet;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util._TestUtil;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.*;
+
+public class TestJoinUtil extends LuceneTestCase {
+
+  public void testSimple() throws Exception {
+    final String idField = "id";
+    final String toField = "productId";
+
+    Directory dir = newDirectory();
+    RandomIndexWriter w = new RandomIndexWriter(
+        random,
+        dir,
+        newIndexWriterConfig(TEST_VERSION_CURRENT,
+            new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
+
+    // 0
+    Document doc = new Document();
+    doc.add(new Field("description", "random text", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field("name", "name1", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(idField, "1", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    w.addDocument(doc);
+
+    // 1
+    doc = new Document();
+    doc.add(new Field("price", "10.0", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(idField, "2", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(toField, "1", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    w.addDocument(doc);
+
+    // 2
+    doc = new Document();
+    doc.add(new Field("price", "20.0", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(idField, "3", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(toField, "1", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    w.addDocument(doc);
+
+    // 3
+    doc = new Document();
+    doc.add(new Field("description", "more random text", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field("name", "name2", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(idField, "4", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    w.addDocument(doc);
+    w.commit();
+
+    // 4
+    doc = new Document();
+    doc.add(new Field("price", "10.0", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(idField, "5", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(toField, "4", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    w.addDocument(doc);
+
+    // 5
+    doc = new Document();
+    doc.add(new Field("price", "20.0", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(idField, "6", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    doc.add(new Field(toField, "4", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+    w.addDocument(doc);
+
+    IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
+    w.close();
+
+    // Search for product
+    Query joinQuery =
+        JoinUtil.createJoinQuery(idField, toField, new TermQuery(new Term("name", "name2")), indexSearcher);
+
+    TopDocs result = indexSearcher.search(joinQuery, 10);
+    assertEquals(2, result.totalHits);
+    assertEquals(4, result.scoreDocs[0].doc);
+    assertEquals(5, result.scoreDocs[1].doc);
+
+    joinQuery = JoinUtil.createJoinQuery(idField, toField, new TermQuery(new Term("name", "name1")), indexSearcher);
+    result = indexSearcher.search(joinQuery, 10);
+    assertEquals(2, result.totalHits);
+    assertEquals(1, result.scoreDocs[0].doc);
+    assertEquals(2, result.scoreDocs[1].doc);
+
+    // Search for offer
+    joinQuery = JoinUtil.createJoinQuery(toField, idField, new TermQuery(new Term("id", "5")), indexSearcher);
+    result = indexSearcher.search(joinQuery, 10);
+    assertEquals(1, result.totalHits);
+    assertEquals(3, result.scoreDocs[0].doc);
+
+    indexSearcher.getIndexReader().close();
+    dir.close();
+  }
+
+  @Test
+  public void testRandom() throws Exception {
+    int maxIndexIter = _TestUtil.nextInt(random, 6, 12);
+    for (int indexIter = 1; indexIter <= maxIndexIter; indexIter++) {
+      if (VERBOSE) {
+        System.out.println("indexIter=" + indexIter);
+      }
+      Directory dir = newDirectory();
+      RandomIndexWriter w = new RandomIndexWriter(
+          random,
+          dir,
+          newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random, MockTokenizer.KEYWORD, false)).setMergePolicy(newLogMergePolicy())
+      );
+      int numberOfDocumentsToIndex = TEST_NIGHTLY ? _TestUtil.nextInt(random, 7889, 14632) : _TestUtil.nextInt(random, 87, 764);
+      IndexIterationContext context = createContext(numberOfDocumentsToIndex, w, false);
+
+      IndexReader topLevelReader = w.getReader();
+      w.close();
+      int maxSearchIter = _TestUtil.nextInt(random, 13, 26);
+      for (int searchIter = 1; searchIter <= maxSearchIter; searchIter++) {
+        if (VERBOSE) {
+          System.out.println("searchIter=" + searchIter);
+        }
+        IndexSearcher indexSearcher = newSearcher(topLevelReader);
+
+        int r = random.nextInt(context.randomUniqueValues.length);
+        boolean from = context.randomFrom[r];
+        String randomValue = context.randomUniqueValues[r];
+        FixedBitSet expectedResult = createExpectedResult(randomValue, from, indexSearcher, context);
+
+        Query actualQuery = new TermQuery(new Term("value", randomValue));
+        if (VERBOSE) {
+          System.out.println("actualQuery=" + actualQuery);
+        }
+        Query joinQuery;
+        if (from) {
+          joinQuery = JoinUtil.createJoinQuery("from", "to", actualQuery, indexSearcher);
+        } else {
+          joinQuery = JoinUtil.createJoinQuery("to", "from", actualQuery, indexSearcher);
+        }
+        if (VERBOSE) {
+          System.out.println("joinQuery=" + joinQuery);
+        }
+
+        // Need to know all documents that have matches. TopDocs doesn't give me that and then I'd be also testing TopDocsCollector...
+        final FixedBitSet actualResult = new FixedBitSet(indexSearcher.getIndexReader().maxDoc());
+        indexSearcher.search(joinQuery, new Collector() {
+
+          int docBase;
+
+          public void collect(int doc) throws IOException {
+            actualResult.set(doc + docBase);
+          }
+
+          public void setNextReader(IndexReader reader, int docBase) throws IOException {
+            this.docBase = docBase;
+          }
+
+          public void setScorer(Scorer scorer) throws IOException {
+          }
+
+          public boolean acceptsDocsOutOfOrder() {
+            return true;
+          }
+        });
+
+        if (VERBOSE) {
+          System.out.println("expected cardinality:" + expectedResult.cardinality());
+          DocIdSetIterator iterator = expectedResult.iterator();
+          for (int doc = iterator.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = iterator.nextDoc()) {
+            System.out.println(String.format("Expected doc[%d] with id value %s", doc, indexSearcher.doc(doc).get("id")));
+          }
+          System.out.println("actual cardinality:" + actualResult.cardinality());
+          iterator = actualResult.iterator();
+          for (int doc = iterator.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = iterator.nextDoc()) {
+            System.out.println(String.format("Actual doc[%d] with id value %s", doc, indexSearcher.doc(doc).get("id")));
+          }
+        }
+
+        assertEquals(expectedResult, actualResult);
+        indexSearcher.close();
+      }
+      topLevelReader.close();
+      dir.close();
+    }
+  }
+
+  private IndexIterationContext createContext(int nDocs, RandomIndexWriter writer, boolean multipleValuesPerDocument) throws IOException {
+    return createContext(nDocs, writer, writer, multipleValuesPerDocument);
+  }
+
+  private IndexIterationContext createContext(int nDocs, RandomIndexWriter fromWriter, RandomIndexWriter toWriter, boolean multipleValuesPerDocument) throws IOException {
+    IndexIterationContext context = new IndexIterationContext();
+    int numRandomValues = nDocs / 2;
+    context.randomUniqueValues = new String[numRandomValues];
+    Set<String> trackSet = new HashSet<String>();
+    context.randomFrom = new boolean[numRandomValues];
+    for (int i = 0; i < numRandomValues; i++) {
+      String uniqueRandomValue;
+      do {
+        uniqueRandomValue = _TestUtil.randomRealisticUnicodeString(random);
+//        uniqueRandomValue = _TestUtil.randomSimpleString(random);
+      } while ("".equals(uniqueRandomValue) || trackSet.contains(uniqueRandomValue));
+      // Generate unique values and empty strings aren't allowed.
+      trackSet.add(uniqueRandomValue);
+      context.randomFrom[i] = random.nextBoolean();
+      context.randomUniqueValues[i] = uniqueRandomValue;
+    }
+
+    for (int i = 0; i < nDocs; i++) {
+      String id = Integer.toString(i);
+      int randomI = random.nextInt(context.randomUniqueValues.length);
+      String value = context.randomUniqueValues[randomI];
+      Document document = new Document();
+      document.add(newField(random, "id", id, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+      document.add(newField(random, "value", value, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+
+      boolean from = context.randomFrom[randomI];
+      int numberOfLinkValues = multipleValuesPerDocument ? 2 + random.nextInt(10) : 1;
+      RandomDoc doc = new RandomDoc(id, numberOfLinkValues, value);
+      for (int j = 0; j < numberOfLinkValues; j++) {
+        String linkValue = context.randomUniqueValues[random.nextInt(context.randomUniqueValues.length)];
+        doc.linkValues.add(linkValue);
+        if (from) {
+          if (!context.fromDocuments.containsKey(linkValue)) {
+            context.fromDocuments.put(linkValue, new ArrayList<RandomDoc>());
+          }
+          if (!context.randomValueFromDocs.containsKey(value)) {
+            context.randomValueFromDocs.put(value, new ArrayList<RandomDoc>());
+          }
+
+          context.fromDocuments.get(linkValue).add(doc);
+          context.randomValueFromDocs.get(value).add(doc);
+          document.add(newField(random, "from", linkValue, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+        } else {
+          if (!context.toDocuments.containsKey(linkValue)) {
+            context.toDocuments.put(linkValue, new ArrayList<RandomDoc>());
+          }
+          if (!context.randomValueToDocs.containsKey(value)) {
+            context.randomValueToDocs.put(value, new ArrayList<RandomDoc>());
+          }
+
+          context.toDocuments.get(linkValue).add(doc);
+          context.randomValueToDocs.get(value).add(doc);
+          document.add(newField(random, "to", linkValue, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
+        }
+      }
+
+      final RandomIndexWriter w;
+      if (from) {
+        w = fromWriter;
+      } else {
+        w = toWriter;
+      }
+
+      w.addDocument(document);
+      if (random.nextInt(10) == 4) {
+        w.commit();
+      }
+      if (VERBOSE) {
+        System.out.println("Added document[" + i + "]: " + document);
+      }
+    }
+    return context;
+  }
+
+  private FixedBitSet createExpectedResult(String queryValue, boolean from, IndexSearcher searcher, IndexIterationContext context) throws IOException {
+    final Map<String, List<RandomDoc>> randomValueDocs;
+    final Map<String, List<RandomDoc>> linkValueDocuments;
+    if (from) {
+      randomValueDocs = context.randomValueFromDocs;
+      linkValueDocuments = context.toDocuments;
+    } else {
+      randomValueDocs = context.randomValueToDocs;
+      linkValueDocuments = context.fromDocuments;
+    }
+
+    FixedBitSet expectedResult = new FixedBitSet(searcher.maxDoc());
+    List<RandomDoc> matchingDocs = randomValueDocs.get(queryValue);
+    if (matchingDocs == null) {
+      return new FixedBitSet(searcher.maxDoc());
+    }
+
+    for (RandomDoc matchingDoc : matchingDocs) {
+      for (String linkValue : matchingDoc.linkValues) {
+        List<RandomDoc> otherMatchingDocs = linkValueDocuments.get(linkValue);
+        if (otherMatchingDocs == null) {
+          continue;
+        }
+
+        for (RandomDoc otherSideDoc : otherMatchingDocs) {
+          int doc = searcher.search(new TermQuery(new Term("id", otherSideDoc.id)), 1).scoreDocs[0].doc;
+          expectedResult.set(doc);
+        }
+      }
+    }
+    return expectedResult;
+  }
+
+  private static class IndexIterationContext {
+
+    String[] randomUniqueValues;
+    boolean[] randomFrom;
+    Map<String, List<RandomDoc>> fromDocuments = new HashMap<String, List<RandomDoc>>();
+    Map<String, List<RandomDoc>> toDocuments = new HashMap<String, List<RandomDoc>>();
+    Map<String, List<RandomDoc>> randomValueFromDocs = new HashMap<String, List<RandomDoc>>();
+    Map<String, List<RandomDoc>> randomValueToDocs = new HashMap<String, List<RandomDoc>>();
+
+  }
+
+  private static class RandomDoc {
+
+    final String id;
+    final List<String> linkValues;
+    final String value;
+
+    private RandomDoc(String id, int numberOfLinkValues, String value) {
+      this.id = id;
+      linkValues = new ArrayList<String>(numberOfLinkValues);
+      this.value = value;
+    }
+  }
+
+}
Index: lucene/contrib/join/src/java/org/apache/lucene/search/join/package.html
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- lucene/contrib/join/src/java/org/apache/lucene/search/join/package.html	(revision 1240771)
+++ lucene/contrib/join/src/java/org/apache/lucene/search/join/package.html	(revision )
@@ -1,7 +1,11 @@
 <html>
 <body>
 
-<p>This module supports index-time joins while searching, where joined
+<p>This modules support index-time and query-time joins.</p>
+
+<h2>Index-time joins</h2>
+
+<p>The index-time joining support joins while searching, where joined
   documents are indexed as a single document block using
   {@link org.apache.lucene.index.IndexWriter#addDocuments}.  This is useful for any normalized content (XML documents or database tables).  In database terms, all rows for all
   joined tables matching a single row of the primary table must be
@@ -34,5 +38,35 @@
   org.apache.lucene.search.join.ToChildBlockJoinQuery}.  This wraps
   any query matching parent documents, creating the joined query
   matching only child documents.
+
+<h2>Search-time joins</h2>
+
+<p>
+  The query time joining is index term based and implemented as two pass search. The first pass collects all the terms from a fromField
+  that match the fromQuery. The second pass returns all documents that have matching terms in a toField to the terms
+  collected in the first pass.
+</p>
+<p>Query time joining has the following input:</p>
+<ul>
+  <li><code>fromField</code>: The from field to join from.
+  <li><code>fromQuery</code>:  The query executed to collect the from terms. This is usually the user specified query.
+  <li><code>toField</code>: The to field to join to
+</ul>
+<p>
+  Basically the query-time joining is accessible from one static method. The user of this method supplies the method
+  with the described input and a <code>IndexSearcher</code> where the from terms need to be collected from. The returned
+  query can be executed with the same <code>IndexSearcher</code>, but also with another <code>IndexSearcher</code>.
+  Example usage of the {@link org.apache.lucene.search.join.JoinUtil#createJoinQuery(String, String, org.apache.lucene.search.Query, org.apache.lucene.search.IndexSearcher)} :
+</p>
+<pre class="prettyprint">
+  String fromField = "from"; // Name of the from field
+  String toField = "to"; // Name of the to field
+  Query fromQuery = new TermQuery(new Term("content", searchTerm)); // Query executed to collect from values to join to the to values
+
+  Query joinQuery = JoinUtil.createJoinQuery(fromField, toField, fromQuery, fromSearcher);
+  TopDocs topDocs = toSearcher.search(joinQuery, 10); // Note: toSearcher can be the same as the fromSearcher
+  // Render topDocs...
+</pre>
+
 </body>
 </html>
Index: lucene/contrib/join/src/java/org/apache/lucene/search/join/TermsQuery.java
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- lucene/contrib/join/src/java/org/apache/lucene/search/join/TermsQuery.java	(revision )
+++ lucene/contrib/join/src/java/org/apache/lucene/search/join/TermsQuery.java	(revision )
@@ -0,0 +1,168 @@
+package org.apache.lucene.search.join;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.index.TermEnum;
+import org.apache.lucene.search.FilteredTermEnum;
+import org.apache.lucene.search.MultiTermQuery;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Set;
+
+/**
+ * A query that has an array of terms from a specific field. This query will match documents have one or more terms in
+ * the specified field that match with the terms specified in the array.
+ *
+ * @lucene.experimental
+ */
+class TermsQuery extends MultiTermQuery {
+
+  private static final FilteredTermEnum EMPTY = new FilteredTermEnum() {
+
+    public boolean next() throws IOException {
+      return false;
+    }
+
+    public Term term() {
+      return null;
+    }
+
+    public int docFreq() {
+      throw new IllegalStateException("this method should never be called");
+    }
+
+    public void close() throws IOException {
+    }
+
+    protected boolean termCompare(Term term) {
+      throw new IllegalStateException("this method should never be called");
+    }
+
+    public float difference() {
+      throw new IllegalStateException("this method should never be called");
+    }
+
+    protected boolean endEnum() {
+      throw new IllegalStateException("this method should never be called");
+    }
+  };
+
+  private final String[] terms;
+  private final String field;
+
+  /**
+   * @param field The field that should contain terms that are specified in the previous parameter
+   * @param terms A set terms that matching documents should have.
+   */
+  TermsQuery(String field, Set<String> terms) {
+    this.field = field;
+    this.terms = terms.toArray(new String[terms.size()]);
+    Arrays.sort(this.terms);
+  }
+
+  protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {
+    if (terms.length == 0) {
+      return EMPTY;
+    }
+
+    TermEnum termEnum = reader.terms(new Term(field, terms[0]));
+    Term firstTerm = termEnum.term();
+    if (firstTerm == null || field != firstTerm.field()) { // interned comparison
+      return EMPTY;
+    }
+
+    return new SeekingTermsEnum(termEnum, firstTerm, field, terms);
+  }
+
+  public String toString(String string) {
+    return "TermsQuery{" +
+        "field=" + field +
+        '}';
+  }
+
+  static class SeekingTermsEnum extends FilteredTermEnum {
+
+    private final String[] terms;
+    private final String field;
+    private final int lastPosition;
+
+    private boolean endEnum;
+    private int upto;
+
+    SeekingTermsEnum(TermEnum termEnum, Term firstTerm, String field, String[] terms) throws IOException {
+      this.terms = terms;
+      this.field = field;
+      this.lastPosition = terms.length - 1;
+
+      upto = Arrays.binarySearch(terms, firstTerm.text());
+      if (upto < 0) {
+        upto = 0;
+      }
+      endEnum = upto == lastPosition;
+      setEnum(termEnum);
+    }
+
+    protected boolean termCompare(Term term) {
+      if (term == null || term.field() != field) { // interned comparison
+        endEnum = true;
+        return false;
+      }
+
+      int cmp = terms[upto].compareTo(term.text());
+      if (cmp < 0) {
+        if (upto == lastPosition) {
+          return false;
+        }
+
+        while ((cmp = terms[++upto].compareTo(term.text())) < 0) {
+          if (upto == lastPosition) {
+            endEnum = true;
+            return false;
+          }
+        }
+        assert cmp >= 0 : "cmp cannot be lower than zero";
+        if (cmp == 0) {
+          upto++;
+          endEnum = upto > lastPosition;
+          return true;
+        } else {
+          return false;
+        }
+      } else if (cmp > 0) {
+        return false;
+      } else {
+        upto++;
+        endEnum = upto > lastPosition;
+        return true;
+      }
+    }
+
+    public float difference() {
+      return 1.0f;
+    }
+
+    protected boolean endEnum() {
+      return endEnum;
+    }
+
+  }
+
+}
Index: lucene/contrib/join/src/java/org/apache/lucene/search/join/TermsCollector.java
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- lucene/contrib/join/src/java/org/apache/lucene/search/join/TermsCollector.java	(revision )
+++ lucene/contrib/join/src/java/org/apache/lucene/search/join/TermsCollector.java	(revision )
@@ -0,0 +1,64 @@
+package org.apache.lucene.search.join;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.search.Collector;
+import org.apache.lucene.search.FieldCache;
+import org.apache.lucene.search.Scorer;
+
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A collector that collects all terms from a specified field matching the query.
+ *
+ * @lucene.experimental
+ */
+class TermsCollector extends Collector {
+
+  final String field;
+  final Set<String> collectorTerms = new HashSet<String>();
+  
+  String[] fromDocTerms;
+
+  TermsCollector(String field) {
+    this.field = field;
+  }
+
+  public Set<String> getCollectorTerms() {
+    return collectorTerms;
+  }
+
+  public void setScorer(Scorer scorer) throws IOException {
+  }
+
+  public boolean acceptsDocsOutOfOrder() {
+    return true;
+  }
+
+  public void collect(int doc) throws IOException {
+    collectorTerms.add(fromDocTerms[doc]);
+  }
+
+  public void setNextReader(IndexReader indexReader, int docBase) throws IOException {
+    fromDocTerms = FieldCache.DEFAULT.getStrings(indexReader, field);
+  }
+
+}
