Skip to content

Commit

Permalink
Fix auto fuzziness in query_string query (#42897)
Browse files Browse the repository at this point in the history
Setting `auto` after the fuzzy operator (e.g. `"query": "foo~auto"`) in the `query_string`
does not take the length of the term into account when computing the distance and always use
a max distance of 1. This change fixes this disrepancy by ensuring that the term is passed when
the fuzziness is computed.
  • Loading branch information
jimczi authored Jun 10, 2019
1 parent 5e16a74 commit ab25a01
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,8 @@ protected Query handleBareFuzzy(String field, Token fuzzySlop, String termImage)
if (fuzzySlop.image.length() == 1) {
return getFuzzyQuery(field, termImage, fuzziness.asDistance(termImage));
}
return getFuzzyQuery(field, termImage, Fuzziness.fromString(fuzzySlop.image.substring(1)).asFloat());
float distance = Fuzziness.fromString(fuzzySlop.image.substring(1)).asDistance(termImage);
return getFuzzyQuery(field, termImage, distance);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -786,27 +786,36 @@ public void testEnabledPositionIncrements() throws Exception {
}

public void testToQueryFuzzyQueryAutoFuziness() throws Exception {
int length = randomIntBetween(1, 10);
StringBuilder queryString = new StringBuilder();
for (int i = 0; i < length; i++) {
queryString.append("a");
}
queryString.append("~");
for (int i = 0; i < 3; i++) {
final int expectedEdits;
String queryString;
switch (i) {
case 0:
queryString = randomAlphaOfLengthBetween(1, 2);
expectedEdits = 0;
break;

case 1:
queryString = randomAlphaOfLengthBetween(3, 5);
expectedEdits = 1;
break;

default:
queryString = randomAlphaOfLengthBetween(6, 20);
expectedEdits = 2;
break;
}

int expectedEdits;
if (length <= 2) {
expectedEdits = 0;
} else if (3 <= length && length <= 5) {
expectedEdits = 1;
} else {
expectedEdits = 2;
for (int j = 0; j < 2; j++) {
Query query = queryStringQuery(queryString + (j == 0 ? "~" : "~auto"))
.defaultField(STRING_FIELD_NAME)
.fuzziness(Fuzziness.AUTO)
.toQuery(createShardContext());
assertThat(query, instanceOf(FuzzyQuery.class));
FuzzyQuery fuzzyQuery = (FuzzyQuery) query;
assertEquals(expectedEdits, fuzzyQuery.getMaxEdits());
}
}

Query query = queryStringQuery(queryString.toString()).defaultField(STRING_FIELD_NAME).fuzziness(Fuzziness.AUTO)
.toQuery(createShardContext());
assertThat(query, instanceOf(FuzzyQuery.class));
FuzzyQuery fuzzyQuery = (FuzzyQuery) query;
assertEquals(expectedEdits, fuzzyQuery.getMaxEdits());
}

public void testFuzzyNumeric() throws Exception {
Expand Down

0 comments on commit ab25a01

Please sign in to comment.