Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(search): Also de-duplicate the field queries based on field names #8788

Merged
merged 9 commits into from
Sep 7, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.linkedin.metadata.search.elasticsearch.query.request;

import com.google.common.annotations.VisibleForTesting;
import com.linkedin.metadata.config.search.ExactMatchConfiguration;
import com.linkedin.metadata.config.search.PartialConfiguration;
import com.linkedin.metadata.config.search.SearchConfiguration;
Expand All @@ -19,6 +20,7 @@

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
Expand Down Expand Up @@ -116,11 +118,8 @@ private QueryBuilder buildInternalQuery(@Nullable QueryConfiguration customQuery

QueryStringQueryBuilder queryBuilder = QueryBuilders.queryStringQuery(withoutQueryPrefix);
queryBuilder.defaultOperator(Operator.AND);
entitySpecs.stream()
.map(this::getStandardFields)
.flatMap(Set::stream)
.distinct()
.forEach(cfg -> queryBuilder.field(cfg.fieldName(), cfg.boost()));
getStandardFields(entitySpecs).forEach(entitySpec ->
queryBuilder.field(entitySpec.fieldName(), entitySpec.boost()));
finalQuery.should(queryBuilder);
if (exactMatchConfiguration.isEnableStructured()) {
getPrefixAndExactMatchQuery(null, entitySpecs, withoutQueryPrefix).ifPresent(finalQuery::should);
Expand All @@ -130,16 +129,46 @@ private QueryBuilder buildInternalQuery(@Nullable QueryConfiguration customQuery
return finalQuery;
}

private Set<SearchFieldConfig> getStandardFields(@Nonnull EntitySpec entitySpec) {
/**
* Gets searchable fields from all entities in the input collection. De-duplicates fields across entities.
* @param entitySpecs: Entity specs to extract searchable fields from
* @return A set of SearchFieldConfigs containing the searchable fields from the input entities.
*/
@VisibleForTesting
Set<SearchFieldConfig> getStandardFields(@Nonnull Collection<EntitySpec> entitySpecs) {
Set<SearchFieldConfig> fields = new HashSet<>();

// Always present
final float urnBoost = Float.parseFloat((String) PRIMARY_URN_SEARCH_PROPERTIES.get("boostScore"));

fields.add(SearchFieldConfig.detectSubFieldType("urn", urnBoost, SearchableAnnotation.FieldType.URN, true));
fields.add(SearchFieldConfig.detectSubFieldType("urn.delimited", urnBoost * partialConfiguration.getUrnFactor(),
SearchableAnnotation.FieldType.URN, true));
SearchableAnnotation.FieldType.URN, true));

entitySpecs.stream()
.map(this::getFieldsFromEntitySpec)
.flatMap(Set::stream)
.collect(Collectors.groupingBy(SearchFieldConfig::fieldName)).forEach((key, value) ->
fields.add(
new SearchFieldConfig(
key,
value.get(0).shortName(),
(float) value.stream().mapToDouble(SearchFieldConfig::boost).average().getAsDouble(),
value.get(0).analyzer(),
value.stream().anyMatch(SearchFieldConfig::hasKeywordSubfield),
value.stream().anyMatch(SearchFieldConfig::hasDelimitedSubfield),
value.stream().anyMatch(SearchFieldConfig::hasWordGramSubfields),
true,
value.stream().anyMatch(SearchFieldConfig::isDelimitedSubfield),
value.stream().anyMatch(SearchFieldConfig::isKeywordSubfield),
value.stream().anyMatch(SearchFieldConfig::isWordGramSubfield)
))
);

return fields;
}

private Set<SearchFieldConfig> getFieldsFromEntitySpec(EntitySpec entitySpec) {
Set<SearchFieldConfig> fields = new HashSet<>();
List<SearchableFieldSpec> searchableFieldSpecs = entitySpec.getSearchableFieldSpecs();
for (SearchableFieldSpec fieldSpec : searchableFieldSpecs) {
if (!fieldSpec.getSearchableAnnotation().isQueryByDefault()) {
Expand All @@ -153,8 +182,8 @@ private Set<SearchFieldConfig> getStandardFields(@Nonnull EntitySpec entitySpec)
final SearchableAnnotation searchableAnnotation = fieldSpec.getSearchableAnnotation();

fields.add(SearchFieldConfig.detectSubFieldType(searchFieldConfig.fieldName() + ".delimited",
searchFieldConfig.boost() * partialConfiguration.getFactor(),
searchableAnnotation.getFieldType(), searchableAnnotation.isQueryByDefault()));
searchFieldConfig.boost() * partialConfiguration.getFactor(),
searchableAnnotation.getFieldType(), searchableAnnotation.isQueryByDefault()));

if (SearchFieldConfig.detectSubFieldType(fieldSpec).hasWordGramSubfields()) {
fields.add(SearchFieldConfig.builder()
Expand Down Expand Up @@ -187,6 +216,20 @@ private Set<SearchFieldConfig> getStandardFields(@Nonnull EntitySpec entitySpec)
}
}
}
return fields;
}

private Set<SearchFieldConfig> getStandardFields(@Nonnull EntitySpec entitySpec) {
Set<SearchFieldConfig> fields = new HashSet<>();

// Always present
final float urnBoost = Float.parseFloat((String) PRIMARY_URN_SEARCH_PROPERTIES.get("boostScore"));

fields.add(SearchFieldConfig.detectSubFieldType("urn", urnBoost, SearchableAnnotation.FieldType.URN, true));
fields.add(SearchFieldConfig.detectSubFieldType("urn.delimited", urnBoost * partialConfiguration.getUrnFactor(),
SearchableAnnotation.FieldType.URN, true));

fields.addAll(getFieldsFromEntitySpec(entitySpec));

return fields;
}
Expand Down Expand Up @@ -255,49 +298,42 @@ private Optional<QueryBuilder> getPrefixAndExactMatchQuery(@Nullable QueryConfig
BoolQueryBuilder finalQuery = QueryBuilders.boolQuery();
String unquotedQuery = unquote(query);

entitySpecs.stream()
.map(this::getStandardFields)
.flatMap(Set::stream)
.filter(SearchFieldConfig::isQueryByDefault)
.forEach(searchFieldConfig -> {

if (searchFieldConfig.isDelimitedSubfield() && isPrefixQuery) {
finalQuery.should(QueryBuilders.matchPhrasePrefixQuery(searchFieldConfig.fieldName(), query)
.boost(searchFieldConfig.boost()
* exactMatchConfiguration.getPrefixFactor()
* exactMatchConfiguration.getCaseSensitivityFactor())
.queryName(searchFieldConfig.shortName())); // less than exact
}

if (searchFieldConfig.isKeyword() && isExactQuery) {
// It is important to use the subfield .keyword (it uses a different normalizer)
// The non-.keyword field removes case information

// Exact match case-sensitive
finalQuery.should(QueryBuilders
.termQuery(ESUtils.toKeywordField(searchFieldConfig.fieldName(), false), unquotedQuery)
.caseInsensitive(false)
.boost(searchFieldConfig.boost()
* exactMatchConfiguration.getExactFactor())
.queryName(searchFieldConfig.shortName()));

// Exact match case-insensitive
finalQuery.should(QueryBuilders
.termQuery(ESUtils.toKeywordField(searchFieldConfig.fieldName(), false), unquotedQuery)
.caseInsensitive(true)
.boost(searchFieldConfig.boost()
* exactMatchConfiguration.getExactFactor()
* exactMatchConfiguration.getCaseSensitivityFactor())
.queryName(searchFieldConfig.fieldName()));
}

if (searchFieldConfig.isWordGramSubfield() && isPrefixQuery) {
finalQuery.should(QueryBuilders
.matchPhraseQuery(ESUtils.toKeywordField(searchFieldConfig.fieldName(), false), unquotedQuery)
getStandardFields(entitySpecs).forEach(searchFieldConfig -> {
if (searchFieldConfig.isDelimitedSubfield() && isPrefixQuery) {
finalQuery.should(QueryBuilders.matchPhrasePrefixQuery(searchFieldConfig.fieldName(), query)
.boost(searchFieldConfig.boost() * exactMatchConfiguration.getPrefixFactor()
* exactMatchConfiguration.getCaseSensitivityFactor())
.queryName(searchFieldConfig.shortName())); // less than exact
}

if (searchFieldConfig.isKeyword() && isExactQuery) {
// It is important to use the subfield .keyword (it uses a different normalizer)
// The non-.keyword field removes case information

// Exact match case-sensitive
finalQuery.should(
QueryBuilders.termQuery(ESUtils.toKeywordField(searchFieldConfig.fieldName(), false), unquotedQuery)
.caseInsensitive(false)
.boost(searchFieldConfig.boost() * exactMatchConfiguration.getExactFactor())
.queryName(searchFieldConfig.shortName()));

// Exact match case-insensitive
finalQuery.should(
QueryBuilders.termQuery(ESUtils.toKeywordField(searchFieldConfig.fieldName(), false), unquotedQuery)
.caseInsensitive(true)
.boost(searchFieldConfig.boost() * exactMatchConfiguration.getExactFactor()
* exactMatchConfiguration.getCaseSensitivityFactor())
.queryName(searchFieldConfig.fieldName()));
}

if (searchFieldConfig.isWordGramSubfield() && isPrefixQuery) {
finalQuery.should(
QueryBuilders.matchPhraseQuery(ESUtils.toKeywordField(searchFieldConfig.fieldName(), false),
unquotedQuery)
.boost(searchFieldConfig.boost() * getWordGramFactor(searchFieldConfig.fieldName()))
.queryName(searchFieldConfig.shortName()));
}
});
}
});

return finalQuery.should().size() > 0 ? Optional.of(finalQuery) : Optional.empty();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.linkedin.metadata.search.elasticsearch.query.request;

import com.linkedin.data.schema.DataSchema;
import com.linkedin.data.schema.PathSpec;
import com.linkedin.metadata.config.search.CustomConfiguration;
import com.linkedin.metadata.config.search.ExactMatchConfiguration;
import com.linkedin.metadata.config.search.PartialConfiguration;
Expand All @@ -10,9 +12,14 @@
import com.google.common.collect.ImmutableList;
import com.linkedin.metadata.TestEntitySpecBuilder;

import com.linkedin.metadata.models.EntitySpec;
import com.linkedin.metadata.models.SearchableFieldSpec;
import com.linkedin.metadata.models.annotation.SearchableAnnotation;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.linkedin.util.Pair;
Expand All @@ -25,6 +32,7 @@
import org.elasticsearch.index.query.SimpleQueryStringBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.mockito.Mockito;
import org.testng.annotations.Test;

import static com.linkedin.metadata.search.elasticsearch.indexbuilder.SettingsBuilder.TEXT_SEARCH_ANALYZER;
Expand Down Expand Up @@ -263,4 +271,108 @@ public void testCustomDefault() {
assertEquals(termQueryBuilder.value().toString(), triggerQuery);
}
}

@Test
public void testGetStandardFields() {
Set<SearchFieldConfig> fieldConfigs = TEST_CUSTOM_BUILDER.getStandardFields(ImmutableList.of(TestEntitySpecBuilder.getSpec()));
assertEquals(fieldConfigs.size(), 21);
assertEquals(fieldConfigs.stream().map(SearchFieldConfig::fieldName).collect(Collectors.toSet()), Set.of(
"nestedArrayArrayField",
"esObjectField",
"foreignKey",
"keyPart1",
"nestedForeignKey",
"textArrayField.delimited",
"nestedArrayArrayField.delimited",
"wordGramField.delimited",
"wordGramField.wordGrams4",
"textFieldOverride",
"nestedArrayStringField.delimited",
"urn.delimited",
"textArrayField",
"keyPart1.delimited",
"nestedArrayStringField",
"wordGramField",
"customProperties",
"wordGramField.wordGrams3",
"textFieldOverride.delimited",
"urn",
"wordGramField.wordGrams2"));

assertEquals(fieldConfigs.stream().filter(field -> field.fieldName().equals("keyPart1")).findFirst().map(SearchFieldConfig::boost), Optional.of(
10.0F));
assertEquals(fieldConfigs.stream().filter(field -> field.fieldName().equals("nestedForeignKey")).findFirst().map(SearchFieldConfig::boost), Optional.of(
1.0F));
assertEquals(fieldConfigs.stream().filter(field -> field.fieldName().equals("textFieldOverride")).findFirst().map(SearchFieldConfig::boost), Optional.of(
1.0F));

EntitySpec mockEntitySpec = Mockito.mock(EntitySpec.class);
Mockito.when(mockEntitySpec.getSearchableFieldSpecs()).thenReturn(List.of(
new SearchableFieldSpec(
Mockito.mock(PathSpec.class),
new SearchableAnnotation("fieldDoesntExistInOriginal",
SearchableAnnotation.FieldType.TEXT,
true, true, false, false,
Optional.empty(), Optional.empty(), 13.0,
Optional.empty(), Optional.empty(), Map.of(), List.of()),
Mockito.mock(DataSchema.class)),
new SearchableFieldSpec(
Mockito.mock(PathSpec.class),
new SearchableAnnotation("keyPart1",
SearchableAnnotation.FieldType.KEYWORD,
true, true, false, false,
Optional.empty(), Optional.empty(), 20.0,
Optional.empty(), Optional.empty(), Map.of(), List.of()),
Mockito.mock(DataSchema.class)),
new SearchableFieldSpec(
Mockito.mock(PathSpec.class),
new SearchableAnnotation("textFieldOverride",
SearchableAnnotation.FieldType.WORD_GRAM,
true, true, false, false,
Optional.empty(), Optional.empty(), 3.0,
Optional.empty(), Optional.empty(), Map.of(), List.of()),
Mockito.mock(DataSchema.class)))
);

fieldConfigs = TEST_CUSTOM_BUILDER.getStandardFields(ImmutableList.of(TestEntitySpecBuilder.getSpec(), mockEntitySpec));
// Same 21 from the original entity + newFieldNotInOriginal + 3 word gram fields from the textFieldOverride
assertEquals(fieldConfigs.size(), 26);
assertEquals(fieldConfigs.stream().map(SearchFieldConfig::fieldName).collect(Collectors.toSet()), Set.of(
"nestedArrayArrayField",
"esObjectField",
"foreignKey",
"keyPart1",
"nestedForeignKey",
"textArrayField.delimited",
"nestedArrayArrayField.delimited",
"wordGramField.delimited",
"wordGramField.wordGrams4",
"textFieldOverride",
"nestedArrayStringField.delimited",
"urn.delimited",
"textArrayField",
"keyPart1.delimited",
"nestedArrayStringField",
"wordGramField",
"customProperties",
"wordGramField.wordGrams3",
"textFieldOverride.delimited",
"urn",
"wordGramField.wordGrams2",
"fieldDoesntExistInOriginal",
"fieldDoesntExistInOriginal.delimited",
"textFieldOverride.wordGrams2",
"textFieldOverride.wordGrams3",
"textFieldOverride.wordGrams4"));

// Field which only exists in first one: Should be the same
assertEquals(fieldConfigs.stream().filter(field -> field.fieldName().equals("nestedForeignKey")).findFirst().map(SearchFieldConfig::boost), Optional.of(
1.0F));
// Average boost value: 10 vs. 20 -> 15
assertEquals(fieldConfigs.stream().filter(field -> field.fieldName().equals("keyPart1")).findFirst().map(SearchFieldConfig::boost), Optional.of(
15.0F));
// Field which added word gram fields: Original boost should be boost value averaged
assertEquals(fieldConfigs.stream().filter(field -> field.fieldName().equals("textFieldOverride")).findFirst().map(SearchFieldConfig::boost), Optional.of(
2.0F));
}
}
Loading