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

fix : added support for multiple values for CONTAIN, START_WITH and END_WITH operators #11068

Merged

Conversation

Nbagga14
Copy link
Contributor

@Nbagga14 Nbagga14 commented Aug 1, 2024

Checklist

  • The PR conforms to DataHub's Contributing Guideline (particularly Commit Message Format)
  • Links to related issues (if applicable)
  • Tests for the changes have been added/updated (if applicable)
  • Docs related to the changes have been added/updated (if applicable). If a new feature has been added a Usage Guide has been added for the same.
  • For any breaking change/potential downtime/deprecation/big changes an entry has been made in Updating DataHub

Summary by CodeRabbit

  • New Features

    • Enhanced query construction methods for better handling of conditions like 'CONTAIN', 'START_WITH', and 'END_WITH'.
    • Improved clarity and modularity in query building through dedicated methods for different conditions.
  • Bug Fixes

    • Improved accuracy of generated queries under various conditions by refining the query builder logic.
  • Tests

    • Added comprehensive tests to validate the new query builder functionalities for 'CONTAIN', 'START_WITH', and 'END_WITH' conditions, ensuring correct output.

Copy link
Contributor

coderabbitai bot commented Aug 1, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The updates to the ESUtils class streamline the query construction process by replacing generic wildcard queries with more specific methods for handling conditions like CONTAIN, START_WITH, and END_WITH. This refactoring enhances code clarity and maintainability, while new test cases bolster the verification of expected behavior for various query scenarios.

Changes

File Change Summary
metadata-io/src/main/java/com/linkedin/metadata/search/utils/ESUtils.java Refactored getQueryBuilderFromCriterionForSingleField method, introduced specific methods for conditions, and added wildcard query building methods.
metadata-io/src/test/java/com/linkedin/metadata/search/utils/ESUtilsTest.java Added tests for CONTAIN, START_WITH, and END_WITH conditions to ensure accurate query generation.

Poem

In fields of code where queries sprout,
A refactor blooms, without a doubt.
Wildcards dance, clear and bright,
Conditions now sing with newfound light.
Hoppy changes, let’s all cheer,
For code that’s tidy, year after year! 🐰✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added product PR or Issue related to the DataHub UI/UX community-contribution PR or Issue raised by member(s) of DataHub Community labels Aug 1, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (3)
metadata-io/src/test/java/com/linkedin/metadata/search/utils/ESUtilsTest.java (3)

149-209: Add assertions for null and empty values.

The test method should also include assertions for null and empty values to ensure robustness.

+    // Add assertions for null and empty values
+    final Criterion nullValueCriterion = new Criterion().setField("myTestField").setCondition(Condition.CONTAIN).setValue(null);
+    result = ESUtils.getQueryBuilderFromCriterion(nullValueCriterion, false, new HashMap<>(), mock(AspectRetriever.class));
+    expected = "{\n" + "  \"wildcard\" : {\n" + "    \"myTestField.keyword\" : {\n" + "      \"wildcard\" : \"**\",\n" + "      \"boost\" : 1.0,\n" + "      \"_name\" : \"myTestField\"\n" + "    }\n" + "  }\n" + "}";
+    Assert.assertEquals(result.toString(), expected);
+
+    final Criterion emptyValueCriterion = new Criterion().setField("myTestField").setCondition(Condition.CONTAIN).setValue("");
+    result = ESUtils.getQueryBuilderFromCriterion(emptyValueCriterion, false, new HashMap<>(), mock(AspectRetriever.class));
+    expected = "{\n" + "  \"wildcard\" : {\n" + "    \"myTestField.keyword\" : {\n" + "      \"wildcard\" : \"**\",\n" + "      \"boost\" : 1.0,\n" + "      \"_name\" : \"myTestField\"\n" + "    }\n" + "  }\n" + "}";
+    Assert.assertEquals(result.toString(), expected);

212-273: Add assertions for null and empty values.

The test method should also include assertions for null and empty values to ensure robustness.

+    // Add assertions for null and empty values
+    final Criterion nullValueCriterion = new Criterion().setField("myTestField").setCondition(Condition.START_WITH).setValue(null);
+    result = ESUtils.getQueryBuilderFromCriterion(nullValueCriterion, false, new HashMap<>(), mock(AspectRetriever.class));
+    expected = "{\n" + "  \"wildcard\" : {\n" + "    \"myTestField.keyword\" : {\n" + "      \"wildcard\" : \"*\",\n" + "      \"boost\" : 1.0,\n" + "      \"_name\" : \"myTestField\"\n" + "    }\n" + "  }\n" + "}";
+    Assert.assertEquals(result.toString(), expected);
+
+    final Criterion emptyValueCriterion = new Criterion().setField("myTestField").setCondition(Condition.START_WITH).setValue("");
+    result = ESUtils.getQueryBuilderFromCriterion(emptyValueCriterion, false, new HashMap<>(), mock(AspectRetriever.class));
+    expected = "{\n" + "  \"wildcard\" : {\n" + "    \"myTestField.keyword\" : {\n" + "      \"wildcard\" : \"*\",\n" + "      \"boost\" : 1.0,\n" + "      \"_name\" : \"myTestField\"\n" + "    }\n" + "  }\n" + "}";
+    Assert.assertEquals(result.toString(), expected);

276-336: Add assertions for null and empty values.

The test method should also include assertions for null and empty values to ensure robustness.

+    // Add assertions for null and empty values
+    final Criterion nullValueCriterion = new Criterion().setField("myTestField").setCondition(Condition.END_WITH).setValue(null);
+    result = ESUtils.getQueryBuilderFromCriterion(nullValueCriterion, false, new HashMap<>(), mock(AspectRetriever.class));
+    expected = "{\n" + "  \"wildcard\" : {\n" + "    \"myTestField.keyword\" : {\n" + "      \"wildcard\" : \"*\",\n" + "      \"boost\" : 1.0,\n" + "      \"_name\" : \"myTestField\"\n" + "    }\n" + "  }\n" + "}";
+    Assert.assertEquals(result.toString(), expected);
+
+    final Criterion emptyValueCriterion = new Criterion().setField("myTestField").setCondition(Condition.END_WITH).setValue("");
+    result = ESUtils.getQueryBuilderFromCriterion(emptyValueCriterion, false, new HashMap<>(), mock(AspectRetriever.class));
+    expected = "{\n" + "  \"wildcard\" : {\n" + "    \"myTestField.keyword\" : {\n" + "      \"wildcard\" : \"*\",\n" + "      \"boost\" : 1.0,\n" + "      \"_name\" : \"myTestField\"\n" + "    }\n" + "  }\n" + "}";
+    Assert.assertEquals(result.toString(), expected);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2ab43f3 and c094fa6.

Files selected for processing (2)
  • metadata-io/src/main/java/com/linkedin/metadata/search/utils/ESUtils.java (1 hunks)
  • metadata-io/src/test/java/com/linkedin/metadata/search/utils/ESUtilsTest.java (1 hunks)
Additional comments not posted (5)
metadata-io/src/main/java/com/linkedin/metadata/search/utils/ESUtils.java (5)

592-603: LGTM!

The method correctly constructs a wildcard query for a single value.


605-616: LGTM!

The method correctly constructs a wildcard query for the CONTAIN condition.


618-629: LGTM!

The method correctly constructs a wildcard query for the START_WITH condition.


631-642: LGTM!

The method correctly constructs a wildcard query for the END_WITH condition.


561-568: Ensure consistent query naming.

The method correctly delegates to specific methods for handling different conditions. Ensure that the query naming is consistent across all conditions.

Verification successful

Query naming is consistent across all conditions.

The queryName parameter is consistently passed and used in the methods buildContainsConditionFromCriterion, buildStartsWithConditionFromCriterion, and buildEndsWithConditionFromCriterion. No issues were found regarding query naming consistency.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the query naming is consistent across all conditions.

# Test: Search for queryName usage. Expect: Consistent query naming.
rg --type java 'queryName'

Length of output: 7903


Script:

#!/bin/bash
# Search for the definitions of the methods to verify the usage of `queryName`.

# Find the definition of `buildContainsConditionFromCriterion`
ast-grep --lang java --pattern 'buildContainsConditionFromCriterion($_, $_, $_, $_, $_)' 

# Find the definition of `buildStartsWithConditionFromCriterion`
ast-grep --lang java --pattern 'buildStartsWithConditionFromCriterion($_, $_, $_, $_, $_)' 

# Find the definition of `buildEndsWithConditionFromCriterion`
ast-grep --lang java --pattern 'buildEndsWithConditionFromCriterion($_, $_, $_, $_, $_)' 

Length of output: 1143


Script:

#!/bin/bash
# Search for the definitions of the methods to verify the usage of `queryName`.

# Find the definition of `buildContainsConditionFromCriterion`
ast-grep --lang java --pattern 'public $_ buildContainsConditionFromCriterion($_, $_, $_, $_, $_)' 

# Find the definition of `buildStartsWithConditionFromCriterion`
ast-grep --lang java --pattern 'public $_ buildStartsWithConditionFromCriterion($_, $_, $_, $_, $_)' 

# Find the definition of `buildEndsWithConditionFromCriterion`
ast-grep --lang java --pattern 'public $_ buildEndsWithConditionFromCriterion($_, $_, $_, $_, $_)' 

Length of output: 1770


Script:

#!/bin/bash
# Search for the definitions of the methods to verify the usage of `queryName`.

# Find the definition of `buildContainsConditionFromCriterion`
ast-grep --lang java --pattern 'function buildContainsConditionFromCriterion($_, $_, $_, $_, $_) { $$$ }' 

# Find the definition of `buildStartsWithConditionFromCriterion`
ast-grep --lang java --pattern 'function buildStartsWithConditionFromCriterion($_, $_, $_, $_, $_) { $$$ }' 

# Find the definition of `buildEndsWithConditionFromCriterion`
ast-grep --lang java --pattern 'function buildEndsWithConditionFromCriterion($_, $_, $_, $_, $_) { $$$ }' 

Length of output: 1812


Script:

#!/bin/bash
# Search for the definitions of the methods to verify the usage of `queryName`.

# Find the definition of `buildContainsConditionFromCriterion`
rg 'buildContainsConditionFromCriterion' -A 10 metadata-io/src/main/java/com/linkedin/metadata/search/utils/ESUtils.java

# Find the definition of `buildStartsWithConditionFromCriterion`
rg 'buildStartsWithConditionFromCriterion' -A 10 metadata-io/src/main/java/com/linkedin/metadata/search/utils/ESUtils.java

# Find the definition of `buildEndsWithConditionFromCriterion`
rg 'buildEndsWithConditionFromCriterion' -A 10 metadata-io/src/main/java/com/linkedin/metadata/search/utils/ESUtils.java

Length of output: 3632

Comment on lines 574 to 588
private static QueryBuilder buildWildcardQueryWithMultipleValues(
@Nonnull final String fieldName,
@Nonnull final Criterion criterion,
final boolean isTimeseries,
@Nullable String queryName,
@Nonnull AspectRetriever aspectRetriever,
String wildcardPattern) {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

for (String value : criterion.getValues()) {
boolQuery.should(QueryBuilders.wildcardQuery(
toKeywordField(criterion.getField(), isTimeseries, aspectRetriever),
String.format(wildcardPattern, ESUtils.escapeReservedCharacters(value.trim())))
.queryName(queryName != null ? queryName : fieldName));
}
return boolQuery;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize wildcard query construction.

The method can be optimized by using a stream to construct the wildcard query.

-    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
-    for (String value : criterion.getValues()) {
-      boolQuery.should(QueryBuilders.wildcardQuery(
-                      toKeywordField(criterion.getField(), isTimeseries, aspectRetriever),
-                      String.format(wildcardPattern, ESUtils.escapeReservedCharacters(value.trim())))
-              .queryName(queryName != null ? queryName : fieldName));
-    }
-    return boolQuery;
+    return criterion.getValues().stream()
+        .map(value -> QueryBuilders.wildcardQuery(
+                toKeywordField(criterion.getField(), isTimeseries, aspectRetriever),
+                String.format(wildcardPattern, ESUtils.escapeReservedCharacters(value.trim())))
+            .queryName(queryName != null ? queryName : fieldName))
+        .collect(Collectors.collectingAndThen(Collectors.toList(), queries -> {
+            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
+            queries.forEach(boolQuery::should);
+            return boolQuery;
+        }));
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private static QueryBuilder buildWildcardQueryWithMultipleValues(
@Nonnull final String fieldName,
@Nonnull final Criterion criterion,
final boolean isTimeseries,
@Nullable String queryName,
@Nonnull AspectRetriever aspectRetriever,
String wildcardPattern) {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
for (String value : criterion.getValues()) {
boolQuery.should(QueryBuilders.wildcardQuery(
toKeywordField(criterion.getField(), isTimeseries, aspectRetriever),
String.format(wildcardPattern, ESUtils.escapeReservedCharacters(value.trim())))
.queryName(queryName != null ? queryName : fieldName));
}
return boolQuery;
}
private static QueryBuilder buildWildcardQueryWithMultipleValues(
@Nonnull final String fieldName,
@Nonnull final Criterion criterion,
final boolean isTimeseries,
@Nullable String queryName,
@Nonnull AspectRetriever aspectRetriever,
String wildcardPattern) {
return criterion.getValues().stream()
.map(value -> QueryBuilders.wildcardQuery(
toKeywordField(criterion.getField(), isTimeseries, aspectRetriever),
String.format(wildcardPattern, ESUtils.escapeReservedCharacters(value.trim())))
.queryName(queryName != null ? queryName : fieldName))
.collect(Collectors.collectingAndThen(Collectors.toList(), queries -> {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
queries.forEach(boolQuery::should);
return boolQuery;
}));
}

@Nbagga14
Copy link
Contributor Author

@david-leifker can you please review the above PR?

@david-leifker
Copy link
Collaborator

david-leifker commented Sep 3, 2024

@Nbagga14 - Please run ./gradlew spotlessApply --rerun-tasks

@david-leifker david-leifker self-assigned this Sep 5, 2024
@david-leifker david-leifker merged commit 455c90f into datahub-project:master Sep 6, 2024
41 checks passed
@david-leifker
Copy link
Collaborator

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
community-contribution PR or Issue raised by member(s) of DataHub Community product PR or Issue related to the DataHub UI/UX
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants