【问题标题】:Picking random entries from mongodb using spring data使用spring数据从mongodb中选择随机条目
【发布时间】:2016-09-16 20:26:26
【问题描述】:

我正在尝试使用 spring 从 mongodb 获取 x 个随机条目。

我的仓库如下所示

public interface StoryRepository extends MongoRepository<Story, Long> {
    @Query("{$sample: {size: ?0} }")
    List<Story> findRandom(int quantity);
}

我得到的错误看起来像这样

com.mongodb.BasicDBObject cannot be cast to org.springframework.data.domain.Example

我也尝试了以下给出完全相同的错误

    public List<Story> findRandom(final int quantity) {
        CustomAggregationOperation customAggregationOperation = new CustomAggregationOperation(new BasicDBObject("$sample", new BasicDBObject("size", quantity)));
        TypedAggregation<Story> aggregation = new TypedAggregation<>(Story.class, customAggregationOperation);
        AggregationResults<Story> aggregationResults = mongoTemplate.aggregate(aggregation, Story.class);
        return aggregationResults.getMappedResults();
    }

我的故事类如下所示

public class Story {
    @Id
    private long id;
    private String by;
    private int descendants;
    private List<Long> kids;
    private int score;
    private long time;
    private String title;
    private String type;
    private String url;

    private By author;


    public long getId() {
        return id;
    }

    ...
}

我的pom文件如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>dk.tons.hackernews.backend</groupId>
<artifactId>tons-hackernews-backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Backend</name>
<description>Tons Hacker News Backend</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

有什么线索吗?

【问题讨论】:

  • ExampleStory 的子类吗?
  • 不,我不知道它是什么......我没有使用它。
  • 请发布您的 Story 课程和您的 POM/Gradle 文件。
  • 完成... Stackoverflow 迫使我写的比完成...
  • (请注意,从个人经验来看,对于这种数据对象之间有大量关系的模型,MongoDB 是一个糟糕的选择:您必须手动完成所有连接。)

标签: java spring mongodb spring-data spring-data-mongodb


【解决方案1】:

为什么会失败

您使用了自定义查询@Query("{$sample: {size: ?0} }") 和/或像这样定义了您的CustomAggregationOperation(使用context.getMappedObject):

public class CustomAggregationOperation implements AggregationOperation {
    private DBObject operation;
    public CustomAggregationOperation (DBObject operation) {
        this.operation = operation;
    }
    @Override
    public DBObject toDBObject(final AggregationOperationContext context) {
        return context.getMappedObject(operation);
    }
}

两者都经过QueryMapper.getMappedKeyword,这是引发错误的spring方法。如果你打开spring的QueryMapper.getMappedKeyword,你会看到:

protected DBObject getMappedKeyword(Keyword keyword, MongoPersistentEntity<?> entity) {
    ...
    if (keyword.isSample()) {
        return exampleMapper.getMappedExample(keyword.<Example<?>> getValue(), entity);
    }
    ...
}

public boolean isSample() {
    return "$sample".equalsIgnoreCase(key);
}

它会解析查询并在找到单​​词$sample 时尝试使用Example这解释了您的错误。

现在的问题是:如何在没有$sample 或绕过这条逻辑的情况下实现你想要的?此外,对 Spring 的 JIRA 提出了改进请求,这将确认 $sample 不支持开箱即用:https://jira.spring.io/browse/DATAMONGO-1415

(1) 不使用 AggregationOperationContext 实现 CustomSampleOperation

不使用上下文返回 $sample 查询:

CustomSampleOperation customSampleOperation = new CustomSampleOperation(1);
TypedAggregation<Story> typedAggr = Aggregation.newAggregation(Story.class, 
    customSampleperation);

AggregationResults<Story> aggregationResults = mongoTemplate.aggregate(typedAggr, Story.class);
aggregationResults.getMappedResults().get(0);

...

public class CustomSampleOperation implements AggregationOperation {
    private int size;
    public CustomSampleOperation(int size){
        this.size = size;   
    }

    @Override
    public DBObject toDBObject(final AggregationOperationContext context){
        return new BasicDBObject("$sample", new BasicDBObject("size", size));
    }
}

如果您查看其他操作的编写方式,我们就知道了 (LimitOperation):

public class LimitOperation implements AggregationOperation {
    private final long maxElements;
    public LimitOperation(long maxElements) {
        this.maxElements = maxElements;
    }

    public DBObject toDBObject(AggregationOperationContext context) {    
        return new BasicDBObject("$limit", maxElements);
    }
}

(2) 如果需要,可以使其通用

为了让您的 CustomOperation 保持通用性,您可以这样定义它:

CustomGenericOperation customGenericOperation = 
    new CustomGenericOperation(new BasicDBObject("$sample", new BasicDBObject("size", 1)));    
...

public class CustomGenericOperation implements AggregationOperation {
    private DBObject dbObject;
    public CustomGenericOperation(DBObject dbObject){
        this.dbObject = dbObject;

    }
    @Override
    public DBObject toDBObject(final AggregationOperationContext context) {
        return dbObject;
    }
}

(3) 替代方案

除了定义自定义 AggregationOperation,您还可以:

  • 在 Java 中获取一个随机数(假设您首先检索集合中的文档数)
  • 在聚合查询中
    • 限制(随机数)
    • 升序排序
    • 限制(1)

简而言之,用一个随机数限制,得到最后一个文档:

$ db.story.aggregate([{$limit: RANDOM_NUMBER},{$sort: {_id: 1}}, {$limit: 1}])

【讨论】:

  • 但这不是错误吗?我的意思是无法使用 $sample 运算符
  • 我不会说这是一个错误..只是我们现在不知道如何使用? :)
  • 谢谢!哇!但是@Query("{$sample: {size: ?0} }") 不起作用不是问题吗?
  • 我仍然认为他们对示例有所了解,只是没有记录。但是,我看到很少有人要求提供 $sample 支持:jira.spring.io/browse/DATAMONGO-1415jira.spring.io/browse/DATAMONGO-1325。建议我们目前的解决方案是正确的!
猜你喜欢
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
相关资源
最近更新 更多