java – 使用spring数据从mongodb中挑选随机条目
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 使用spring数据从mongodb中挑选随机条目,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5616字,纯文字阅读大概需要9分钟。
内容图文
我正在尝试使用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>
有线索吗?
解决方法:
为什么失败
您使用了自定义查询@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中获取一个随机数(假设您首先检索集合中的文档数)
>在聚合查询中
> limit(randomNumber)
>升序
>限制(1)
简而言之,用随机数限制并获取最后一个文档:
$db.story.aggregate([{$limit: RANDOM_NUMBER},{$sort: {_id: 1}}, {$limit: 1}])
内容总结
以上是互联网集市为您收集整理的java – 使用spring数据从mongodb中挑选随机条目全部内容,希望文章能够帮你解决java – 使用spring数据从mongodb中挑选随机条目所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。