Java Code Examples for com.datastax.driver.core.querybuilder.Update

The following are top voted examples for showing how to use com.datastax.driver.core.querybuilder.Update. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Camel   File: CassandraComponentProducerTest.java   View source code 7 votes vote down vote up
/**
 * Test with incoming message containing a header with RegularStatement.
 */
@Test
public void testRequestMessageStatement() throws Exception {
    Update.Where update = update("camel_user")
            .with(set("first_name", bindMarker()))
            .and(set("last_name", bindMarker()))
            .where(eq("login", bindMarker()));
    Object response = producerTemplate.requestBodyAndHeader(new Object[]{"Claus 2", "Ibsen 2", "c_ibsen"},
            CassandraConstants.CQL_QUERY, update);

    Cluster cluster = CassandraUnitUtils.cassandraCluster();
    Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
    ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
    Row row = resultSet.one();
    assertNotNull(row);
    assertEquals("Claus 2", row.getString("first_name"));
    assertEquals("Ibsen 2", row.getString("last_name"));
    session.close();
    cluster.close();
}
 
Example 2
Project: Camel   File: CassandraComponentProducerUnpreparedTest.java   View source code 6 votes vote down vote up
/**
 * Test with incoming message containing a header with RegularStatement.
 */
@Test
public void testRequestMessageStatement() throws Exception {
    Update.Where update = update("camel_user")
            .with(set("first_name", "Claus 2"))
            .and(set("last_name", "Ibsen 2"))
            .where(eq("login", "c_ibsen"));
    Object response = producerTemplate.requestBodyAndHeader(null,
            CassandraConstants.CQL_QUERY, update);

    Cluster cluster = CassandraUnitUtils.cassandraCluster();
    Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
    ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
    Row row = resultSet.one();
    assertNotNull(row);
    assertEquals("Claus 2", row.getString("first_name"));
    assertEquals("Ibsen 2", row.getString("last_name"));
    session.close();
    cluster.close();
}
 
Example 3
Project: storm-cassandra-cql   File: ConditionalUpdateTest.java   View source code 6 votes vote down vote up
@Test
public void testConditionalUpdates() throws Exception {
    Update initialStatement = update(KEYSPACE_NAME, TABLE_NAME);
    initialStatement.with(set(VALUE_NAME, 10)).where(eq(KEY_NAME, "DE"));
    this.executeAndAssert(initialStatement, "DE", 10);

    // Now let's conditionally update where it is true
    Update updateStatement = update(KEYSPACE_NAME, TABLE_NAME);
    updateStatement.with(set(VALUE_NAME, 15)).where(eq(KEY_NAME, "DE")).onlyIf(eq(VALUE_NAME, 10));
    this.executeAndAssert(updateStatement, "DE", 15);

    // Now let's conditionally update where it is false
    Update conditionalStatement = update(KEYSPACE_NAME, TABLE_NAME);
    conditionalStatement.with(set(VALUE_NAME, 20)).where(eq(KEY_NAME, "DE")).onlyIf(eq(VALUE_NAME, 10));
    this.executeAndAssert(conditionalStatement, "DE", 15);
}
 
Example 4
Project: realtime-analytics   File: MetricCassandraCollector.java   View source code 6 votes vote down vote up
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 5
Project: kaa   File: CredentialsCassandraDao.java   View source code 6 votes vote down vote up
@Override
public Optional<CassandraCredentials> updateStatus(String applicationId,
                                                   String credentialsId,
                                                   CredentialsStatus status) {
  LOG.debug("Updating credentials status with applicationID[{}] "
          + "and credentialsID[{}] to STATUS[{}]",
      applicationId, credentialsId, status.toString());
  Update.Assignments query = update(getColumnFamilyName())
      .where(eq(CREDENTIALS_ID_PROPERTY, credentialsId))
      .and(eq(CREDENTIALS_APPLICATION_ID_PROPERTY, applicationId))
      .with(set(CREDENTIALS_STATUS_PROPERTY, status.toString()));
  execute(query);
  return find(applicationId, credentialsId);
}
 
Example 6
Project: gora   File: CassandraQueryFactory.java   View source code 6 votes vote down vote up
/**
 * This method returns the CQL Query for UpdateByQuery method
 * refer : http://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlUpdate.html
 *
 * @param mapping        Cassandra mapping {@link CassandraMapping}
 * @param cassandraQuery Cassandra Query {@link CassandraQuery}
 * @param objects        field Objects list
 * @return CQL Query
 */
static String getUpdateByQueryForAvro(CassandraMapping mapping, Query cassandraQuery, List<Object> objects, Schema schema) {
  Update update = QueryBuilder.update(mapping.getKeySpace().getName(), mapping.getCoreName());
  Update.Assignments updateAssignments = null;
  if (cassandraQuery instanceof CassandraQuery) {
    String[] columnNames = getColumnNames(mapping, Arrays.asList(cassandraQuery.getFields()));
      for (String column : columnNames) {
        updateAssignments = update.with(QueryBuilder.set(column, "?"));
        Field field = mapping.getFieldFromColumnName(column);
        Object value = ((CassandraQuery) cassandraQuery).getUpdateFieldValue(field.getFieldName());
        try {
          Schema schemaField = schema.getField(field.getFieldName()).schema();
          objects.add(AvroCassandraUtils.getFieldValueFromAvroBean(schemaField, schemaField.getType(), value, field));
        } catch (NullPointerException e) {
          throw new RuntimeException(field + " field couldn't find in the class " + mapping.getPersistentClass() + ".");
        }
      }
  } else {
    throw new RuntimeException("Please use Cassandra Query object to invoke, UpdateByQuery method.");
  }
  return processQuery(cassandraQuery, updateAssignments, mapping, objects);
}
 
Example 7
Project: gcplot   File: CassandraGCAnalyseRepository.java   View source code 5 votes vote down vote up
private RegularStatement updateAnalyse(Identifier accountId, String analyseId, String name, String timezone,
                                       String ext) {
    Preconditions.checkNotNull(name, "Analyse name can't be null.");
    UUID uuid = UUID.fromString(analyseId);
    Update.Assignments query = updateTable(accountId, uuid).with(set("analyse_name", name));
    if (!Strings.isNullOrEmpty(timezone)) {
        query = query.and(set("timezone", timezone));
    }
    if (ext != null) {
        query = query.and(set("ext", ext));
    }
    return query;
}
 
Example 8
Project: gcplot   File: CassandraGCAnalyseRepository.java   View source code 5 votes vote down vote up
private RegularStatement updateCornerEvents(Identifier accId, String analyseId, String jvmId,
                                           DateTime firstEvent, DateTime lastEvent) {
    RegularStatement ule = updateTable(accId, analyseId)
            .with(put("last_event", jvmId, lastEvent.toDateTime(DateTimeZone.UTC).getMillis()));
    if (firstEvent != null) {
        Update.Where firstEventQuery = updateTable(accId, analyseId);
        firstEventQuery
                .with(put("first_event", jvmId, firstEvent.toDateTime(DateTimeZone.UTC).getMillis()));
        firstEventQuery.onlyIf(eq("first_event['" + jvmId + "']", null));
        connector.session().execute(firstEventQuery);
    }
    return ule;
}
 
Example 9
Project: Camel   File: CassandraComponentProducerTest.java   View source code 5 votes vote down vote up
/**
 * Simulate different CQL statements in the incoming message containing a header with RegularStatement, justifying the cassandracql endpoint not containing a "cql" Uri parameter
 */
@Test
public void testEndpointNoCqlParameter() throws Exception {
    Update.Where updateFirstName = update("camel_user")
            .with(set("first_name", bindMarker()))
            .where(eq("login", bindMarker()));
    @SuppressWarnings("unused")
    Object response1 = producerTemplateNoEndpointCql.requestBodyAndHeader(new Object[]{"Claus 2", "c_ibsen"},
            CassandraConstants.CQL_QUERY, updateFirstName);

    Cluster cluster = CassandraUnitUtils.cassandraCluster();
    Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
    ResultSet resultSet1 = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
    Row row1 = resultSet1.one();
    assertNotNull(row1);
    assertEquals("Claus 2", row1.getString("first_name"));
    assertEquals("Ibsen", row1.getString("last_name"));

    Update.Where updateLastName = update("camel_user")
            .with(set("last_name", bindMarker()))
            .where(eq("login", bindMarker()));
    @SuppressWarnings("unused")
    Object response2 = producerTemplateNoEndpointCql.requestBodyAndHeader(new Object[]{"Ibsen 2", "c_ibsen"},
            CassandraConstants.CQL_QUERY, updateLastName);

    ResultSet resultSet2 = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
    Row row2 = resultSet2.one();
    assertNotNull(row2);
    assertEquals("Claus 2", row2.getString("first_name"));
    assertEquals("Ibsen 2", row2.getString("last_name"));

    session.close();
    cluster.close();
}
 
Example 10
Project: agon   File: CassandraPlayerRepository.java   View source code 5 votes vote down vote up
@Override
public void incrementEvent(long playerId, String event, long count) {
    Update updateStatement = QueryBuilder.update("player_event_counts");
    updateStatement.where(QueryBuilder.eq("player_id", playerId)).and(QueryBuilder.eq("event", event));
    updateStatement.with(QueryBuilder.incr("counter_value", count));
    session.execute(updateStatement);
}
 
Example 11
Project: kaa   File: EndpointUserCassandraDao.java   View source code 5 votes vote down vote up
@Override
public String generateAccessToken(String externalId, String tenantId) {
  LOG.debug("Generating access token for endpoint user with external id {} and tenant id {}",
      externalId, tenantId);
  String accessToken = UUID.randomUUID().toString();
  Update.Where query = update(getColumnFamilyName())
      .with(set(CassandraModelConstants.EP_USER_ACCESS_TOKEN_PROPERTY, accessToken))
      .where(eq(EP_USER_EXTERNAL_ID_PROPERTY, externalId))
      .and(eq(EP_USER_TENANT_ID_PROPERTY, tenantId));
  execute(query);
  LOG.trace("Generated access token {} for endpoint user by query {}", accessToken, query);
  return accessToken;
}
 
Example 12
Project: gora   File: CassandraQueryFactory.java   View source code 5 votes vote down vote up
/**
 * This method returns the CQL Query for UpdateByQuery method
 * refer : http://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlUpdate.html
 *
 * @param mapping        Cassandra mapping {@link CassandraMapping}
 * @param cassandraQuery Cassandra Query {@link CassandraQuery}
 * @param objects        field Objects list
 * @return CQL Query
 */
static String getUpdateByQueryForNative(CassandraMapping mapping, Query cassandraQuery, List<Object> objects) {
  Update update = QueryBuilder.update(mapping.getKeySpace().getName(), mapping.getCoreName());
  Update.Assignments updateAssignments = null;
  if (cassandraQuery instanceof CassandraQuery) {
    String[] columnNames = getColumnNames(mapping, Arrays.asList(cassandraQuery.getFields()));
      for (String column : columnNames) {
        updateAssignments = update.with(QueryBuilder.set(column, "?"));
        objects.add(((CassandraQuery) cassandraQuery).getUpdateFieldValue(mapping.getFieldFromColumnName(column).getFieldName()));
      }
  } else {
    throw new RuntimeException("Please use Cassandra Query object to invoke, UpdateByQuery method.");
  }
  return processQuery(cassandraQuery, updateAssignments, mapping, objects);
}
 
Example 13
Project: lucidity   File: CassandraEntityStore.java   View source code 5 votes vote down vote up
private Collection<RegularStatement> diffMap(String table, String column, Clause whereClause, Map<?, ?> past,
        Map<?, ?> present) {

    List<RegularStatement> queries = Lists.newArrayList();

    Set<?> removed = Sets.newHashSet(past.keySet());
    removed.removeAll(present.keySet());

    if (!removed.isEmpty()) {
        Delete.Selection delete = QueryBuilder.delete();

        for (Object o : removed) {
            delete.mapElt(column, o);
        }

        queries.add(delete.from(table).where(whereClause));
    }

    Set<Entry<?, ?>> changed = Sets.<Entry<?, ?>> newHashSet(present.entrySet());
    changed.removeAll(past.entrySet());

    if (!changed.isEmpty()) {
        Update update = QueryBuilder.update(table);

        for (Entry<?, ?> entry : changed) {
            update.with(QueryBuilder.put(column, entry.getKey(), entry.getValue()));
        }

        queries.add(update.where(whereClause));
    }

    return queries;
}
 
Example 14
Project: gcplot   File: CassandraGCAnalyseRepository.java   View source code 4 votes vote down vote up
private Update.Where updateTable(Identifier accId, String uuid) {
    return updateTable(accId, UUID.fromString(uuid));
}
 
Example 15
Project: gcplot   File: CassandraGCAnalyseRepository.java   View source code 4 votes vote down vote up
private Update.Where updateTable(Identifier accId, UUID uuid) {
    return QueryBuilder.update(TABLE_NAME).where(eq("id", uuid)).and(eq("account_id", accId.toString()));
}
 
Example 16
Project: storm-cassandra-cql   File: SimpleUpdateMapper.java   View source code 4 votes vote down vote up
public Statement map(TridentTuple tuple) {
    long t = System.currentTimeMillis() % 10;
    Update statement = update("mykeyspace", "mytable");
    statement.with(set("col1", tuple.getString(0))).where(eq("t", t));
    return statement;
}