Java Code Examples for com.datastax.driver.core.querybuilder.Update#with()

The following examples show how to use com.datastax.driver.core.querybuilder.Update#with() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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;
}