For that you will need to use the Product Projection endpoint, where you can query for products which have either a variant "OR" master variant with the key you desire. Through the JVM SDK, you can achieve that by doing the following:
Build a QueryPredicate<EmbeddedProductVariantQueryModel>
for the key you desire :
final String myKey = "foo";
final QueryPredicate<EmbeddedProductVariantQueryModel> queryPredicate =
QueryPredicate.of("key=\"" + myKey + "\"");
Build a Function<ProductProjectionQueryModel, QueryPredicate<ProductProjection>>
to query for the master variant:
final Function<ProductProjectionQueryModel, QueryPredicate<ProductProjection>> mvPredicateFunction = productQueryModel ->
productQueryModel.masterVariant().where(queryPredicate);
Build a Function<ProductProjectionQueryModel, QueryPredicate<ProductProjection>>
to query for the rest of the variants:
final Function<ProductProjectionQueryModel, QueryPredicate<ProductProjection>> variantsPredicateFunction = productQueryModel ->
productQueryModel.variants().where(queryPredicate);
Combine both predicates with a semantic OR operator to build the ProductProjectionQuery
(in this case on the staged
projection):
final ProductProjectionQuery query = ProductProjectionQuery.ofStaged()
.withPredicates(productQueryModel -> mvPredicateFunction
.apply(productQueryModel)
.or(variantsPredicateFunction.apply(productQueryModel)));
Execute the request:
final PagedQueryResult<ProductProjection> requestStage = sphereClient.executeBlocking(query);
Since variant keys are unique, you should be expecting to yield one resulting product projection, if any:
final Optional<ProductProjection> optionalProductProjection = requestStage.head();
Traverse all (including the master variant) variants of the resultant product projection to fetch the matching variant with such key:
final Optional<ProductVariant> optionalVariant = optionalProductProjection.flatMap(
productProjection -> productProjection.getAllVariants().stream()
.filter(productVariant -> myKey.equals(productVariant.getKey()))
.findFirst());
Update:
Steps 1-4 can also be simplified to:
final String myKey = "foo";
final QueryPredicate<ProductProjection> productProjectionQueryPredicate = QueryPredicate
.of("masterVariant(key = \"" + myKey + "\") OR variants(key = \"" + myKey + "\")");
final ProductProjectionQuery query = ProductProjectionQuery.ofStaged().withPredicates(
productProjectionQueryPredicate);