分面分类 - Spring 数据 Mongo

Faceted classification - Spring Data Mongo

我正在尝试使用 Spring 数据 Mongo 构建分面分类,但我对如何使用 Aggregation.facet 方法感到困惑。

当我试图弄清楚它是如何工作的时,我使用了两次相同的 FacetOperation,我得到了一个 java.lang.IllegalArgumentException: Invalid reference 'producer.fundings'!。这个 FacetOperation 单独在 Aggregation 中工作正常!

FacetOperation fo1 = facet(
        unwind("producer.fundings"),
        project().and("producer.fundings.type").as("type").and("producer.fundings.acronym").as("name"),
        group("name", "type").count().as("count"),
        project("count").and("_id.name").as("name").and("_id.type").as("type").andExclude("_id")
    ).as("fundingAcronymFacet");

    FacetOperation fo2 = facet(
        unwind("producer.fundings"),
        project().and("producer.fundings.type").as("type").and("producer.fundings.acronym").as("name"),
        group("name", "type").count().as("count"),
        project("count").and("_id.name").as("name").and("_id.type").as("type").andExclude("_id")
    ).as("fundingNameFacet");

Aggregation agg = Aggregation.newAggregation(fo1,fo2);
AggregationResults<FacetClassification> groupResults = mongoTemplate.aggregate(agg, "observations", FacetClassification.class);
List<FacetClassification> facet = groupResults.getMappedResults();

所以要么我没有很好地使用 facet 方法,只需要一次调用就可以创建不同的 facet。这看起来像它在 MongoDB API 中的实现方式:$facet (aggregation) 或者我需要链接 facet 调用来创建我的分类的不同方面,并且需要知道在第一次调用之后会发生什么以及为什么找不到完全相同的引用。

该文档仅提供了创建一个方面的示例,在其他地方找不到任何示例:Spring Data Mongo Faceted Classification

相关:Using multiple facets in MongoDB Spring Data

如有任何帮助,我们将不胜感激!

您可以使用 and().as() 方法链接多个方面的操作。该示例应如下所示,以在同一聚合操作中创建两个不同的方面:

FacetOperation fo1 = facet(
        unwind("producer.fundings"),
        project().and("producer.fundings.type").as("type").and("producer.fundings.acronym").as("name"),
        group("name", "type").count().as("count"),
        project("count").and("_id.name").as("name").and("_id.type").as("type").andExclude("_id")
).as("fundingAcronymFacet")
        .and(unwind("producer.fundings"),
                project().and("producer.fundings.type").as("type").and("producer.fundings.acronym").as("name"),
                group("name", "type").count().as("count"),
                project("count").and("_id.name").as("name").and("_id.type").as("type").andExclude("_id")
        ).as("fundingNamesFacet");