You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@lucene.apache.org by GitBox <gi...@apache.org> on 2020/09/08 13:07:14 UTC

[GitHub] [lucene-solr] dweiss commented on a change in pull request #1820: LUCENE-9464: Add high(er)-level hit highlighter example that demonstrates and uses low-level components

dweiss commented on a change in pull request #1820:
URL: https://github.com/apache/lucene-solr/pull/1820#discussion_r484900156



##########
File path: lucene/highlighter/src/test/org/apache/lucene/search/matchhighlight/TestMatchHighlighter.java
##########
@@ -0,0 +1,466 @@
+/*
+ * 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.matchhighlight;
+
+import com.carrotsearch.randomizedtesting.RandomizedTest;
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.Tokenizer;
+import org.apache.lucene.analysis.core.WhitespaceTokenizer;
+import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
+import org.apache.lucene.analysis.synonym.SynonymGraphFilter;
+import org.apache.lucene.analysis.synonym.SynonymMap;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.FieldType;
+import org.apache.lucene.document.TextField;
+import org.apache.lucene.index.IndexOptions;
+import org.apache.lucene.index.IndexableField;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.queries.intervals.IntervalQuery;
+import org.apache.lucene.queries.intervals.Intervals;
+import org.apache.lucene.search.BooleanClause;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.MatchAllDocsQuery;
+import org.apache.lucene.search.PhraseQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Sort;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.LuceneTestCase;
+import org.hamcrest.Matchers;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class TestMatchHighlighter extends LuceneTestCase {
+  private static final String FLD_ID = "id";
+  private static final String FLD_TEXT1 = "text1";
+  private static final String FLD_TEXT2 = "text2";
+
+  private FieldType TYPE_TEXT_POSITIONS_OFFSETS;
+  private FieldType TYPE_TEXT_POSITIONS;
+
+  private PerFieldAnalyzerWrapper analyzer;
+
+  @Before
+  public void setup() throws IOException {
+    TYPE_TEXT_POSITIONS = TextField.TYPE_STORED;
+
+    TYPE_TEXT_POSITIONS_OFFSETS = new FieldType(TextField.TYPE_STORED);
+    TYPE_TEXT_POSITIONS_OFFSETS.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
+    TYPE_TEXT_POSITIONS_OFFSETS.freeze();
+
+    Map<String, Analyzer> fieldAnalyzers = new HashMap<>();
+
+    // Create an analyzer with some synonyms, just to showcase them.
+    SynonymMap synonymMap = buildSynonymMap(new String[][]{
+        {"moon\u0000shine", "firewater"},
+        {"firewater", "moon\u0000shine"},
+    });
+
+    // Make a non-empty offset gap so that break iterator doesn't go haywire on multivalues
+    // glued together.
+    final int offsetGap = RandomizedTest.randomIntBetween(1, 2);
+    final int positionGap = RandomizedTest.randomFrom(new int[]{0, 1, 100});
+    Analyzer synonymsAnalyzer =
+        new AnalyzerWithGaps(offsetGap, positionGap, new Analyzer() {
+          @Override
+          protected TokenStreamComponents createComponents(String fieldName) {
+            Tokenizer tokenizer = new WhitespaceTokenizer();
+            TokenStream tokenStream = new SynonymGraphFilter(tokenizer, synonymMap, true);
+            return new TokenStreamComponents(tokenizer, tokenStream);
+          }
+        });
+
+    fieldAnalyzers.put(FLD_TEXT1, synonymsAnalyzer);
+    fieldAnalyzers.put(FLD_TEXT2, synonymsAnalyzer);
+
+    analyzer = new PerFieldAnalyzerWrapper(new MissingAnalyzer(), fieldAnalyzers);
+  }
+
+  static SynonymMap buildSynonymMap(String[][] synonyms) throws IOException {
+    SynonymMap.Builder builder = new SynonymMap.Builder();
+    for (String[] pair : synonyms) {
+      assertThat(pair.length, Matchers.equalTo(2));
+      builder.add(new CharsRef(pair[0]), new CharsRef(pair[1]), true);
+    }
+    return builder.build();
+  }
+
+  @Test
+  public void testBasicUsage() throws IOException {
+    new IndexBuilder(this::toField)
+        .doc(FLD_TEXT1, "foo bar baz")
+        .doc(FLD_TEXT1, "bar foo baz")
+        .doc(fields -> {
+          fields.add(FLD_TEXT1, "Very long content but not matching anything.");
+          fields.add(FLD_TEXT2, "no foo but bar");
+        })
+        .build(analyzer, reader -> {
+          Query query = new BooleanQuery.Builder()
+              .add(new TermQuery(new Term(FLD_TEXT1, "foo")), BooleanClause.Occur.SHOULD)
+              .add(new TermQuery(new Term(FLD_TEXT2, "bar")), BooleanClause.Occur.SHOULD)
+              .build();
+
+          // In the most basic scenario, we run a search against a query, retrieve
+          // top docs...
+          IndexSearcher searcher = new IndexSearcher(reader);
+          Sort sortOrder = Sort.INDEXORDER; // So that results are consistently ordered.
+          TopDocs topDocs = searcher.search(query, 10, sortOrder);
+
+          // ...and would want a fixed set of fields from those documents, some of them
+          // possibly highlighted if they matched the query.
+          //
+          // This configures the highlighter so that the FLD_ID field is always returned verbatim,
+          // and FLD_TEXT1 is returned *only if it contained a query match*.
+          MatchHighlighter highlighter =
+              new MatchHighlighter(searcher, analyzer)
+                .appendFieldHighlighter(FieldValueHighlighters.verbatimValue(FLD_ID))
+                .appendFieldHighlighter(FieldValueHighlighters.highlighted(
+                    80 * 3, 1, new PassageFormatter("...", ">", "<"), FLD_TEXT1::equals))
+                .appendFieldHighlighter(FieldValueHighlighters.skipRemaining());

Review comment:
       These field highlighters can apply to more than one field and the highlighter may receive fields it wasn't prepared to process (because they were part of the query). I opted to be explicit - if no field highlighter "accepts" a field, the entire highlighting process fails. The "skip remaining" is essentially a rule that does nothing for any field that wasn't consumed before.
   
   Performance-wise I admit I wasn't too keen on optimizing things too early. This thing, even if slower, just works for me in 
   so many more scenarios than any of the approaches I've tried with other highlighters in Lucene. That "two queries at once" example isn't entirely out of thin air... we actually do use something like this to highlight queries originating from different sources.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org