com.datastax.driver.core.querybuilder.Insert Java Examples

The following examples show how to use com.datastax.driver.core.querybuilder.Insert. 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: DDelayedLocatorIO.java    From blueflood with Apache License 2.0 6 votes vote down vote up
public DDelayedLocatorIO() {

        // create a generic select statement for retrieving from metrics_delayed_locator
        Select.Where select = QueryBuilder
                .select()
                .all()
                .from( CassandraModel.CF_METRICS_DELAYED_LOCATOR_NAME )
                .where( eq ( KEY, bindMarker() ));
        getValue = DatastaxIO.getSession().prepare( select );

        // create a generic insert statement for inserting into metrics_delayed_locator
        Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_DELAYED_LOCATOR_NAME)
                .using(ttl(TenantTtlProvider.DELAYED_LOCATOR_TTL))
                .value(KEY, bindMarker())
                .value(COLUMN1, bindMarker())
                .value(VALUE, bindMarker());
        putValue = DatastaxIO.getSession()
                .prepare(insert)
                .setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
    }
 
Example #2
Source File: DLocatorIO.java    From blueflood with Apache License 2.0 6 votes vote down vote up
/**
 * Create all prepared statements use in this class for metrics_locator
 */
private void createPreparedStatements()  {

    // create a generic select statement for retrieving from metrics_locator
    Select.Where select = QueryBuilder
            .select()
            .all()
            .from( CassandraModel.CF_METRICS_LOCATOR_NAME )
            .where( eq ( KEY, bindMarker() ));
    getValue = DatastaxIO.getSession().prepare( select );

    // create a generic insert statement for inserting into metrics_locator
    Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_LOCATOR_NAME)
            .using(ttl(TenantTtlProvider.LOCATOR_TTL))
            .value(KEY, bindMarker())
            .value(COLUMN1, bindMarker())
            .value(VALUE, bindMarker());
    putValue = DatastaxIO.getSession()
            .prepare(insert)
            .setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
}
 
Example #3
Source File: DMetadataIO.java    From blueflood with Apache License 2.0 6 votes vote down vote up
private void createPreparedStatements() {

        Select.Where select = select()
                .all()
                .from( CassandraModel.CF_METRICS_METADATA_NAME )
                .where( eq( KEY, bindMarker() ));

        getValue = DatastaxIO.getSession().prepare( select );

        Insert insert = insertInto( CassandraModel.CF_METRICS_METADATA_NAME )
                .value( KEY, bindMarker() )
                .value( COLUMN1, bindMarker() )
                .value( VALUE, bindMarker() );

        putValue = DatastaxIO.getSession().prepare( insert );
        putValue.setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
    }
 
Example #4
Source File: CassandraBaseEventDao.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
private Optional<Event> save(EventEntity entity, boolean ifNotExists) {
    if (entity.getId() == null) {
        entity.setId(UUIDs.timeBased());
    }
    Insert insert = QueryBuilder.insertInto(getColumnFamilyName())
            .value(ModelConstants.ID_PROPERTY, entity.getId())
            .value(ModelConstants.EVENT_TENANT_ID_PROPERTY, entity.getTenantId())
            .value(ModelConstants.EVENT_ENTITY_TYPE_PROPERTY, entity.getEntityType())
            .value(ModelConstants.EVENT_ENTITY_ID_PROPERTY, entity.getEntityId())
            .value(ModelConstants.EVENT_TYPE_PROPERTY, entity.getEventType())
            .value(ModelConstants.EVENT_UID_PROPERTY, entity.getEventUid())
            .value(ModelConstants.EVENT_BODY_PROPERTY, entity.getBody());
    if (ifNotExists) {
        insert = insert.ifNotExists();
    }
    ResultSet rs = executeWrite(insert);
    if (rs.wasApplied()) {
        return Optional.of(DaoUtil.getData(entity));
    } else {
        return Optional.empty();
    }
}
 
Example #5
Source File: MetricCassandraCollector.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
private void runBatchInsert(List<Insert> insertRequest) {
    try {
        Batch batch;
        if (config.getLoggedBatch()) {
            batch = QueryBuilder.batch(insertRequest
                    .toArray(new RegularStatement[insertRequest.size()]));
        } else {
            batch = QueryBuilder.unloggedBatch(insertRequest
                    .toArray(new RegularStatement[insertRequest.size()]));
        }
        totalCassandraInsertRequest.addAndGet(insertRequest.size());
        ResultSetFuture future = cassandraSession.executeAsync(batch);
        CallBackListener listener = new CallBackListener(future, null);
        future.addListener(listener, pool);
        incrementBatchInsertCounter();
        pendingRequestCounter.incrementAndGet();
    } catch (Throwable ex) {
        LOGGER.error("Error publising metrics in MetricCassandraCollector:" + ex.getMessage());
        cassandraErrorCount.increment();
        registerError(ex);
    } finally {
        insertRequest.clear();
    }
}
 
Example #6
Source File: CassandraTestingUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
public static void insertIntoTableClusteringKeys(CassandraSession session, SchemaTableName table, int rowsCount)
{
    for (int rowNumber = 1; rowNumber <= rowsCount; rowNumber++) {
        Insert insert = QueryBuilder.insertInto(table.getSchemaName(), table.getTableName())
                .value("key", "key_" + rowNumber)
                .value("clust_one", "clust_one")
                .value("clust_two", "clust_two_" + rowNumber)
                .value("clust_three", "clust_three_" + rowNumber);
        session.execute(insert);
    }
    assertEquals(session.execute("SELECT COUNT(*) FROM " + table).all().get(0).getLong(0), rowsCount);
}
 
Example #7
Source File: CqlQueriesIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSavingBook_thenAvailableOnRetrieval_usingQueryBuilder() {
    final UUID uuid = UUIDs.timeBased();
    final Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("id", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software"));
    cassandraTemplate.execute(insert);
    final Select select = QueryBuilder.select().from("book").limit(10);
    final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
    assertEquals(uuid, retrievedBook.getId());
}
 
Example #8
Source File: PutCassandraRecord.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Statement generateInsert(String cassandraTable, RecordSchema schema, Map<String, Object> recordContentMap) {
    Insert insertQuery;
    if (cassandraTable.contains(".")) {
        String[] keyspaceAndTable = cassandraTable.split("\\.");
        insertQuery = QueryBuilder.insertInto(keyspaceAndTable[0], keyspaceAndTable[1]);
    } else {
        insertQuery = QueryBuilder.insertInto(cassandraTable);
    }
    for (String fieldName : schema.getFieldNames()) {
        insertQuery.value(fieldName, recordContentMap.get(fieldName));
    }
    return insertQuery;
}
 
Example #9
Source File: CassandraMetadataWriter.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void write(final GeoWaveMetadata metadata) {
  final Insert insert = operations.getInsert(tableName);
  insert.value(PRIMARY_ID_KEY, ByteBuffer.wrap(metadata.getPrimaryId()));
  if (metadata.getSecondaryId() != null) {
    insert.value(SECONDARY_ID_KEY, ByteBuffer.wrap(metadata.getSecondaryId()));
    insert.value(TIMESTAMP_ID_KEY, QueryBuilder.now());
    if ((metadata.getVisibility() != null) && (metadata.getVisibility().length > 0)) {
      insert.value(VISIBILITY_KEY, ByteBuffer.wrap(metadata.getVisibility()));
    }
  }

  insert.value(VALUE_KEY, ByteBuffer.wrap(metadata.getValue()));
  operations.getSession().execute(insert);
}
 
Example #10
Source File: CassandraTable.java    From ingestion with Apache License 2.0 5 votes vote down vote up
public void save(final List<Event> events) {
  final BatchStatement batch = new BatchStatement();
  for (final Event event : events) {
    final Map<String, Object> parsedEvent = parse(event);
    if (parsedEvent.isEmpty()) {
      log.warn("Event {} could not be mapped. Suggestion: Cassandra is case sensitive, so maybe you can check field names.", event);
      continue;
    }
    if (!hasPrimaryKey(parsedEvent)) {
      break;
    }
    final Insert insert = QueryBuilder.insertInto(table);
    for (final Map.Entry<String, Object> entry : parsedEvent.entrySet()) {
      insert.value(entry.getKey(), entry.getValue());
    }
    if (log.isTraceEnabled()) {
      log.trace("Preparing insert for table {}: {}", table.getName(), insert.getQueryString());
    }
    batch.add(insert);
  }
  if (batch.getStatements().isEmpty()) {
    log.warn("No event produced insert query for table {}", table.getName());
    return;
  }
  batch.setConsistencyLevel(consistencyLevel);
  session.execute(batch);
}
 
Example #11
Source File: SaveToCassandraOperationsServiceTest.java    From Decision with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateInsertStatement() throws Exception {
    Insert insert= service.createInsertStatement(TABLE, columns, "timestamp");
    assertEquals("Expected keyspace not found",
            "\"" + STREAMING.STREAMING_KEYSPACE_NAME + "\"", insert.getKeyspace());

}
 
Example #12
Source File: SaveToCassandraOperationsService.java    From Decision with Apache License 2.0 5 votes vote down vote up
public Insert createInsertStatement(String streamName, List<ColumnNameTypeValue> columns, String timestampColumnName) {
    Insert insert = QueryBuilder.insertInto(addQuotes(STREAMING.STREAMING_KEYSPACE_NAME), addQuotes(streamName));
    for (ColumnNameTypeValue column : columns) {
        insert.value(addQuotes(column.getColumn()), column.getValue());
    }
    insert.value(addQuotes(timestampColumnName), UUIDs.timeBased());
    return insert;
}
 
Example #13
Source File: WordCountAndSourceMapper.java    From storm-cassandra-cql with Apache License 2.0 5 votes vote down vote up
@Override
public Statement map(List<String> keys, Number value) {
    Insert statement = QueryBuilder.insertInto(KEYSPACE_NAME, TABLE_NAME);
    statement.value(WORD_KEY_NAME, keys.get(0));
    statement.value(SOURCE_KEY_NAME, keys.get(1));
    statement.value(VALUE_NAME, value);
    return statement;
}
 
Example #14
Source File: CassandraUtils.java    From deep-spark with Apache License 2.0 5 votes vote down vote up
public static <W> void doCql3SaveToCassandra(RDD<W> rdd, ICassandraDeepJobConfig<W> writeConfig,
                                             Function1<W, Tuple2<Cells, Cells>> transformer) {
    if (!writeConfig.getIsWriteConfig()) {
        throw new IllegalArgumentException("Provided configuration object is not suitable for writing");
    }
    Tuple2<Map<String, ByteBuffer>, Map<String, ByteBuffer>> tuple = new Tuple2<>(null, null);

    RDD<Tuple2<Cells, Cells>> mappedRDD = rdd.map(transformer,
            ClassTag$.MODULE$.<Tuple2<Cells, Cells>>apply(tuple.getClass()));

    ((CassandraDeepJobConfig) writeConfig).createOutputTableIfNeeded(mappedRDD.first());

    final int pageSize = writeConfig.getBatchSize();
    int offset = 0;

    List<Tuple2<Cells, Cells>> elements = Arrays.asList((Tuple2<Cells, Cells>[]) mappedRDD.collect());
    List<Tuple2<Cells, Cells>> split;
    do {
        split = elements.subList(pageSize * (offset++), Math.min(pageSize * offset, elements.size()));

        Batch batch = QueryBuilder.batch();

        for (Tuple2<Cells, Cells> t : split) {
            Tuple2<String[], Object[]> bindVars = Utils.prepareTuple4CqlDriver(t);

            Insert insert = QueryBuilder
                    .insertInto(quote(writeConfig.getKeyspace()), quote(writeConfig.getTable()))
                    .values(bindVars._1(), bindVars._2());

            batch.add(insert);
        }
        writeConfig.getSession().execute(batch);

    } while (!split.isEmpty() && split.size() == pageSize);
}
 
Example #15
Source File: CassandraPageSink.java    From presto with Apache License 2.0 5 votes vote down vote up
public CassandraPageSink(
        CassandraSession cassandraSession,
        ProtocolVersion protocolVersion,
        String schemaName,
        String tableName,
        List<String> columnNames,
        List<Type> columnTypes,
        boolean generateUuid)
{
    this.cassandraSession = requireNonNull(cassandraSession, "cassandraSession");
    requireNonNull(schemaName, "schemaName is null");
    requireNonNull(tableName, "tableName is null");
    requireNonNull(columnNames, "columnNames is null");
    this.columnTypes = ImmutableList.copyOf(requireNonNull(columnTypes, "columnTypes is null"));
    this.generateUuid = generateUuid;

    if (protocolVersion.toInt() <= ProtocolVersion.V3.toInt()) {
        this.toCassandraDate = value -> DATE_FORMATTER.print(TimeUnit.DAYS.toMillis(value));
    }
    else {
        this.toCassandraDate = value -> LocalDate.fromDaysSinceEpoch(toIntExact(value));
    }

    Insert insert = insertInto(validSchemaName(schemaName), validTableName(tableName));
    if (generateUuid) {
        insert.value(ID_COLUMN_NAME, bindMarker());
    }
    for (int i = 0; i < columnNames.size(); i++) {
        String columnName = columnNames.get(i);
        checkArgument(columnName != null, "columnName is null at position: %s", i);
        insert.value(validColumnName(columnName), bindMarker());
    }
    this.insert = cassandraSession.prepare(insert);
}
 
Example #16
Source File: CassandraTestingUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
public static void insertIntoTableMultiPartitionClusteringKeys(CassandraSession session, SchemaTableName table)
{
    for (int rowNumber = 1; rowNumber < 10; rowNumber++) {
        Insert insert = QueryBuilder.insertInto(table.getSchemaName(), table.getTableName())
                .value("partition_one", "partition_one_" + rowNumber)
                .value("partition_two", "partition_two_" + rowNumber)
                .value("clust_one", "clust_one")
                .value("clust_two", "clust_two_" + rowNumber)
                .value("clust_three", "clust_three_" + rowNumber);
        session.execute(insert);
    }
    assertEquals(session.execute("SELECT COUNT(*) FROM " + table).all().get(0).getLong(0), 9);
}
 
Example #17
Source File: CassandraTestingUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
public static void insertIntoTableClusteringKeysInequality(CassandraSession session, SchemaTableName table, Date date, int rowsCount)
{
    for (int rowNumber = 1; rowNumber <= rowsCount; rowNumber++) {
        Insert insert = QueryBuilder.insertInto(table.getSchemaName(), table.getTableName())
                .value("key", "key_1")
                .value("clust_one", "clust_one")
                .value("clust_two", rowNumber)
                .value("clust_three", date.getTime() + rowNumber * 10);
        session.execute(insert);
    }
    assertEquals(session.execute("SELECT COUNT(*) FROM " + table).all().get(0).getLong(0), rowsCount);
}
 
Example #18
Source File: CassandraTestingUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
private static void insertTestData(CassandraSession session, SchemaTableName table, Date date, int rowsCount)
{
    for (int rowNumber = 1; rowNumber <= rowsCount; rowNumber++) {
        Insert insert = QueryBuilder.insertInto(table.getSchemaName(), table.getTableName())
                .value("key", "key " + rowNumber)
                .value("typeuuid", UUID.fromString(format("00000000-0000-0000-0000-%012d", rowNumber)))
                .value("typeinteger", rowNumber)
                .value("typelong", rowNumber + 1000)
                .value("typebytes", ByteBuffer.wrap(Ints.toByteArray(rowNumber)).asReadOnlyBuffer())
                .value("typetimestamp", date)
                .value("typeansi", "ansi " + rowNumber)
                .value("typeboolean", rowNumber % 2 == 0)
                .value("typedecimal", new BigDecimal(Math.pow(2, rowNumber)))
                .value("typedouble", Math.pow(4, rowNumber))
                .value("typefloat", (float) Math.pow(8, rowNumber))
                .value("typeinet", InetAddresses.forString("127.0.0.1"))
                .value("typevarchar", "varchar " + rowNumber)
                .value("typevarint", BigInteger.TEN.pow(rowNumber))
                .value("typetimeuuid", UUID.fromString(format("d2177dd0-eaa2-11de-a572-001b779c76e%d", rowNumber)))
                .value("typelist", ImmutableList.of("list-value-1" + rowNumber, "list-value-2" + rowNumber))
                .value("typemap", ImmutableMap.of(rowNumber, rowNumber + 1L, rowNumber + 2, rowNumber + 3L))
                .value("typeset", ImmutableSet.of(false, true));

        session.execute(insert);
    }
    assertEquals(session.execute("SELECT COUNT(*) FROM " + table).all().get(0).getLong(0), rowsCount);
}
 
Example #19
Source File: InsertStatementHandler.java    From scalardb with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
protected PreparedStatement prepare(Operation operation) {
  checkArgument(operation, Put.class);

  Put put = (Put) operation;
  Insert insert = prepare(put);
  String query = insert.getQueryString();

  return prepare(query);
}
 
Example #20
Source File: InsertStatementHandler.java    From scalardb with Apache License 2.0 5 votes vote down vote up
private Insert prepare(Put put) {
  Insert insert = insertInto(put.forNamespace().get(), put.forTable().get());

  put.getPartitionKey().forEach(v -> insert.value(v.getName(), bindMarker()));
  put.getClusteringKey()
      .ifPresent(
          k -> {
            k.forEach(v -> insert.value(v.getName(), bindMarker()));
          });
  put.getValues().forEach((k, v) -> insert.value(v.getName(), bindMarker()));

  setCondition(insert, put);

  return insert;
}
 
Example #21
Source File: CassandraTable.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
protected Insert buildInsert(CassandraBackendEntry.Row entry) {
    assert entry.columns().size() > 0;
    Insert insert = QueryBuilder.insertInto(this.table());

    for (Map.Entry<HugeKeys, Object> c : entry.columns().entrySet()) {
        insert.value(formatKey(c.getKey()), c.getValue());
    }
    return insert;
}
 
Example #22
Source File: CassandraEventRecorder.java    From eventapis with Apache License 2.0 5 votes vote down vote up
private Insert createInsertQuery(EntityEvent entityEvent) {
    Insert insert = QueryBuilder.insertInto(tableName);
    insert.value(ENTITY_ID, entityEvent.getEventKey().getEntityId());
    insert.value(VERSION, entityEvent.getEventKey().getVersion());
    insert.value(OP_ID, entityEvent.getOpId());
    insert.value(OP_DATE, entityEvent.getOpDate());
    insert.value(EVENT_TYPE, entityEvent.getEventType());
    insert.value(STATUS, entityEvent.getStatus().name());
    insert.value(AUDIT_INFO, entityEvent.getAuditInfo());
    insert.value(EVENT_DATA, entityEvent.getEventData());
    insert.ifNotExists();
    return insert;
}
 
Example #23
Source File: CassandraPerDomainMaxQuotaDao.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Insert setMaxMessageStatement() {
    return insertInto(CassandraDomainMaxQuota.TABLE_NAME)
        .value(CassandraDomainMaxQuota.DOMAIN, bindMarker())
        .value(CassandraDomainMaxQuota.MESSAGE_COUNT, bindMarker());
}
 
Example #24
Source File: ConditionSetter.java    From scalardb with Apache License 2.0 4 votes vote down vote up
/**
 * Adds {@code PutIfNotExists}-specific conditions to the statement
 *
 * @param condition {@code PutIfNotExists} condition
 */
@Override
public void visit(PutIfNotExists condition) {
  Insert insert = (Insert) statement;
  insert.ifNotExists();
}
 
Example #25
Source File: CassandraOperations.java    From geowave with Apache License 2.0 4 votes vote down vote up
public Insert getInsert(final String table) {
  return QueryBuilder.insertInto(gwNamespace, getCassandraSafeName(table));
}
 
Example #26
Source File: CassandraGlobalMaxQuotaDao.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Insert setGlobalMaxStorageStatement() {
    return insertInto(CassandraGlobalMaxQuota.TABLE_NAME)
        .value(CassandraGlobalMaxQuota.TYPE, CassandraGlobalMaxQuota.STORAGE)
        .value(CassandraGlobalMaxQuota.VALUE, bindMarker());
}
 
Example #27
Source File: CassandraPersistWriter.java    From streams with Apache License 2.0 4 votes vote down vote up
private void createInsertStatement() {
  Insert insertBuilder = QueryBuilder.insertInto(config.getTable());
  insertBuilder.value(config.getPartitionKeyColumn(), new Object());
  insertBuilder.value(config.getColumn(), new Object());
  insertStatement = session.prepare(insertBuilder.getQueryString());
}
 
Example #28
Source File: CassandraPerDomainMaxQuotaDao.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Insert setMaxStorageStatement() {
    return insertInto(CassandraDomainMaxQuota.TABLE_NAME)
        .value(CassandraDomainMaxQuota.DOMAIN, bindMarker())
        .value(CassandraDomainMaxQuota.STORAGE, bindMarker());
}
 
Example #29
Source File: CassandraNotificationRegistryDAO.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Insert createInsert() {
    return insertInto(CassandraNotificationTable.TABLE_NAME)
        .value(CassandraNotificationTable.ACCOUNT_ID, bindMarker(CassandraNotificationTable.ACCOUNT_ID))
        .value(CassandraNotificationTable.RECIPIENT_ID, bindMarker(CassandraNotificationTable.RECIPIENT_ID));
}
 
Example #30
Source File: CassandraVacationDAO.java    From james-project with Apache License 2.0 4 votes vote down vote up
private <T> Insert applyPatchForField(String field, Optional<T> value, Insert insert) {
    return insert.value(field, value.orElse(null));
}