com.datastax.driver.core.querybuilder.QueryBuilder Java Examples
The following examples show how to use
com.datastax.driver.core.querybuilder.QueryBuilder.
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: CassandraUtil.java From sunbird-lms-service with MIT License | 6 votes |
/** * Method to create the cassandra update query. * * @param primaryKey map representing the composite primary key. * @param nonPKRecord map contains the fields that has to update. * @param keyspaceName cassandra keyspace name. * @param tableName cassandra table name. * @return RegularStatement. */ public static RegularStatement createUpdateQuery( Map<String, Object> primaryKey, Map<String, Object> nonPKRecord, String keyspaceName, String tableName) { Update update = QueryBuilder.update(keyspaceName, tableName); Assignments assignments = update.with(); Update.Where where = update.where(); nonPKRecord .entrySet() .stream() .forEach( x -> { assignments.and(QueryBuilder.set(x.getKey(), x.getValue())); }); primaryKey .entrySet() .stream() .forEach( x -> { where.and(QueryBuilder.eq(x.getKey(), x.getValue())); }); return where; }
Example #2
Source File: QueueMessageSerializationImpl.java From usergrid with Apache License 2.0 | 6 votes |
private Statement createDeleteAllMessagesStatement( Shard shard ) { Clause queueNameClause = QueryBuilder.eq( COLUMN_QUEUE_NAME, shard.getQueueName() ); Clause regionClause = QueryBuilder.eq( COLUMN_REGION, shard.getRegion() ); Clause shardIdClause = QueryBuilder.eq( COLUMN_SHARD_ID, shard.getShardId() ); DatabaseQueueMessage.Type dbqmType = Shard.Type.DEFAULT.equals( shard.getType() ) ? DatabaseQueueMessage.Type.DEFAULT : DatabaseQueueMessage.Type.INFLIGHT; Statement deleteAll = QueryBuilder.delete().from( getTableName( dbqmType )) .where(queueNameClause) .and(regionClause) .and(shardIdClause); return deleteAll; }
Example #3
Source File: MapSerializationImpl.java From usergrid with Apache License 2.0 | 6 votes |
@Override public void putLong( final MapScope scope, final String key, final Long value ) { Preconditions.checkNotNull( scope, "mapscope is required" ); Preconditions.checkNotNull( key, "key is required" ); Preconditions.checkNotNull( value, "value is required" ); Statement mapEntry = QueryBuilder.insertInto(MAP_ENTRIES_TABLE) .value("key", getMapEntryPartitionKey(scope, key)) .value("column1", DataType.cboolean().serialize(true, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", DataType.bigint().serialize(value, ProtocolVersion.NEWEST_SUPPORTED)); session.execute(mapEntry); final int bucket = BUCKET_LOCATOR.getCurrentBucket( scope.getName() ); Statement mapKey; mapKey = QueryBuilder.insertInto(MAP_KEYS_TABLE) .value("key", getMapKeyPartitionKey(scope, bucket)) .value("column1", DataType.text().serialize(key, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", DataType.cboolean().serialize(true, ProtocolVersion.NEWEST_SUPPORTED)); session.execute(mapKey); }
Example #4
Source File: CassandraCachePrimer.java From newts with Apache License 2.0 | 6 votes |
@Inject public CassandraCachePrimer(CassandraSession session) { m_session = checkNotNull(session); Select select = QueryBuilder.select(Constants.Schema.C_METRICS_CONTEXT, Constants.Schema.C_METRICS_RESOURCE, Constants.Schema.C_METRICS_NAME) .from(Constants.Schema.T_METRICS); m_selectAllMetricsStatement = session.prepare(select.toString()); select = QueryBuilder.select(Constants.Schema.C_ATTRS_CONTEXT, Constants.Schema.C_ATTRS_RESOURCE, Constants.Schema.C_ATTRS_ATTR, Constants.Schema.C_ATTRS_VALUE) .from(Constants.Schema.T_ATTRS); m_selectAllAttributesStatement = session.prepare(select.toString()); }
Example #5
Source File: BaseRelationDao.java From iotplatform with Apache License 2.0 | 6 votes |
@Override public ListenableFuture<List<EntityRelation>> findRelations(EntityId from, String relationType, RelationTypeGroup typeGroup, ThingType childType, TimePageLink pageLink) { Select.Where query = CassandraAbstractSearchTimeDao.buildQuery(ModelConstants.RELATION_BY_TYPE_AND_CHILD_TYPE_VIEW_NAME, Arrays.asList(eq(ModelConstants.RELATION_FROM_ID_PROPERTY, from.getId()), eq(ModelConstants.RELATION_FROM_TYPE_PROPERTY, from.getEntityType().name()), eq(ModelConstants.RELATION_TYPE_GROUP_PROPERTY, typeGroup.name()), eq(ModelConstants.RELATION_TYPE_PROPERTY, relationType), eq(ModelConstants.RELATION_TO_TYPE_PROPERTY, childType.name())), Arrays.asList( pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TYPE_GROUP_PROPERTY) : QueryBuilder.asc(ModelConstants.RELATION_TYPE_GROUP_PROPERTY), pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TYPE_PROPERTY) : QueryBuilder.asc(ModelConstants.RELATION_TYPE_PROPERTY), pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TO_TYPE_PROPERTY) : QueryBuilder.asc(ModelConstants.RELATION_TO_TYPE_PROPERTY) ), pageLink, ModelConstants.RELATION_TO_ID_PROPERTY); return getFuture(executeAsyncRead(query), this::getEntityRelations); }
Example #6
Source File: MetricCassandraCollector.java From realtime-analytics with GNU General Public License v2.0 | 6 votes |
private void runBatchUpdate(List<Update> updateRequest) { try { Batch batch; if (config.getLoggedBatch()) { batch = QueryBuilder.batch(updateRequest .toArray(new RegularStatement[updateRequest.size()])); } else { batch = QueryBuilder.unloggedBatch(updateRequest .toArray(new RegularStatement[updateRequest.size()])); } totalCassandraUpdateRequest.addAndGet(updateRequest.size()); ResultSetFuture future = cassandraSession.executeAsync(batch); CallBackListener listener = new CallBackListener(future, null); future.addListener(listener, pool); incrementBatchUpdateCounter(); pendingRequestCounter.incrementAndGet(); } catch (Throwable ex) { LOGGER.error("Error publising metrics in MetricCassandraCollector:" + ex.getMessage()); cassandraErrorCount.increment(); registerError(ex); } finally { updateRequest.clear(); } }
Example #7
Source File: CassandraDependenciesJob.java From zipkin-dependencies with Apache License 2.0 | 6 votes |
void saveToCassandra(List<DependencyLink> links) { Dependencies thrift = Dependencies.create(day, day /** ignored */, links); ByteBuffer blob = thrift.toThrift(); log.info("Saving with day={}", dateStamp); CassandraConnector.apply(conf).withSessionDo(new AbstractFunction1<Session, Void>() { @Override public Void apply(Session session) { session.execute(QueryBuilder.insertInto(keyspace, "dependencies") .value("day", new Date(day)) .value("dependencies", blob) ); return null; } }); log.info("Done"); }
Example #8
Source File: CassandraSinkIntegrationTests.java From spring-cloud-stream-app-starters with Apache License 2.0 | 6 votes |
@Test public void testInsert() throws InterruptedException { Book book = new Book(); book.setIsbn(UUIDs.timeBased()); book.setTitle("Spring Integration Cassandra"); book.setAuthor("Cassandra Guru"); book.setPages(521); book.setSaleDate(new Date()); book.setInStock(true); this.sink.input().send(new GenericMessage<>(book)); final Select select = QueryBuilder.select().all().from("book"); assertEqualsEventually(1, new Supplier<Integer>() { @Override public Integer get() { return cassandraTemplate.select(select, Book.class).size(); } }); this.cassandraTemplate.delete(book); }
Example #9
Source File: UpdateStatementHandler.java From scalardb with Apache License 2.0 | 6 votes |
private Update prepare(Put put) { Update update = QueryBuilder.update(put.forNamespace().get(), put.forTable().get()); Update.Assignments assignments = update.with(); put.getValues().forEach((k, v) -> assignments.and(set(k, bindMarker()))); Update.Where where = update.where(); put.getPartitionKey().forEach(v -> where.and(QueryBuilder.eq(v.getName(), bindMarker()))); put.getClusteringKey() .ifPresent( k -> { k.forEach(v -> where.and(QueryBuilder.eq(v.getName(), bindMarker()))); }); setCondition(where, put); return update; }
Example #10
Source File: Statements.java From conductor with Apache License 2.0 | 5 votes |
/** * @return cql query statement to delete a workflow def name/version from the "workflow_defs_index" table */ public String getDeleteWorkflowDefIndexStatement() { return QueryBuilder.delete() .from(keyspace, TABLE_WORKFLOW_DEFS_INDEX) .where(eq(WORKFLOW_DEF_INDEX_KEY, bindMarker())) .and(eq(WORKFLOW_DEF_NAME_VERSION_KEY, bindMarker())) .getQueryString(); }
Example #11
Source File: CassandraAggregateCatalogue.java From concursus with MIT License | 5 votes |
@Override public List<String> getAggregateIds(String aggregateType) { Select select = QueryBuilder.select("aggregateId").from("Catalogue"); select.where(QueryBuilder.eq("aggregateType", aggregateType)); select.where(QueryBuilder.in("bucket", IntStream.range(0, bucketCount).mapToObj(Integer::valueOf).collect(Collectors.toList()))); List<String> result = new ArrayList<>(); cassandraTemplate.query(select, (Row row) -> result.add(row.getString(0))); return result; }
Example #12
Source File: Statements.java From conductor with Apache License 2.0 | 5 votes |
/** * @return cql query statement to delete a workflow definition by name and version from the "workflow_definitions" * table */ public String getDeleteWorkflowDefStatement() { return QueryBuilder.delete() .from(keyspace, TABLE_WORKFLOW_DEFS) .where(eq(WORKFLOW_DEF_NAME_KEY, bindMarker())) .and(eq(WORKFLOW_VERSION_KEY, bindMarker())) .getQueryString(); }
Example #13
Source File: CassandraMailboxPathV2DAO.java From james-project with Apache License 2.0 | 5 votes |
private PreparedStatement prepareDelete(Session session) { return session.prepare(QueryBuilder.delete() .from(TABLE_NAME) .where(eq(NAMESPACE, bindMarker(NAMESPACE))) .and(eq(USER, bindMarker(USER))) .and(eq(MAILBOX_NAME, bindMarker(MAILBOX_NAME))) .ifExists()); }
Example #14
Source File: Statements.java From conductor with Apache License 2.0 | 5 votes |
/** * @return cql query statement to retrieve all task definitions from the "task_definitions" table */ public String getSelectAllTaskDefsStatement() { return QueryBuilder.select() .all() .from(keyspace, TABLE_TASK_DEFS) .where(eq(TASK_DEFS_KEY, bindMarker())) .getQueryString(); }
Example #15
Source File: Statements.java From conductor with Apache License 2.0 | 5 votes |
/** * @return cql query statement to fetch a task definition by name from the "task_definitions" table */ public String getSelectTaskDefStatement() { return QueryBuilder.select(TASK_DEFINITION_KEY) .from(keyspace, TABLE_TASK_DEFS) .where(eq(TASK_DEFS_KEY, TASK_DEFS_KEY)) .and(eq(TASK_DEF_NAME_KEY, bindMarker())) .getQueryString(); }
Example #16
Source File: QueueSerializationImpl.java From usergrid with Apache License 2.0 | 5 votes |
@Override public List<String> getListOfQueues() { logger.trace( "getListOfQueues " ); Statement select = QueryBuilder.select().all().from( TABLE_QUEUES ); ResultSet rs = cassandraClient.getApplicationSession().execute( select ); return rs.all().stream() .map( row -> row.getString( COLUMN_QUEUE_NAME )) .collect( Collectors.toList() ); }
Example #17
Source File: Statements.java From conductor with Apache License 2.0 | 5 votes |
/** * @return cql query statement to retrieve all versions of a workflow definition by name from the * "workflow_definitions" table */ public String getSelectAllWorkflowDefVersionsByNameStatement() { return QueryBuilder.select() .all() .from(keyspace, TABLE_WORKFLOW_DEFS) .where(eq(WORKFLOW_DEF_NAME_KEY, bindMarker())) .getQueryString(); }
Example #18
Source File: CassandraAlarmDao.java From iotplatform with Apache License 2.0 | 5 votes |
@Override public ListenableFuture<Alarm> findLatestByOriginatorAndType(TenantId tenantId, EntityId originator, String type) { Select select = select().from(ALARM_COLUMN_FAMILY_NAME); Select.Where query = select.where(); query.and(eq(ALARM_TENANT_ID_PROPERTY, tenantId.getId())); query.and(eq(ALARM_ORIGINATOR_ID_PROPERTY, originator.getId())); query.and(eq(ALARM_ORIGINATOR_TYPE_PROPERTY, originator.getEntityType())); query.and(eq(ALARM_TYPE_PROPERTY, type)); query.limit(1); query.orderBy(QueryBuilder.asc(ModelConstants.ALARM_TYPE_PROPERTY), QueryBuilder.desc(ModelConstants.ID_PROPERTY)); return findOneByStatementAsync(query); }
Example #19
Source File: AdaptiveResultSetTest.java From emodb with Apache License 2.0 | 5 votes |
@Test(dataProvider = "async") public void testInitialPageExceedsMaxFetchSize(boolean async) throws Exception { if (!_runTests) { throw new SkipException("Skipping test"); } // Query for all data starting with the second row, "b", since the first row can be read in a single frame // with fetch size 256. Statement statement = QueryBuilder.select("rowid", "col", "data") .from(_keyspaceName, _tableName) .where(QueryBuilder.gte(QueryBuilder.token("rowid"), "b")) .setFetchSize(256); // Run once without using adaptive queries to verify the maximum frame size is exceeded try { _session.execute(statement); fail("FrameTooLongException not thrown"); } catch (FrameTooLongException e) { // Ok, this is the expected exception } ResultSet rs; if (async) { rs = AdaptiveResultSet.executeAdaptiveQueryAsync(_session, statement, 256).get(); } else { rs = AdaptiveResultSet.executeAdaptiveQuery(_session, statement, 256); } verifyResults(rs, 'b', 'k'); }
Example #20
Source File: CassandraAttachmentMessageIdDAO.java From james-project with Apache License 2.0 | 5 votes |
private PreparedStatement prepareDelete(Session session) { return session.prepare( QueryBuilder.delete() .from(TABLE_NAME) .where(eq(ATTACHMENT_ID_AS_UUID, bindMarker(ATTACHMENT_ID_AS_UUID))) .and(eq(MESSAGE_ID, bindMarker(MESSAGE_ID)))); }
Example #21
Source File: CassandraTableTest.java From james-project with Apache License 2.0 | 5 votes |
@Test void shouldRespectBeanContract() { EqualsVerifier.forClass(CassandraTable.class) .withPrefabValues( Statement.class, QueryBuilder.select("foo").from("foo"), QueryBuilder.select("bar").from("bar")) .verify(); }
Example #22
Source File: Statements.java From conductor with Apache License 2.0 | 5 votes |
/** * @return cql query statement to retrieve the total_tasks and total_partitions for a workflow from the "workflows" * table */ public String getSelectTotalStatement() { return QueryBuilder.select(TOTAL_TASKS_KEY, TOTAL_PARTITIONS_KEY) .from(keyspace, TABLE_WORKFLOWS) .where(eq(WORKFLOW_ID_KEY, bindMarker())) .and(eq(SHARD_ID_KEY, 1)) .getQueryString(); }
Example #23
Source File: CassandraDACImpl.java From sunbird-lms-service with MIT License | 5 votes |
public Response getRecords( String keySpace, String table, Map<String, Object> filters, List<String> fields) { Response response = new Response(); Session session = connectionManager.getSession(keySpace); try { Select select; if (CollectionUtils.isNotEmpty(fields)) { select = QueryBuilder.select((String[]) fields.toArray()).from(keySpace, table); } else { select = QueryBuilder.select().all().from(keySpace, table); } if (MapUtils.isNotEmpty(filters)) { Select.Where where = select.where(); for (Map.Entry<String, Object> filter : filters.entrySet()) { Object value = filter.getValue(); if (value instanceof List) { where = where.and(QueryBuilder.in(filter.getKey(), ((List) filter.getValue()))); } else { where = where.and(QueryBuilder.eq(filter.getKey(), filter.getValue())); } } } ResultSet results = null; results = session.execute(select); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + table + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } return response; }
Example #24
Source File: BaseCassandraViewQuery.java From eventapis with Apache License 2.0 | 5 votes |
@Override public EntityEvent queryEvent(String entityId, int version) throws EventStoreException { Select select = QueryBuilder.select().from(tableName); select.where(QueryBuilder.eq(CassandraEventRecorder.ENTITY_ID, entityId)); select.where(QueryBuilder.eq(CassandraEventRecorder.VERSION, version)); Row one = cassandraSession.execute(select, PagingIterable::one); return one == null ? null : convertToEntityEvent(one); }
Example #25
Source File: CassandraMailboxRecentsDAO.java From james-project with Apache License 2.0 | 5 votes |
private PreparedStatement createDeleteStatement(Session session) { return session.prepare( QueryBuilder.delete() .from(CassandraMailboxRecentsTable.TABLE_NAME) .where(eq(CassandraMailboxRecentsTable.MAILBOX_ID, bindMarker(CassandraMailboxRecentsTable.MAILBOX_ID))) .and(eq(CassandraMailboxRecentsTable.RECENT_MESSAGE_UID, bindMarker(CassandraMailboxRecentsTable.RECENT_MESSAGE_UID)))); }
Example #26
Source File: CassandraOperations.java From geowave with Apache License 2.0 | 5 votes |
public boolean deleteRow( final String tableName, final GeoWaveRow row, final String... additionalAuthorizations) { boolean exhausted = true; for (int i = 0; i < row.getFieldValues().length; i++) { final ResultSet rs = session.execute( QueryBuilder.delete().from(gwNamespace, getCassandraSafeName(tableName)).where( QueryBuilder.eq( CassandraField.GW_PARTITION_ID_KEY.getFieldName(), ByteBuffer.wrap( CassandraUtils.getCassandraSafePartitionKey(row.getPartitionKey())))).and( QueryBuilder.eq( CassandraField.GW_SORT_KEY.getFieldName(), ByteBuffer.wrap(row.getSortKey()))).and( QueryBuilder.eq( CassandraField.GW_ADAPTER_ID_KEY.getFieldName(), row.getAdapterId())).and( QueryBuilder.eq( CassandraField.GW_DATA_ID_KEY.getFieldName(), ByteBuffer.wrap(row.getDataId()))).and( QueryBuilder.eq( CassandraField.GW_FIELD_VISIBILITY_KEY.getFieldName(), ByteBuffer.wrap( row.getFieldValues()[i].getVisibility())))); exhausted &= rs.isExhausted(); } return !exhausted; }
Example #27
Source File: CassandraIndexer.java From newts with Apache License 2.0 | 5 votes |
private void definitelyUnindexResource(List<RegularStatement> statement, Context context, Resource resource, ConsistencyLevel writeConsistencyLevel) { for (String s : m_resourceIdSplitter.splitIdIntoElements(resource.getId())) { RegularStatement delete = QueryBuilder.delete() .from(Constants.Schema.T_TERMS) .where(QueryBuilder.eq(Constants.Schema.C_TERMS_CONTEXT, context.getId())) .and(QueryBuilder.eq(Constants.Schema.C_TERMS_FIELD, Constants.DEFAULT_TERM_FIELD)) .and(QueryBuilder.eq(Constants.Schema.C_TERMS_VALUE, s)) .and(QueryBuilder.eq(Constants.Schema.C_TERMS_RESOURCE, resource.getId())); delete.setConsistencyLevel(writeConsistencyLevel); statement.add(delete); } if (m_options.isHierarchicalIndexingEnabled()) { recursivelyUnindexResourceElements(statement, context, resource.getId(), writeConsistencyLevel); } }
Example #28
Source File: QueueMessageSerializationImpl.java From usergrid with Apache License 2.0 | 5 votes |
private Statement createDeleteMessageStatement( final String queueName, final String region, final Long shardIdOrNull, final DatabaseQueueMessage.Type type, final UUID queueMessageId ) { final long shardId; if ( shardIdOrNull == null ) { Shard.Type shardType = DatabaseQueueMessage.Type.DEFAULT.equals( type ) ? Shard.Type.DEFAULT : Shard.Type.INFLIGHT; Shard shard = shardStrategy.selectShard( queueName, region, shardType, queueMessageId ); shardId = shard.getShardId(); } else { shardId = shardIdOrNull; } Clause queueNameClause = QueryBuilder.eq( COLUMN_QUEUE_NAME, queueName ); Clause regionClause = QueryBuilder.eq( COLUMN_REGION, region ); Clause shardIdClause = QueryBuilder.eq( COLUMN_SHARD_ID, shardId ); Clause queueMessageIdClause = QueryBuilder.eq( COLUMN_QUEUE_MESSAGE_ID, queueMessageId); Statement delete = QueryBuilder.delete().from(getTableName( type )) .where(queueNameClause) .and(regionClause) .and(shardIdClause) .and(queueMessageIdClause); return delete; }
Example #29
Source File: CassandraCqlUtils.java From presto with Apache License 2.0 | 5 votes |
public static Selection select(List<CassandraColumnHandle> columns) { Selection selection = QueryBuilder.select(); for (CassandraColumnHandle column : columns) { selection.column(validColumnName(column.getName())); } return selection; }
Example #30
Source File: CassandraTableManager.java From james-project with Apache License 2.0 | 5 votes |
private Mono<Void> truncate(CassandraAsyncExecutor executor, String name) { return executor.execute( QueryBuilder.select() .from(name) .limit(1) .setFetchSize(1)) .filter(resultSet -> !resultSet.isExhausted()) .flatMap(ignored -> executor.executeVoid(QueryBuilder.truncate(name))); }