Skip to content

Commit

Permalink
fvh adaptor to highlight the top phrase once only.
Browse files Browse the repository at this point in the history
  • Loading branch information
waziqi89 committed Jan 2, 2025
1 parent dfa5c79 commit 44acb65
Show file tree
Hide file tree
Showing 10 changed files with 2,086 additions and 1,835 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ java {
}

allprojects {
version = '0.40.0'
version = '0.40.1'
group = 'com.yelp.nrtsearch'
}

Expand Down
2 changes: 2 additions & 0 deletions clientlib/src/main/proto/yelp/nrtsearch/search.proto
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,8 @@ message Highlight {
google.protobuf.UInt32Value boundary_max_scan = 15;
// Locale used in boundary scanner when using "word" or "sentence" boundary_scanner. Examples: "en-US", "ch-ZH".
google.protobuf.StringValue boundary_scanner_locale = 16;
// Only highlight the top matched phrase (with the highest boost value) once per segment. By default, it is false.
google.protobuf.BoolValue top_phrase_once = 17;
}

// Highlight settings
Expand Down
2,483 changes: 1,257 additions & 1,226 deletions grpc-gateway/luceneserver.pb.go

Large diffs are not rendered by default.

26 changes: 26 additions & 0 deletions grpc-gateway/luceneserver.swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -1406,6 +1406,14 @@
"required": false,
"type": "boolean"
},
{
"name": "liveSettings.defaultTerminateAfterMaxRecallCount",
"description": "Terminate after max recall count value to use when not specified in the search request, or 0 for none, default: 0",
"in": "query",
"required": false,
"type": "integer",
"format": "int32"
},
{
"name": "local",
"description": "When set to true, live settings changes are only applied to the local node. These changes are ephemeral, so will not persist through a restart. Also, the live settings returned in the response will contain the local overrides only when this flag is true.",
Expand Down Expand Up @@ -1757,6 +1765,10 @@
"boundaryScannerLocale": {
"type": "string",
"description": "Locale used in boundary scanner when using \"word\" or \"sentence\" boundary_scanner. Examples: \"en-US\", \"ch-ZH\"."
},
"topPhraseOnce": {
"type": "boolean",
"description": "Only highlight the top matched phrase (with the highest boost value) once per segment. By default, it is false."
}
}
},
Expand Down Expand Up @@ -2158,6 +2170,10 @@
"additionalProperties": {
"$ref": "#/definitions/SearchResponseDiagnostics"
}
},
"loggingHitsTimeMs": {
"type": "number",
"format": "double"
}
}
},
Expand Down Expand Up @@ -3814,6 +3830,11 @@
"verboseMetrics": {
"type": "boolean",
"title": "Collect and publish additional index metrics, which may be more expensive in terms of volume, memory and/or compute, default: false"
},
"defaultTerminateAfterMaxRecallCount": {
"type": "integer",
"format": "int32",
"title": "Terminate after max recall count value to use when not specified in the search request, or 0 for none, default: 0"
}
}
},
Expand Down Expand Up @@ -4053,6 +4074,11 @@
"type": "integer",
"format": "int32",
"description": "Terminate after value to use when not specified in the search request."
},
"defaultTerminateAfterMaxRecallCount": {
"type": "integer",
"format": "int32",
"description": "Terminate after max recall count value to use when not specified in the search request."
}
},
"title": "Input to liveSettings"
Expand Down
1,221 changes: 623 additions & 598 deletions grpc-gateway/search.pb.go

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public class HighlightSettings {
private final Character[] boundaryChars;
private final int boundaryMaxScan;
private final Locale boundaryScannerLocale;
private final boolean topPhraseOnce;

public HighlightSettings(
Highlighter highlighter,
Expand All @@ -54,6 +55,7 @@ public HighlightSettings(
Character[] boundaryChars,
int boundaryMaxScan,
Locale boundaryScannerLocale,
boolean topPhraseOnce,
Map<String, Object> customHighlighterParams) {
this.highlighter = highlighter;
this.preTags = preTags;
Expand All @@ -69,6 +71,7 @@ public HighlightSettings(
this.boundaryChars = boundaryChars;
this.boundaryMaxScan = boundaryMaxScan;
this.boundaryScannerLocale = boundaryScannerLocale;
this.topPhraseOnce = topPhraseOnce;
this.customHighlighterParams = customHighlighterParams;
}

Expand All @@ -88,6 +91,7 @@ public Builder toBuilder() {
.withBoundaryChars(this.boundaryChars)
.withBoundaryMaxScan(this.boundaryMaxScan)
.withBoundaryScannerLocale(this.boundaryScannerLocale)
.withTopPhraseOnce(this.topPhraseOnce)
.withCustomHighlighterParams(this.customHighlighterParams);
}

Expand Down Expand Up @@ -147,6 +151,10 @@ public Locale getBoundaryScannerLocale() {
return boundaryScannerLocale;
}

public boolean getTopPhraseOnce() {
return topPhraseOnce;
}

public Map<String, Object> getCustomHighlighterParams() {
return customHighlighterParams;
}
Expand Down Expand Up @@ -182,10 +190,12 @@ public String toString() {
+ '\''
+ ", boundaryChars="
+ Arrays.toString(boundaryChars)
+ ", boundaryCharsMaxScan="
+ ", boundaryMaxScan="
+ boundaryMaxScan
+ ", boundaryScannerLocale="
+ boundaryScannerLocale.toLanguageTag()
+ boundaryScannerLocale
+ ", topPhraseOnce="
+ topPhraseOnce
+ '}';
}

Expand All @@ -205,6 +215,7 @@ public static final class Builder {
private Character[] boundaryChars;
private int boundaryMaxScan;
private Locale boundaryScannerLocale;
private boolean topPhraseOnce;
private Map<String, Object> customHighlighterParams;

public Builder() {}
Expand Down Expand Up @@ -279,6 +290,11 @@ public Builder withBoundaryScannerLocale(Locale boundaryScannerLocale) {
return this;
}

public Builder withTopPhraseOnce(boolean topPhraseOnce) {
this.topPhraseOnce = topPhraseOnce;
return this;
}

public Builder withCustomHighlighterParams(Map<String, Object> customHighlighterParams) {
this.customHighlighterParams = customHighlighterParams;
return this;
Expand All @@ -300,6 +316,7 @@ public HighlightSettings build() {
boundaryChars,
boundaryMaxScan,
boundaryScannerLocale,
topPhraseOnce,
customHighlighterParams);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public class HighlightUtils {
private static final boolean DEFAULT_DISCRETE_MULTIVALUE = false;
private static final Character[] DEFAULT_BOUNDARY_CHARS =
SimpleBoundaryScanner.DEFAULT_BOUNDARY_CHARS;
private static final boolean DEFAULT_TOP_PHRASE_ONCE = false;
private static final int DEFAULT_BOUNDARY_MAX_SCAN = SimpleBoundaryScanner.DEFAULT_MAX_SCAN;
private static final Locale DEFAULT_BOUNDARY_SCANNER_LOCALE = Locale.ROOT;
private static final QueryNodeMapper QUERY_NODE_MAPPER = QueryNodeMapper.getInstance();
Expand Down Expand Up @@ -132,6 +133,10 @@ static Map<String, HighlightSettings> createPerFieldSettings(
settings.hasBoundaryScannerLocale()
? Locale.forLanguageTag(settings.getBoundaryScannerLocale().getValue())
: globalSettings.getBoundaryScannerLocale())
.withTopPhraseOnce(
settings.hasTopPhraseOnce()
? settings.getTopPhraseOnce().getValue()
: globalSettings.getTopPhraseOnce())
.withCustomHighlighterParams(
settings.hasCustomHighlighterParams()
? StructValueTransformer.transformStruct(
Expand Down Expand Up @@ -212,6 +217,10 @@ private static HighlightSettings createGlobalFieldSettings(
settings.hasBoundaryScannerLocale()
? Locale.forLanguageTag(settings.getBoundaryScannerLocale().getValue())
: DEFAULT_BOUNDARY_SCANNER_LOCALE)
.withTopPhraseOnce(
settings.hasTopPhraseOnce()
? settings.getTopPhraseOnce().getValue()
: DEFAULT_TOP_PHRASE_ONCE)
.withCustomHighlighterParams(
settings.hasCustomHighlighterParams()
? StructValueTransformer.transformStruct(settings.getCustomHighlighterParams())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,13 @@ public String[] getHighlights(
"Unknown boundary scanner: " + settings.getBoundaryScanner());
}

BaseFragmentsBuilder fragmentsBuilder;
if (settings.isScoreOrdered()) {
fragmentsBuilder = new ScoreOrderFragmentsBuilder(boundaryScanner);
} else {
fragmentsBuilder = new SimpleFragmentsBuilder(boundaryScanner);
}
BaseFragmentsBuilder fragmentsBuilder =
new TopPhraseOnceFragmentsBuilderAdaptor(
settings.isScoreOrdered()
? new ScoreOrderFragmentsBuilder()
: new SimpleFragmentsBuilder(),
boundaryScanner,
settings.getTopPhraseOnce());
fragmentsBuilder.setDiscreteMultiValueHighlighting(settings.getDiscreteMultivalue());

try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright 2024 Yelp Inc.
*
* Licensed 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 com.yelp.nrtsearch.server.luceneserver.highlights;

import org.apache.lucene.document.Field;
import org.apache.lucene.search.highlight.Encoder;
import org.apache.lucene.search.vectorhighlight.BaseFragmentsBuilder;
import org.apache.lucene.search.vectorhighlight.BoundaryScanner;
import org.apache.lucene.search.vectorhighlight.FieldFragList.WeightedFragInfo;
import org.apache.lucene.search.vectorhighlight.FieldFragList.WeightedFragInfo.SubInfo;
import org.apache.lucene.search.vectorhighlight.FieldPhraseList.WeightedPhraseInfo.Toffs;

import java.util.Comparator;
import java.util.List;

public class TopPhraseOnceFragmentsBuilderAdaptor extends BaseFragmentsBuilder {
private final BaseFragmentsBuilder innerBaseFragmentsBuilder;
private final boolean topPhraseOnce;

/** a constructor. */
public TopPhraseOnceFragmentsBuilderAdaptor(
BaseFragmentsBuilder baseFragmentsBuilder,
BoundaryScanner boundaryScanner,
boolean topPhraseOnce) {
super(boundaryScanner);
this.innerBaseFragmentsBuilder = baseFragmentsBuilder;
this.topPhraseOnce = topPhraseOnce;
}

@Override
public List<WeightedFragInfo> getWeightedFragInfoList(List<WeightedFragInfo> src) {
return innerBaseFragmentsBuilder.getWeightedFragInfoList(src);
}

@Override
protected String makeFragment(
StringBuilder buffer,
int[] index,
Field[] values,
WeightedFragInfo fragInfo,
String[] preTags,
String[] postTags,
Encoder encoder) {
if (!topPhraseOnce) {
return super.makeFragment(buffer, index, values, fragInfo, preTags, postTags, encoder);
}
StringBuilder fragment = new StringBuilder();
final int s = fragInfo.getStartOffset();
int[] modifiedStartOffset = {s};
String src =
getFragmentSourceMSO(
buffer, index, values, s, fragInfo.getEndOffset(), modifiedStartOffset);
int srcIndex = 0;
// get a list of the first highest boosted phrase only
List<SubInfo> subInfos =
fragInfo.getSubInfos().stream().max(Comparator.comparingDouble(SubInfo::getBoost)).stream()
.toList();
for (SubInfo subInfo : subInfos) {
for (Toffs to : subInfo.getTermsOffsets()) {
fragment
.append(
encoder.encodeText(
src.substring(srcIndex, to.getStartOffset() - modifiedStartOffset[0])))
.append(getPreTag(preTags, subInfo.getSeqnum()))
.append(
encoder.encodeText(
src.substring(
to.getStartOffset() - modifiedStartOffset[0],
to.getEndOffset() - modifiedStartOffset[0])))
.append(getPostTag(postTags, subInfo.getSeqnum()));
srcIndex = to.getEndOffset() - modifiedStartOffset[0];
}
}
fragment.append(encoder.encodeText(src.substring(srcIndex)));
return fragment.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import com.google.protobuf.UInt32Value;
import com.yelp.nrtsearch.server.grpc.AddDocumentRequest;
import com.yelp.nrtsearch.server.grpc.AddDocumentRequest.MultiValuedField;
import com.yelp.nrtsearch.server.grpc.BooleanClause;
import com.yelp.nrtsearch.server.grpc.BooleanQuery;
import com.yelp.nrtsearch.server.grpc.FieldDefRequest;
import com.yelp.nrtsearch.server.grpc.Highlight;
import com.yelp.nrtsearch.server.grpc.Highlight.Settings;
Expand Down Expand Up @@ -78,8 +80,9 @@ protected void initIndex(String name) throws Exception {
.addAllValue(
List.of(
"The food is good there, but the service is terrible.",
"I personally don't like the staff at this place",
"Not all food are good."))
"I personally don't like the staff at this place.",
"Not all food are good.",
"This pizza place was one of my favorites in downtown, and as promised by other users, the pepperoni pizza is the best pepperoni pizza in town."))
.build())
.putFields(
"boundary_scanner_field",
Expand Down Expand Up @@ -190,6 +193,53 @@ public void testHighlightMultivalueField() {
assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0);
}

@Test
public void testHighlightMultivalueFieldWithTopPhraseOnly() {
Highlight highlight =
Highlight.newBuilder()
.addFields("comment_multivalue")
.setSettings(
Settings.newBuilder()
.setHighlightQuery(
Query.newBuilder()
.setBooleanQuery(
BooleanQuery.newBuilder()
.addClauses(
BooleanClause.newBuilder()
.setQuery(
Query.newBuilder()
.setPhraseQuery(
PhraseQuery.newBuilder()
.setField("comment_multivalue")
.addAllTerms(
List.of("pepperoni", "pizza")))
.setBoost(3))
.setOccurValue(BooleanClause.Occur.SHOULD_VALUE))
.addClauses(
BooleanClause.newBuilder()
.setQuery(
Query.newBuilder()
.setTermQuery(
TermQuery.newBuilder()
.setField("comment_multivalue")
.setTextValue("pizza"))
.setBoost(2)))))
.setMaxNumberOfFragments(UInt32Value.of(1))
.setFragmentSize(UInt32Value.of(250))
.setTopPhraseOnce(BoolValue.of(true))
.setScoreOrdered(BoolValue.of(true))
.setDiscreteMultivalue(BoolValue.of(true)))
.build();
SearchResponse response = doHighlightQuery(highlight);

assertFields(response);

assertThat(response.getHits(0).getHighlightsMap().get("comment_multivalue").getFragmentsList())
.containsExactly(
"This pizza place was one of my favorites in downtown, and as promised by other users, the <em>pepperoni pizza</em> is the best pepperoni pizza in town.");
assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0);
}

@Test
public void testHighlightGlobalSettings() {
Settings settings =
Expand Down

0 comments on commit 44acb65

Please sign in to comment.