How to Use minimum_should_match to Control Partial Matching in OpenSearch Queries

The minimum_should_match parameter specifies exactly how many query terms must appear in a document for it to be considered a hit, enabling granular control over partial matching strictness without reindexing or modifying mapping configurations.

This implementation guide references the aws-samples/sample-for-amazon-opensearch-service-tutorials-101 repository, where minimum_should_match serves as the bridge between user-friendly frontend controls and precise backend search logic. The parameter functions as a runtime knob that adjusts the threshold of term matching required for document retrieval.

How minimum_should_match Controls Query Strictness

The minimum_should_match setting (often exposed as minimumShouldMatch in user interfaces) defines the minimum number of optional should clauses that must satisfy a document. You can express this value as an absolute integer count or as a percentage of total query terms.

  • Exact match requirements: Set to "100%" or an integer equal to the total term count to mandate that every term appears in matching documents.
  • Partial matching flexibility: Use "2" to require at least two terms, or "75%" to require three-quarters of the provided terms.
  • Complex conditional logic: Combine formats such as "2<75%" to apply different rules based on the total number of query terms.

As implemented in this repository, these values pass directly into the OpenSearch DSL match clause, allowing dynamic adjustment of search precision without altering index settings.

Backend Implementation in opensearch_search.py

The Lambda handler in artifacts/search_lambda/opensearch_search.py manages the validation and injection of minimum_should_match into OpenSearch queries. Between lines 25 and 48, the code processes match type requests by validating the parameter type before construction of the search body.

elif body["type"] == "match":
    if "minimum_should_match" in body:
        if not (isinstance(body["minimum_should_match"], int) or
                isinstance(body["minimum_should_match"], str)):
            return failure_response(
                "Invalid request, minimum_should_match should be of type string or integer",
                "400",
            )
        search_body = {
            "size": 100,
            "query": {
                "match": {
                    attribute_name: {
                        "query": attribute_value,
                        "minimum_should_match": body["minimum_should_match"],
                    }
                }
            },
        }

When the client omits minimum_should_match, the Lambda excludes the key from the DSL entirely, allowing OpenSearch to apply its default matching behavior (typically requiring all terms). The validation logic explicitly rejects non-string and non-integer types with a 400 Bad Request response.

For complex any (OR-style) searches, the repository demonstrates additional usage at lines 54-58 by enforcing minimum_should_match: 1 on boolean queries:

if search_type == "any" and should_conditions:
    search_body["query"]["bool"]["should"] = should_conditions
    search_body["query"]["bool"]["minimum_should_match"] = 1

This guarantees that documents satisfying at least one optional condition are returned, preventing empty result sets when multiple filters are applied.

Frontend Integration in keyword-match-page.tsx

The React application in artifacts/opensearch-app-ui/src/pages/keyword-match-page.tsx exposes minimum_should_match functionality through a percentage slider interface. Located between lines 42 and 112, the component manages state as an integer and transforms it into the string percentage format required by the OpenSearch DSL.

const [minimum_should_match, setMinimumShouldMatch] = React.useState(10);

// Within the search submission handler:
const payload = {
  type: "match",
  attribute_name: selectedField,
  attribute_value: searchText,
  minimum_should_match: String(minimum_should_match) + "%"
};

The slider configuration restricts values between 10 and 100 percent with 5-percent increments, ensuring users cannot accidentally disable all matching while providing intuitive control over result granularity. The frontend links directly to OpenSearch documentation for the parameter's full grammar via an anchor element: <a href="https://opensearch.org/docs/latest/query-dsl/minimum-should-match/">.

Practical Query Examples

Fixed Threshold Partial Matching

To retrieve documents containing at least two of three search terms, the API accepts the following payload, which the Lambda translates into the corresponding DSL:

request_body = {
    "type": "match",
    "attribute_name": "description",
    "attribute_value": "red running shoes",
    "minimum_should_match": "2"
}

This generates an OpenSearch query matching documents containing any combination of at least two terms ("red", "running", or "shoes").

Percentage-Based Matching

When the UI slider is set to 75 percent for a four-term query, the system constructs DSL requiring three term matches:

{
  "size": 100,
  "query": {
    "match": {
      "title": {
        "query": "waterproof hiking boots men",
        "minimum_should_match": "75%"
      }
    }
  }
}

Boolean Query Enforcement

For searches requiring at least one match among multiple optional filters, the backend injects the parameter directly into the bool query structure:

search_body = {
    "query": {
        "bool": {
            "should": [
                {"match": {"category": "footwear"}},
                {"match": {"material": "leather"}}
            ],
            "minimum_should_match": 1
        }
    }
}

Summary

  • Runtime configurability: The minimum_should_match parameter enables dynamic adjustment of search precision without index reconfiguration or mapping updates.
  • Type safety: The Lambda handler in opensearch_search.py enforces strict validation, accepting only integers and strings while rejecting malformed inputs with HTTP 400 errors.
  • User interface integration: The React frontend exposes the parameter as an intuitive percentage slider, automatically formatting values as strings (e.g., "75%") for the OpenSearch DSL.
  • Dual implementation: The repository utilizes minimum_should_match for both simple match queries and complex bool queries with optional should clauses.
  • Default fallback: Omitting the parameter relies on OpenSearch defaults, which typically enforce 100% term matching for standard match queries.

Frequently Asked Questions

What values can minimum_should_match accept in the OpenSearch DSL?

The parameter accepts integers representing absolute term counts and strings representing percentages or complex expressions (such as "2<75%"). According to the implementation in opensearch_search.py, the Lambda validation layer explicitly checks isinstance(body["minimum_should_match"], int) or isinstance(body["minimum_should_match"], str), returning a 400 error for booleans, floats, or other types.

How does the frontend communicate minimum_should_match to the backend?

The React component in keyword-match-page.tsx maintains state as an integer percentage, then converts it to a string format by appending a percent sign: String(minimum_should_match) + "%". This formatted string travels in the JSON payload to the Lambda function, which inserts it directly into the OpenSearch query DSL without transformation.

What happens if minimum_should_match is omitted from the request?

When the client omits the field, the Lambda handler skips the minimum_should_match injection logic entirely. The resulting OpenSearch query relies on engine defaults, which typically require all query terms to match (equivalent to an AND operation) for standard match queries.

Can minimum_should_match be used with boolean queries?

Yes. The repository demonstrates this capability in opensearch_search.py lines 54-58, where minimum_should_match: 1 is applied to bool queries containing should clauses. This configuration ensures documents matching at least one optional condition are returned, effectively creating an OR-style search while maintaining the flexibility to increase the threshold for stricter requirements.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →