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

The following examples show how to use com.datastax.driver.core.querybuilder.Update. 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: UpdateStatementHandler.java    From scalardb with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: ConditionalUpdateTest.java    From storm-cassandra-cql with Apache License 2.0 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 #3
Source File: CassandraEventRecorder.java    From eventapis with Apache License 2.0 6 votes vote down vote up
@Override
public String updateEvent(EventKey eventKey, @Nullable RecordedEvent newEventData, @Nullable EventState newEventState, @Nullable String newEventType) throws EventStoreException {
    Update update = QueryBuilder.update(tableName);
    update.where(QueryBuilder.eq(ENTITY_ID, eventKey.getEntityId()))
            .and(QueryBuilder.eq(VERSION, eventKey.getVersion()))
            .ifExists();
    if (newEventData != null)
        update.with(QueryBuilder.set(EVENT_DATA, createEventStr(newEventData)));
    if (newEventState != null)
        update.with(QueryBuilder.set(STATUS, newEventState.name()));
    if (newEventType != null)
        update.with(QueryBuilder.set(EVENT_TYPE, newEventType));
    try {
        ResultSet execute = cassandraSession.execute(update);
        log.debug("Update Event, Result:" + execute.toString() + " Update: " + update.toString());
        return execute.toString();
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
        throw new EventStoreException(e.getMessage(), e);
    }
}
 
Example #4
Source File: CassandraUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * 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 #5
Source File: MetricCassandraCollector.java    From realtime-analytics with GNU General Public License v2.0 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 #6
Source File: HubDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void updateAttributes(String hubId, Map<String, Object> attrs) {
   Preconditions.checkNotNull(hubId, "device cannot be null");

   Map<String, Object> filtered = filter.filter(attrs);
   Map<String, String> attributesAsStrings = new HashMap<>();
   Update update = QueryBuilder.update(TABLE);
   update.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
   update.where(eq(BaseEntityColumns.ID, hubId));

   filtered.forEach((k,v) -> {
      if(v == null) {
         update.with(put(ATTRIBUTES_COLUMN, k, null));
      } else {
         attributesAsStrings.put(k, JSON.toJson(v));
      }
   });

   update.with(putAll(ATTRIBUTES_COLUMN, attributesAsStrings));
   final Context ctxt = updateAttributesTimer.time();
   Futures.addCallback(session.executeAsync(update), new FutureCallback<ResultSet>() {
      @Override
      public void onSuccess(ResultSet result) {
         ctxt.stop();
         if(!result.wasApplied()) {
            hubUpdateAttributesFailure.inc();
         }
      }
      @Override
      public void onFailure(Throwable t) {
         ctxt.stop();
         hubUpdateAttributesFailure.inc();
      }
   }, MoreExecutors.directExecutor());
}
 
Example #7
Source File: UpdateStatementHandler.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;
  Update update = prepare(put);
  String query = update.getQueryString();

  return prepare(query);
}
 
Example #8
Source File: ConditionSetter.java    From scalardb with Apache License 2.0 5 votes vote down vote up
/**
 * Adds {@code PutIf}-specific conditions to the statement
 *
 * @param condition {@code PutIf} condition
 */
@Override
public void visit(PutIf condition) {
  Update.Where update = (Update.Where) statement;

  List<ConditionalExpression> expressions = condition.getExpressions();
  Update.Conditions cond = update.onlyIf(createClauseWith(expressions.get(0)));
  IntStream.range(1, expressions.size())
      .forEach(
          i -> {
            cond.and(createClauseWith(expressions.get(i)));
          });
}
 
Example #9
Source File: CassandraTable.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
protected Update buildAppend(CassandraBackendEntry.Row entry) {
    List<HugeKeys> idNames = this.idColumnName();
    List<HugeKeys> colNames = this.modifiableColumnName();

    Map<HugeKeys, Object> columns = entry.columns();

    Update update = QueryBuilder.update(table());

    for (HugeKeys key : colNames) {
        if (!columns.containsKey(key)) {
            continue;
        }

        String name = formatKey(key);
        Object value = columns.get(key);

        if (value instanceof Map) {
            update.with(QueryBuilder.putAll(name, (Map<?, ?>) value));
        } else if (value instanceof List) {
            update.with(QueryBuilder.appendAll(name, (List<?>) value));
        } else {
            update.with(QueryBuilder.append(name, value));
        }
    }

    for (HugeKeys idName : idNames) {
        assert columns.containsKey(idName);
        update.where(formatEQ(idName, columns.get(idName)));
    }
    return update;
}
 
Example #10
Source File: CassandraTables.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
public void increaseCounter(CassandraSessionPool.Session session,
                            HugeType type, long increment) {
    Update update = QueryBuilder.update(TABLE);
    update.with(QueryBuilder.incr(formatKey(HugeKeys.ID), increment));
    update.where(formatEQ(HugeKeys.SCHEMA_TYPE, type.name()));
    session.execute(update);
}
 
Example #11
Source File: PutCassandraRecord.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected Statement generateUpdate(String cassandraTable, RecordSchema schema, String updateKeys, String updateMethod, Map<String, Object> recordContentMap) {
    Update updateQuery;

    // Split up the update key names separated by a comma, should not be empty
    final Set<String> updateKeyNames;
    updateKeyNames = Arrays.stream(updateKeys.split(","))
            .map(String::trim)
            .filter(StringUtils::isNotEmpty)
            .collect(Collectors.toSet());
    if (updateKeyNames.isEmpty()) {
        throw new IllegalArgumentException("No Update Keys were specified");
    }

    // Verify if all update keys are present in the record
    for (String updateKey : updateKeyNames) {
        if (!schema.getFieldNames().contains(updateKey)) {
            throw new IllegalArgumentException("Update key '" + updateKey + "' is not present in the record schema");
        }
    }

    // Prepare keyspace/table names
    if (cassandraTable.contains(".")) {
        String[] keyspaceAndTable = cassandraTable.split("\\.");
        updateQuery = QueryBuilder.update(keyspaceAndTable[0], keyspaceAndTable[1]);
    } else {
        updateQuery = QueryBuilder.update(cassandraTable);
    }

    // Loop through the field names, setting those that are not in the update key set, and using those
    // in the update key set as conditions.
    for (String fieldName : schema.getFieldNames()) {
        Object fieldValue = recordContentMap.get(fieldName);

        if (updateKeyNames.contains(fieldName)) {
            updateQuery.where(QueryBuilder.eq(fieldName, fieldValue));
        } else {
            Assignment assignment;
            if (SET_TYPE.getValue().equalsIgnoreCase(updateMethod)) {
                assignment = QueryBuilder.set(fieldName, fieldValue);
            } else if (INCR_TYPE.getValue().equalsIgnoreCase(updateMethod)) {
                assignment = QueryBuilder.incr(fieldName, convertFieldObjectToLong(fieldName, fieldValue));
            } else if (DECR_TYPE.getValue().equalsIgnoreCase(updateMethod)) {
                assignment = QueryBuilder.decr(fieldName, convertFieldObjectToLong(fieldName, fieldValue));
            } else {
                throw new IllegalArgumentException("Update Method '" + updateMethod + "' is not valid.");
            }
            updateQuery.with(assignment);
        }
    }
    return updateQuery;
}
 
Example #12
Source File: DeviceDAOImpl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private void executeStateUpdate(Device device, DeviceDriverStateHolder state, boolean replace) {
   Preconditions.checkNotNull(device, "device cannot be null");
   Preconditions.checkNotNull(device.getId(), "device must have an id");

   Map<String,String> attributesAsStrings = new HashMap<>();
   Update update = QueryBuilder.update(TABLE);
   update.where(eq(BaseEntityColumns.ID, device.getId()));

   // allow entries defined in ATTR_TO_COLUMN_MAP to be
   // edited here, however this call is mainly intended for
   // drivers, so any updates to other columns which are not
   // allowed fail fast
   List<Object> values = new ArrayList<>();
   if(state.getAttributes() != null) {
      state.getAttributes().entries().forEach((value) -> {
         AttributeKey<?> attributeKey = value.getKey();
         if(isStrictColumn(attributeKey)) {
            String columnName = ATTR_TO_COLUMN_MAP.get(attributeKey.getName());
            if(columnName == null) {
               throw new IllegalArgumentException("Attempted to modify core property '" + value.getKey() + "' via update or replace attributes.  This property may not be updated from a driver.");
            }
            Object val = value.getValue();
            if(columnName.equals(BaseEntityColumns.IMAGES)) {
               val = convertImageMap((Map<String,String>) val);
            }

            update.with(set(columnName, val));
         }
         else {
            if(value.getValue() == null) {
               if(!replace) {
                  update.with(set(NonEntityColumns.ATTRIBUTES + "[?]", null));
                  values.add(attributeKey.getName());
               }
            }
            else {
               attributesAsStrings.put(attributeKey.getName(), serialize(attributeKey, value.getValue()));
            }
         }
      });
   }

   if(state.getVariables().size() > 0) {
      HashMap<String,Object> vars = new HashMap<String,Object>(state.getVariables());
      ByteBuffer buffer = ByteBuffer.wrap(SerializationUtils.serialize(vars));
      update.with(set(NonEntityColumns.VARIABLES, buffer));
   }

   if(replace) {
      update.with(set(NonEntityColumns.ATTRIBUTES, attributesAsStrings));
   } else {
      update.with(putAll(NonEntityColumns.ATTRIBUTES, attributesAsStrings));
   }

   session.execute(update.toString(), values.toArray());
}
 
Example #13
Source File: SimpleUpdateMapper.java    From storm-cassandra-cql with Apache License 2.0 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;
}
 
Example #14
Source File: CassandraApplicableFlagDAO.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Update.Where updateQuery(CassandraId cassandraId, Set<String> userFlags) {
    return addUserFlagsToQuery(userFlags,
            update(TABLE_NAME).with())
        .where(eq(MAILBOX_ID, cassandraId.asUuid()));
}
 
Example #15
Source File: CassandraDACImpl.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
public Response updateMapRecord(
    String keySpace,
    String table,
    Map<String, Object> primaryKey,
    String column,
    String key,
    Object value,
    boolean add) {
  Update update = QueryBuilder.update(keySpace, table);
  if (add) {
    update.with(QueryBuilder.put(column, key, value));
  } else {
    update.with(QueryBuilder.remove(column, key));
  }
  if (MapUtils.isEmpty(primaryKey)) {
    ProjectLogger.log(
        Constants.EXCEPTION_MSG_FETCH + table + " : primary key is a must for update call",
        LoggerEnum.ERROR.name());
    throw new ProjectCommonException(
        ResponseCode.SERVER_ERROR.getErrorCode(),
        ResponseCode.SERVER_ERROR.getErrorMessage(),
        ResponseCode.SERVER_ERROR.getResponseCode());
  }
  Update.Where where = update.where();
  for (Map.Entry<String, Object> filter : primaryKey.entrySet()) {
    Object filterValue = filter.getValue();
    if (filterValue instanceof List) {
      where = where.and(QueryBuilder.in(filter.getKey(), ((List) filter.getValue())));
    } else {
      where = where.and(QueryBuilder.eq(filter.getKey(), filter.getValue()));
    }
  }
  try {
    Response response = new Response();
    ProjectLogger.log("Remove Map-Key Query: " + update.toString(), LoggerEnum.INFO);
    connectionManager.getSession(keySpace).execute(update);
    response.put(Constants.RESPONSE, Constants.SUCCESS);
    return response;
  } catch (Exception e) {
    e.printStackTrace();
    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());
  }
}
 
Example #16
Source File: CassandraTables.java    From hugegraph with Apache License 2.0 4 votes vote down vote up
@Override
public void append(CassandraSessionPool.Session session,
                   CassandraBackendEntry.Row entry) {
    Update update = this.buildAppend(entry);
    session.add(setTtl(update, entry));
}
 
Example #17
Source File: CassandraTable.java    From hugegraph with Apache License 2.0 4 votes vote down vote up
protected Update buildEliminate(CassandraBackendEntry.Row entry) {
    List<HugeKeys> idNames = this.idColumnName();
    List<HugeKeys> colNames = this.modifiableColumnName();

    Map<HugeKeys, Object> columns = entry.columns();

    // Update by id
    Update update = QueryBuilder.update(table());

    for (HugeKeys key : colNames) {
        /*
         * NOTE: eliminate from map<text, text> should just pass key,
         * if use the following statement:
         * UPDATE vertices SET PROPERTIES=PROPERTIES-{'city':'"Wuhan"'}
         * WHERE LABEL='person' AND PRIMARY_VALUES='josh';
         * it will throw a cassandra exception:
         * Invalid map literal for properties of typefrozen<set<text>>
         */
        if (!columns.containsKey(key)) {
            continue;
        }

        String name = formatKey(key);
        Object value = columns.get(key);
        if (value instanceof Map) {
            @SuppressWarnings("rawtypes")
            Set<?> keySet = ((Map) value).keySet();
            update.with(QueryBuilder.removeAll(name, keySet));
        } else if (value instanceof Set) {
            update.with(QueryBuilder.removeAll(name, (Set<?>) value));
        } else if (value instanceof List) {
            Set<?> keySet = new HashSet<>((List<?>) value);
            update.with(QueryBuilder.removeAll(name, keySet));
        } else {
            update.with(QueryBuilder.remove(name, value));
        }
    }

    for (HugeKeys idName : idNames) {
        assert columns.containsKey(idName);
        update.where(formatEQ(idName, columns.get(idName)));
    }
    return update;
}
 
Example #18
Source File: ConditionSetter.java    From scalardb with Apache License 2.0 4 votes vote down vote up
/**
 * Adds {@code PutIfExists}-specific conditions to the statement
 *
 * @param condition {@code PutIfExists} condition
 */
@Override
public void visit(PutIfExists condition) {
  Update.Where update = (Update.Where) statement;
  update.ifExists();
}