Index: src/java/org/apache/lucene/search/FieldCacheImpl.java =================================================================== --- src/java/org/apache/lucene/search/FieldCacheImpl.java (revision 955617) +++ src/java/org/apache/lucene/search/FieldCacheImpl.java (working copy) @@ -634,7 +634,7 @@ try { do { Term term = termEnum.term(); - if (term==null || term.field() != field) break; + if (term==null || term.field() != field || t >= mterms.length) break; // store term text mterms[t] = term.text(); Index: src/test/org/apache/lucene/search/TestSort.java =================================================================== --- src/test/org/apache/lucene/search/TestSort.java (revision 955617) +++ src/test/org/apache/lucene/search/TestSort.java (working copy) @@ -1013,4 +1013,25 @@ } } + public void testLUCENE2142() throws IOException { + RAMDirectory indexStore = new RAMDirectory (); + IndexWriter writer = new IndexWriter(indexStore, new IndexWriterConfig( + TEST_VERSION_CURRENT, new SimpleAnalyzer( + TEST_VERSION_CURRENT))); + for (int i=0; i<5; i++) { + Document doc = new Document(); + doc.add (new Field ("string", "a"+i, Field.Store.NO, Field.Index.NOT_ANALYZED)); + doc.add (new Field ("string", "b"+i, Field.Store.NO, Field.Index.NOT_ANALYZED)); + writer.addDocument (doc); + } + writer.optimize(); // enforce one segment to have a higher unique term count in all cases + writer.close(); + sort.setSort( + new SortField("string", SortField.STRING), + new SortField("string2", SortField.STRING, true), + SortField.FIELD_DOC ); + // this should not throw AIOOBE or RuntimeEx + new IndexSearcher (indexStore, true).search(new MatchAllDocsQuery(), null, 500, sort); + } + }