Java Code Examples for org.springframework.data.mongodb.core.query.Query#limit()

The following examples show how to use org.springframework.data.mongodb.core.query.Query#limit() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IngestionBatchJobDAOImpl.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public List<IngestionBatchJob> find(String tenantId, Integer limit, Integer offset, String sortOn, Order order) {
	Query query = new Query();

	// Tenant Id is required.
	query.addCriteria(Criteria.where("tenantId").is(tenantId));
	/*
	 * We are going to allow for null for multiple items, so we'll do a null check on each.
	 */
	if (limit != null) {
		query.limit(limit);
	}
	
	if (offset != null) {
		query.skip(offset);
	}

	if (sortOn != null && !"".equals(sortOn)) {
		if (order != null) {
			query.sort().on(sortOn, order);
		} else {
			query.sort().on(sortOn, Order.ASCENDING);
		}
	}
	return ingestionBatchJobMongoTemplate.find(query, IngestionBatchJob.class);
}
 
Example 2
Source File: MongoDataPointRepositoryImpl.java    From omh-dsu-ri with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<DataPoint> findBySearchCriteria(DataPointSearchCriteria searchCriteria, @Nullable Integer offset,
        @Nullable Integer limit) {

    checkNotNull(searchCriteria);
    checkArgument(offset == null || offset >= 0);
    checkArgument(limit == null || limit >= 0);

    Query query = newQuery(searchCriteria);

    if (offset != null) {
        query.skip(offset);
    }

    if (limit != null) {
        query.limit(limit);
    }

    return mongoOperations.find(query, DataPoint.class);
}
 
Example 3
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> List<T> queryIntersection(Class<T> clazz, Map<String, Object> condition, StoragePagination pagination) {
	MongoMetadata metadata = metadatas.get(clazz);
	final Iterator<Entry<String, Object>> conditionIterator = condition.entrySet().iterator();
	Criteria criteria = Criteria.where(MongoMetadata.mongoId).exists(true);
	Criteria[] andCriterias = new Criteria[condition.size()];
	int index = 0;
	while (conditionIterator.hasNext()) {
		Entry<String, Object> keyValue = conditionIterator.next();
		String key = keyValue.getKey();
		Object value = keyValue.getValue();
		if (metadata.getPrimaryName().equals(key)) {
			key = MongoMetadata.mongoId;
		}
		andCriterias[index++] = Criteria.where(key).is(value);
	}
	Query query = Query.query(criteria.andOperator(andCriterias));
	if (pagination != null) {
		query.skip(pagination.getFirst());
		query.limit(pagination.getSize());
	}
	return template.find(query, clazz, metadata.getOrmName());
}
 
Example 4
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> List<T> queryUnion(Class<T> clazz, Map<String, Object> condition, StoragePagination pagination) {
	MongoMetadata metadata = metadatas.get(clazz);
	final Iterator<Entry<String, Object>> conditionIterator = condition.entrySet().iterator();
	Criteria criteria = Criteria.where(MongoMetadata.mongoId).exists(true);
	Criteria[] orCriterias = new Criteria[condition.size()];
	int index = 0;
	while (conditionIterator.hasNext()) {
		Entry<String, Object> keyValue = conditionIterator.next();
		String key = keyValue.getKey();
		Object value = keyValue.getValue();
		if (metadata.getPrimaryName().equals(key)) {
			key = MongoMetadata.mongoId;
		}
		orCriterias[index++] = Criteria.where(key).is(value);
	}
	Query query = Query.query(criteria.orOperator(orCriterias));
	if (pagination != null) {
		query.skip(pagination.getFirst());
		query.limit(pagination.getSize());
	}
	return template.find(query, clazz, metadata.getOrmName());
}
 
Example 5
Source File: SimilarityManager.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<Artifact> getSimilarProjects(Artifact prj1, int numResult) {
	Query q1 = new Query(new Criteria().orOperator(Criteria.where("toArtifact.$id").is(new ObjectId(prj1.getId())),
			Criteria.where("fromArtifact.$id").is(new ObjectId(prj1.getId()))));
	q1.with(new Sort(Sort.Direction.DESC, "value"));
	q1.limit(numResult);
	List<Relation> r1 = mongoOperations.find(q1, Relation.class);
	List<Artifact> results = new ArrayList<>();
	for (Relation rel : r1) {
		if (rel.getFromProject().getId().equals(prj1.getId()))
			results.add(rel.getToProject());
		else
			results.add(rel.getFromProject());
	}
	return results;
}
 
Example 6
Source File: GalleryRepositoryImpl.java    From jakduk-api with MIT License 6 votes vote down vote up
/**
 * 사진첩 보기의 앞, 뒤 사진을 가져온다.
 */
@Override
public List<Gallery> findGalleriesById(ObjectId id, Constants.CRITERIA_OPERATOR operator, Integer limit) {
    Query query = new Query();
    query.addCriteria(Criteria.where("status.status").is(Constants.GALLERY_STATUS_TYPE.ENABLE.name()));
    query.limit(limit);

    if (Objects.nonNull(id)) {
        switch (operator) {
            case GT:
                query.addCriteria(Criteria.where("_id").gt(id));
                break;
            case LT:
                query.addCriteria(Criteria.where("_id").lt(id));
                break;
        }
    }

    query.with(new Sort(Sort.Direction.DESC, "_id"));

    return mongoTemplate.find(query, Gallery.class);
}
 
Example 7
Source File: EventMongoDBDaoImpl.java    From chronus with Apache License 2.0 6 votes vote down vote up
@Override
public List<EventEntity> getLastEvent(String cluster, String address, String version) {
    Query query = new Query();
    query.addCriteria(Criteria.where("cluster").is(cluster));
    query.addCriteria(Criteria.where("address").is(address));
    query.addCriteria(Criteria.where("version").is(version));
    query.with(new Sort(Sort.Direction.DESC, "dateCreated"));
    query.limit(3);
    return super.selectList(query);
}
 
Example 8
Source File: RiskService.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
/**
 * Get RiskScore for a user and a class given
 *
 * @param tenantId
 * @param orgId
 * @param classId
 * @param userId
 * @param date : format 'yyyy-mm-dd' or keyword 'latest'
 * @return Collection<MongoRisk>
 */
public Collection<MongoRisk> getRisksForUserAndClass(
        final String tenantId, final String orgId, final String classId,
        final String userId, final String date, final int limit
){
    if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(orgId) || StringUtils.isBlank(userId) || StringUtils.isBlank(classId))
        throw new IllegalArgumentException();

    Collection<MongoRisk> mongoRisks;

    Query query = new Query();
    query.with(Sort.by("dateTime").descending()); // Order by date: the most recent
    query.addCriteria(where("userSourcedId").is(userId).and("classSourcedId").is(classId).and("orgId").is(orgId).and("tenantId").is(tenantId));

    if (limit > 0)
        query.limit(limit);

    this.dayCriteria(query, date);

    mongoRisks = mongoOps.find(query, MongoRisk.class);

    if (!mongoRisks.isEmpty())
        return new ArrayList<>(mongoRisks);

    throw new OneRosterNotFoundException("Risks not found.");
}
 
Example 9
Source File: RiskService.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
/**
 * Get RiskScore for a user and a class given
 *
 * @param tenantId
 * @param orgId
 * @param classId
 * @param date : format 'yyyy-mm-dd' or keyword 'latest'
 * @return Collection<MongoRisk>
 */
public Collection<MongoRisk> getRisksForClass(final String tenantId, final String orgId, final String classId, final String date, final int limit){
    if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(orgId) || StringUtils.isBlank(classId))
        throw new IllegalArgumentException();

    Collection<MongoRisk> mongoRisks;

    Query query = new Query();

    query.with(Sort.by("dateTime").descending()); // Order by date: the most recent
    query.addCriteria(where("classSourcedId").is(classId).and("orgId").is(orgId).and("tenantId").is(tenantId));

    if (limit > 0)
        query.limit(limit);

    this.dayCriteria(query, date);
    mongoRisks = mongoOps.find(query, MongoRisk.class);

    if (!mongoRisks.isEmpty())
        return new ArrayList<>(mongoRisks);

    throw new OneRosterNotFoundException("Risks not found.");
}
 
Example 10
Source File: ProxyDaoImpl.java    From ProxyPool with Apache License 2.0 5 votes vote down vote up
@Override
public List<ProxyData> findProxyByCond(QueryProxyDTO queryProxyDTO, boolean isGetAll) {
    Query query = new Query();
    if(Preconditions.isNotBlank(queryProxyDTO.getType()) && !"all".equals(queryProxyDTO.getType())) {
        query.addCriteria(Criteria.where("proxyType").is(queryProxyDTO.getType()));
    }
    if(Preconditions.isNotBlank(queryProxyDTO.getIp()) && !"all".equals(queryProxyDTO.getIp())) {
        query.addCriteria(Criteria.where("proxyAddress").regex(".*?"+queryProxyDTO.getIp()+".*"));
    }
    if(queryProxyDTO.getMinPort() != null) {
        query.addCriteria(Criteria.where("proxyPort").gte(queryProxyDTO.getMinPort()).lte(queryProxyDTO.getMaxPort()));
    }
    if(!isGetAll) {
        if(Preconditions.isNotBlank(queryProxyDTO.getSort())) {
            if("asc".equals(queryProxyDTO.getOrder())) {
                query.with(new Sort(Sort.Direction.ASC, queryProxyDTO.getSort()));
            } else {
                query.with(new Sort(Sort.Direction.DESC, queryProxyDTO.getSort()));
            }
        } else {
            query.with(new Sort(Sort.Direction.DESC, "lastSuccessfulTime"));
            query.with(new Sort(Sort.Direction.ASC, "proxyPort"));
        }
        int skip = (queryProxyDTO.getPage() - 1) * queryProxyDTO.getRows();
        query.skip(skip);
        query.limit(queryProxyDTO.getRows());
    }
    return mongoTemplate.find(query, ProxyData.class, Constant.COL_NAME_PROXY);
}
 
Example 11
Source File: ArticleCommentRepositoryImpl.java    From jakduk-api with MIT License 5 votes vote down vote up
@Override
public List<ArticleCommentSimple> findSimpleComments() {
    Query query = new Query();
    query.with(new Sort(Sort.Direction.DESC, "_id"));
    query.limit(Constants.HOME_SIZE_LINE_NUMBER);

    return mongoTemplate.find(query, ArticleCommentSimple.class);
}
 
Example 12
Source File: BatchJobMongoDA.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public List<NewBatchJob> findLatestBatchJobs(int limit)
{
    Query query = new Query();
    query.sort().on("jobStartTimestamp", Order.DESCENDING);
    query.limit(limit);
    List<NewBatchJob> sortedBatchJobs = batchJobMongoTemplate.find(query, NewBatchJob.class);
    if (sortedBatchJobs.size() == 0) { sortedBatchJobs = null; } 
    return sortedBatchJobs;
}
 
Example 13
Source File: UserRepositoryImpl.java    From jakduk-api with MIT License 5 votes vote down vote up
@Override
public List<UserSimple> findSimpleUsers() {
    Query query = new Query();
    query.with(new Sort(Sort.Direction.DESC, "_id"));
    query.limit(Constants.HOME_SIZE_LINE_NUMBER);

    return mongoTemplate.find(query, UserSimple.class);
}
 
Example 14
Source File: GalleryRepositoryImpl.java    From jakduk-api with MIT License 5 votes vote down vote up
@Override
public List<GallerySimple> findSimpleById(ObjectId id, Integer limit) {

    Query query = new Query();
    query.addCriteria(Criteria.where("status.status").is(Constants.GALLERY_STATUS_TYPE.ENABLE.name()));
    query.limit(limit);

    if (Objects.nonNull(id)) {
        query.addCriteria(Criteria.where("_id").lt(id));
    }

    query.with(new Sort(Sort.Direction.DESC, "_id"));

    return mongoTemplate.find(query, GallerySimple.class);
}
 
Example 15
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> void iterateUnion(StorageIterator<T> iterator, Class<T> clazz, Map<String, Object> condition, StoragePagination pagination) {
	MongoMetadata metadata = metadatas.get(clazz);
	final Iterator<Entry<String, Object>> conditionIterator = condition.entrySet().iterator();
	Criteria criteria = Criteria.where(MongoMetadata.mongoId).exists(true);
	Criteria[] orCriterias = new Criteria[condition.size()];
	int index = 0;
	while (conditionIterator.hasNext()) {
		Entry<String, Object> keyValue = conditionIterator.next();
		String key = keyValue.getKey();
		Object value = keyValue.getValue();
		if (metadata.getPrimaryName().equals(key)) {
			key = MongoMetadata.mongoId;
		}
		orCriterias[index++] = Criteria.where(key).is(value);
	}
	Query query = Query.query(criteria.orOperator(orCriterias));
	if (pagination != null) {
		query.skip(pagination.getFirst());
		query.limit(pagination.getSize());
	}
	try (CloseableIterator<T> stream = template.stream(query, clazz, metadata.getOrmName())) {
		while (stream.hasNext()) {
			try {
				// TODO 需要考虑中断
				final T object = stream.next();
				iterator.iterate(object);
			} catch (Throwable throwable) {
				throw new StorageQueryException(throwable);
			}
		}
	}
}
 
Example 16
Source File: ArticleCommentRepositoryImpl.java    From jakduk-api with MIT License 5 votes vote down vote up
/**
 * Board Seq와 기준 ArticleComment ID(null 가능) 이상의 ArticleComment 목록을 가져온다.
 *
 * @param articleSeq  게시물 seq
 * @param commentId 댓글 ID
 */
@Override
public List<ArticleComment> findByBoardSeqAndGTId(String board, Integer articleSeq, ObjectId commentId) {
    Query query = new Query();
    query.addCriteria(Criteria.where("article.seq").is(articleSeq).and("article.board").is(board));

    if (Objects.nonNull(commentId))
        query.addCriteria(Criteria.where("_id").gt(commentId));

    query.with(new Sort(Sort.Direction.ASC, "_id"));
    query.limit(Constants.COMMENT_MAX_LIMIT);

    return mongoTemplate.find(query, ArticleComment.class);
}
 
Example 17
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> List<T> queryInstances(Class<T> clazz, StoragePagination pagination) {
	MongoMetadata metadata = metadatas.get(clazz);
	Query query = new Query(Criteria.where(MongoMetadata.mongoId).exists(true));
	if (pagination != null) {
		query.skip(pagination.getFirst());
		query.limit(pagination.getSize());
	}
	return template.find(query, clazz, metadata.getOrmName());
}
 
Example 18
Source File: ArticleRepositoryImpl.java    From jakduk-api with MIT License 5 votes vote down vote up
/**
 * 홈에서 보여지는 최근글 목록
 */
@Override
public List<ArticleOnList> findLatest(Sort sort, Integer limit) {
    Query query = new Query();
    query.with(sort);
    query.limit(limit);

    return mongoTemplate.find(query, ArticleOnList.class);
}
 
Example 19
Source File: ExternalMonitorServiceImpl.java    From ExecDashboard with Apache License 2.0 5 votes vote down vote up
@Override
public List<ExternalSystemMonitor> getLatestRecord() {
	List<ExternalSystemMonitor> results = new ArrayList<>();
	List<String> distinctsources = mongoTemplate.getCollection("externalmonitor").distinct("sourceSystemName");
	for (String type : distinctsources) {
		Query query = new Query();
		query.addCriteria(new Criteria().where("sourceSystemName").is(type));
		query.with(new Sort(Sort.Direction.DESC, "lastConnectedTime"));
		query.limit(1);
		ExternalSystemMonitor result = mongoTemplate.findOne(query, ExternalSystemMonitor.class);
		results.add(result);
	}
	return results;
}
 
Example 20
Source File: MongoPageHelper.java    From zheshiyigeniubidexiangmu with MIT License 4 votes vote down vote up
/**
 * 分页查询.
 *
 * @param query       Mongo Query对象,构造你自己的查询条件.
 * @param entityClass Mongo collection定义的entity class,用来确定查询哪个集合.
 * @param mapper      映射器,你从db查出来的list的元素类型是entityClass, 如果你想要转换成另一个对象,比如去掉敏感字段等,可以使用mapper来决定如何转换.
 * @param pageSize    分页的大小.
 * @param pageNum     当前页.
 * @param lastId      条件分页参数, 区别于skip-limit,采用find(_id>lastId).limit分页.
 *                    如果不跳页,像朋友圈,微博这样下拉刷新的分页需求,需要传递上一页的最后一条记录的ObjectId。 如果是null,则返回pageNum那一页.
 * @param <T>         collection定义的class类型.
 * @param <R>         最终返回时,展现给页面时的一条记录的类型。
 * @return PageResult,一个封装page信息的对象.
 */
public <T, R> PageResult<R> pageQuery(Query query, Class<T> entityClass, String className, Function<T, R> mapper,
                                      Integer pageSize, Integer pageNum, String lastId) {

    //设定分页默认值
    if (pageSize == null) {
        pageSize = 20;
    }
    if (pageNum == null) {
        pageNum = 1;
    }

    //分页逻辑
    long total = mongoTemplate.count(query, entityClass, className);
    final Integer pages = (int) Math.ceil(total / (double) pageSize);
    if (pageNum <= 0 || pageNum > pages) {
        pageNum = FIRST_PAGE_NUM;
    }
    final Criteria criteria = new Criteria();
    if (StringUtils.isNotBlank(lastId)) {
        if (pageNum != FIRST_PAGE_NUM) {
            criteria.and(ID).gt(new ObjectId(lastId));
        }
        query.limit(pageSize);
    } else {
        int skip = pageSize * (pageNum - 1);
        query.skip(skip).limit(pageSize);
    }

    final List<T> entityList = mongoTemplate
            .find(query.addCriteria(criteria)
                            .with(new Sort(Lists.newArrayList(new Order(Direction.ASC, ID)))),
                    entityClass, className);

    final PageResult<R> pageResult = new PageResult<>();
    pageResult.setTotal(total);
    pageResult.setPages(pages);
    pageResult.setPageSize(pageSize);
    pageResult.setPageNum(pageNum);
    pageResult.setList(entityList.stream().map(mapper).collect(Collectors.toList()));
    return pageResult;
}