如何从Commercetools平台中的唯一ID获取类别名称?

时间:2015-12-31 19:49:00

标签: java api commercetools

我试图在Commercetools平台上获取产品所属的所有类别的名称。

通过以下调用,我可以获得与产品相关联的每个类别的唯一ID:

final ProductProjectionQuery query = ProductProjectionQuery.ofCurrent();
    ProductProjectionQuery q = query.withLimit(450);

    try {
        PagedQueryResult<io.sphere.sdk.products.ProductProjection> pagedQueryResult = client.execute(q).toCompletableFuture().get();
        List<io.sphere.sdk.products.ProductProjection> products = pagedQueryResult.getResults();

        //createDocument(products.get(0).getMasterVariant(), request);

        for (io.sphere.sdk.products.ProductProjection product : products) {
            String categoryId = product.getCategories().iterator().next().getId();
            //createDocument(product.getMasterVariant(), request);
        }
    }

虽然我有了categoryId,但我不确定如何访问类别名称。我认为obj属性可能允许我深入到类别,但是obj变量似乎总是 null

1 个答案:

答案 0 :(得分:3)

obj变量为null,因为您尚未展开引用。除非您明确请求,否则所有引用都将为空以提高性能。为了扩展它,您可以使用以下代码:

// Query products
final ProductProjectionQuery query = ProductProjectionQuery.ofCurrent()
        .withExpansionPaths(product -> product.categories()) // Request to expand categories
        .withLimit(450);
final List<ProductProjection> products = client.execute(query).toCompletableFuture().join().getResults();

for (ProductProjection product : products) {
    final List<LocalizedString> categoryLocalizedNames = product.getCategories().stream()
            .map(categoryRef -> categoryRef.getObj().getName())
            .collect(toList());
    // Do something with categoryLocalizedNames
}

但我强烈建议您在CategoryTree实例中缓存这些类别并从中获取名称,否则通过扩展每个产品的所有类别会对性能产生很大影响。这是代码:

// Query all categories and put them in a CategoryTree
final CategoryQuery queryAllCategories = CategoryQuery.of().withLimit(500);
final List<Category> allCategories = client.execute(queryAllCategories).toCompletableFuture().join().getResults();
final CategoryTree categoryTree = CategoryTree.of(allCategories);

// Query products
final ProductProjectionQuery query = ProductProjectionQuery.ofCurrent().withLimit(500);
final List<ProductProjection> products = client.execute(query).toCompletableFuture().join().getResults();

for (ProductProjection product : products) {
    final List<LocalizedString> categoryLocalizedNames = new ArrayList<>();
    product.getCategories().forEach(categoryRef -> {
        final Optional<Category> categoryOpt = categoryTree.findById(categoryRef.getId());
        if (categoryOpt.isPresent()) {
            categoryLocalizedNames.add(categoryOpt.get().getName());
        }
    });
    // Do something with categoryLocalizedNames
}

当然,这意味着您还必须找到一个解决方案,以便在缓存的类别发生变化时使其无效。