<commit_before>/*
 * 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.
 */
package org.apache.lucene.search;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.MultiDocValues;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;

/**
 * Demonstrates an application of the {@link DiversifiedTopDocsCollector} in
 * assembling a collection of top results but without over-representation of any
 * one source (in this case top-selling singles from the 60s without having them
 * all be Beatles records...). Results are ranked by the number of weeks a
 * single is top of the charts and de-duped by the artist name.
 * 
 */
public class TestDiversifiedTopDocsCollector extends LuceneTestCase {

  public void testNonDiversifiedResults() throws Exception {
    int numberOfTracksOnCompilation = 10;
    int expectedMinNumOfBeatlesHits = 5;
    TopDocs res = searcher.search(getTestQuery(), numberOfTracksOnCompilation);
    assertEquals(numberOfTracksOnCompilation, res.scoreDocs.length);
    // due to randomization of segment merging in tests the exact number of Beatles hits 
    // selected varies between 5 and 6 but we prove the point they are over-represented
    // in our result set using a standard search.
    assertTrue(getMaxNumRecordsPerArtist(res.scoreDocs) >= expectedMinNumOfBeatlesHits);
  }

  public void testFirstPageDiversifiedResults() throws Exception {
    // Using a diversified collector we can limit the results from
    // any one artist.
    int requiredMaxHitsPerArtist = 2;
    int numberOfTracksOnCompilation = 10;
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(
        numberOfTracksOnCompilation, requiredMaxHitsPerArtist);
    ScoreDoc[] sd = tdc.topDocs(0).scoreDocs;
    assertEquals(numberOfTracksOnCompilation, sd.length);
    assertTrue(getMaxNumRecordsPerArtist(sd) <= requiredMaxHitsPerArtist);
  }

  public void testSecondPageResults() throws Exception {
    int numberOfTracksPerCompilation = 10;
    int numberOfCompilations = 2;
    int requiredMaxHitsPerArtist = 1;

    // Volume 2 of our hits compilation - start at position 10
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(
        numberOfTracksPerCompilation * numberOfCompilations,
        requiredMaxHitsPerArtist);
    ScoreDoc[] volume2 = tdc.topDocs(numberOfTracksPerCompilation,
        numberOfTracksPerCompilation).scoreDocs;
    assertEquals(numberOfTracksPerCompilation, volume2.length);
    assertTrue(getMaxNumRecordsPerArtist(volume2) <= requiredMaxHitsPerArtist);

  }

  public void testInvalidArguments() throws Exception {
    int numResults = 5;
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(numResults, 15);

    // start < 0
    assertEquals(0, tdc.topDocs(-1).scoreDocs.length);

    // start > pq.size()
    assertEquals(0, tdc.topDocs(numResults + 1).scoreDocs.length);

    // start == pq.size()
    assertEquals(0, tdc.topDocs(numResults).scoreDocs.length);

    // howMany < 0
    assertEquals(0, tdc.topDocs(0, -1).scoreDocs.length);

    // howMany == 0
    assertEquals(0, tdc.topDocs(0, 0).scoreDocs.length);

  }

  // Diversifying collector that looks up de-dup keys using SortedDocValues
  // from a top-level Reader
  private static final class DocValuesDiversifiedCollector extends
      DiversifiedTopDocsCollector {
    private final SortedDocValues sdv;

    public DocValuesDiversifiedCollector(int size, int maxHitsPerKey,
        SortedDocValues sdv) {
      super(size, maxHitsPerKey);
      this.sdv = sdv;
    }

    @Override
    protected NumericDocValues getKeys(final LeafReaderContext context) {

      return new NumericDocValues() {
<commit_msg>Harden Up TestDiversifiedTopDocsCollector (#858)<commit_after>/*
 * 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.
 */
package org.apache.lucene.search;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.MultiDocValues;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;

/**
 * Demonstrates an application of the {@link DiversifiedTopDocsCollector} in
 * assembling a collection of top results but without over-representation of any
 * one source (in this case top-selling singles from the 60s without having them
 * all be Beatles records...). Results are ranked by the number of weeks a
 * single is top of the charts and de-duped by the artist name.
 * 
 */
public class TestDiversifiedTopDocsCollector extends LuceneTestCase {

  public void testNonDiversifiedResults() throws Exception {
    int numberOfTracksOnCompilation = 10;
    int expectedMinNumOfBeatlesHits = 5;
    TopDocs res = searcher.search(getTestQuery(), numberOfTracksOnCompilation);
    assertEquals(numberOfTracksOnCompilation, res.scoreDocs.length);
    // due to randomization of segment merging in tests the exact number of Beatles hits 
    // selected varies between 5 and 6 but we prove the point they are over-represented
    // in our result set using a standard search.
    assertTrue(getMaxNumRecordsPerArtist(res.scoreDocs) >= expectedMinNumOfBeatlesHits);
  }

  public void testFirstPageDiversifiedResults() throws Exception {
    // Using a diversified collector we can limit the results from
    // any one artist.
    int requiredMaxHitsPerArtist = 2;
    int numberOfTracksOnCompilation = 10;
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(
        numberOfTracksOnCompilation, requiredMaxHitsPerArtist);
    ScoreDoc[] sd = tdc.topDocs(0).scoreDocs;
    assertEquals(numberOfTracksOnCompilation, sd.length);
    assertTrue(getMaxNumRecordsPerArtist(sd) <= requiredMaxHitsPerArtist);
  }

  public void testSecondPageResults() throws Exception {
    int numberOfTracksPerCompilation = 10;
    int numberOfCompilations = 2;
    int requiredMaxHitsPerArtist = 1;

    // Volume 2 of our hits compilation - start at position 10
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(
        numberOfTracksPerCompilation * numberOfCompilations,
        requiredMaxHitsPerArtist);
    ScoreDoc[] volume2 = tdc.topDocs(numberOfTracksPerCompilation,
        numberOfTracksPerCompilation).scoreDocs;
    assertEquals(numberOfTracksPerCompilation, volume2.length);
    assertTrue(getMaxNumRecordsPerArtist(volume2) <= requiredMaxHitsPerArtist);

  }

  public void testInvalidArguments() throws Exception {
    int numResults = 5;
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(numResults, 15);

    // start < 0
    IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
      tdc.topDocs(-1);
    });

    assertEquals("Expected value of starting position is between 0 and 5, got -1", expected.getMessage());

    // start > pq.size()
    assertEquals(0, tdc.topDocs(numResults + 1).scoreDocs.length);

    // start == pq.size()
    assertEquals(0, tdc.topDocs(numResults).scoreDocs.length);

    // howMany < 0
    expected = expectThrows(IllegalArgumentException.class, () -> {
      tdc.topDocs(0, -1);
    });

    assertEquals("Number of hits requested must be greater than 0 but value was -1", expected.getMessage());

    // howMany == 0
    assertEquals(0, tdc.topDocs(0, 0).scoreDocs.length);

  }

  // Diversifying collector that looks up de-dup keys using SortedDocValues
  // from a top-level Reader
  private static final class DocValuesDiversifiedCollector extends
      DiversifiedTopDocsCollector {
    private final SortedDocValues sdv;

    public DocValuesDiversifiedCollector(int size, int maxHitsPerKey,
        SortedDocValues sdv) {
      super(size, maxHitsPerKey);
      this.sdv = sdv;
    }

    @Override
    protected NumericDocValues getKeys(final LeafReaderContext context) {

      return new NumericDocValues() {

{'fraction_non_alphanumeric': 0.0793947319260228, 'fraction_numerical': 0.008406501027461237, 'mean_word_length': 4.295252225519288, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5015751', 'n_tokens_mistral': 3195, 'n_tokens_neox': 3040, 'n_words': 887}