com.datastax.driver.core.querybuilder.QueryBuilder.in()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(13.3k)|赞(0)|评价(0)|浏览(173)

本文整理了Java中com.datastax.driver.core.querybuilder.QueryBuilder.in方法的一些代码示例,展示了QueryBuilder.in的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。QueryBuilder.in方法的具体详情如下:
包路径:com.datastax.driver.core.querybuilder.QueryBuilder
类名称:QueryBuilder
方法名:in

QueryBuilder.in介绍

[英]Creates an "in" WHERE clause for a group of clustering columns (a.k.a. "multi-column IN restriction").

For instance, in(Arrays.asList("a", "b"), Arrays.asList(Arrays.asList(1, "foo"), will generate the CQL WHERE clause (a, b) IN ((1,.

Each element in values must be either an Iterable containing exactly as many values as there are columns to match in names, or a #bindMarker() – in which case, that marker is to be considered as a placeholder for one whole tuple of values to match.

Please note that this variant is only supported starting with Cassandra 2.0.9.
[中]为一组集群列创建一个“in”WHERE子句(又称“multi-column-in-restriction”)。
例如,在(Arrays.asList(“a”、“b”)中,数组。asList(Arrays.asList(1,“foo”)将生成((1,)中的CQL WHERE子句(a,b),。
值中的每个元素必须是一个Iterable,包含的值与名称中要匹配的列的数量相同,或者是一个#bindMarker()——在这种情况下,该标记将被视为一整组要匹配的值的占位符。
请注意,仅从Cassandra 2.0.9开始支持此变体。

代码示例

代码示例来源:origin: prestodb/presto

private static void addWhereInClauses(Where where, List<CassandraColumnHandle> partitionKeyColumns, List<Set<Object>> filterPrefixes)
{
  for (int i = 0; i < filterPrefixes.size(); i++) {
    CassandraColumnHandle column = partitionKeyColumns.get(i);
    List<Object> values = filterPrefixes.get(i)
        .stream()
        .map(value -> column.getCassandraType().getJavaValue(value))
        .collect(toList());
    Clause clause = QueryBuilder.in(CassandraCqlUtils.validColumnName(column.getName()), values);
    where.and(clause);
  }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "short")
public void batchNonBuiltStatementTest() throws Exception {
 SimpleStatement simple =
   new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES ('batchTest1', 'val1')");
 RegularStatement built = insertInto(TABLE1).value("k", "batchTest2").value("t", "val2");
 session().execute(batch().add(simple).add(built));
 List<Row> rows =
   session().execute(select().from(TABLE1).where(in("k", "batchTest1", "batchTest2"))).all();
 assertEquals(2, rows.size());
 Row r1 = rows.get(0);
 assertEquals("batchTest1", r1.getString("k"));
 assertEquals("val1", r1.getString("t"));
 Row r2 = rows.get(1);
 assertEquals("batchTest2", r2.getString("k"));
 assertEquals("val2", r2.getString("t"));
}

代码示例来源:origin: apache/usergrid

private <T> T getValuesCQL(
  final MapScope scope, final Collection<String> keys, final ResultsBuilderCQL<T> builder ) {
  final List<ByteBuffer> serializedKeys = new ArrayList<>();
  keys.forEach(key -> serializedKeys.add(getMapEntryPartitionKey(scope,key)));
  Clause in = QueryBuilder.in("key", serializedKeys );
  Statement statement = QueryBuilder.select().all().from(MAP_ENTRIES_TABLE)
    .where(in);
  ResultSet resultSet = session.execute(statement);
  return builder.buildResultsCQL( resultSet );
}

代码示例来源:origin: kaaproject/kaa

@Override
public List<CassandraNotification> findNotificationsByTopicId(String topicId) {
 LOG.debug("Try to find notifications by topic id {}", topicId);
 Where query = select().from(getColumnFamilyName()).where(eq(NF_TOPIC_ID_PROPERTY, topicId))
   .and(QueryBuilder.in(
     NF_NOTIFICATION_TYPE_PROPERTY, getStringTypes(NotificationTypeDto.values())));
 LOG.trace("Execute query {}", query);
 List<CassandraNotification> notifications = findListByStatement(query);
 if (LOG.isTraceEnabled()) {
  LOG.trace("Found notifications {}", Arrays.toString(notifications.toArray()));
 }
 return notifications;
}

代码示例来源:origin: kaaproject/kaa

@Override
public List<CassandraEndpointProfile> findByEndpointUserId(String endpointUserId) {
 LOG.debug("Try to find endpoint profiles by endpoint user id [{}]", endpointUserId);
 List<CassandraEndpointProfile> profileList = Collections.emptyList();
 CassandraEndpointUser endpointUser = endpointUserDao.findById(endpointUserId);
 if (endpointUser != null) {
  List<String> ids = endpointUser.getEndpointIds();
  if (ids != null && !ids.isEmpty()) {
   Statement select = select().from(getColumnFamilyName())
     .where(in(EP_EP_KEY_HASH_PROPERTY, convertStringIds(ids)));
   LOG.trace("Execute statements {}", select);
   profileList = findListByStatement(select);
  }
 }
 if (LOG.isTraceEnabled()) {
  LOG.trace("Found endpoint profiles {}", Arrays.toString(profileList.toArray()));
 }
 return profileList;
}

代码示例来源:origin: kaaproject/kaa

@Override
public void removeNotificationsByAppId(String appId) {
 LOG.debug("Remove endpoint notifications by app id {}", appId);
 Statement deleteEpNfs = delete().from(getColumnFamilyName())
   .where(
     QueryBuilder.in(
       ET_NF_ENDPOINT_KEY_HASH_PROPERTY,
       cassandraEpByAppIdDao.getEpIdsListByAppId(appId)));
 LOG.trace("Execute query {}", deleteEpNfs);
 execute(deleteEpNfs);
}

代码示例来源:origin: apache/usergrid

@Override
public Iterator<UniqueValue> getAllUniqueFields( final ApplicationScope collectionScope, final Id entityId ) {
  Preconditions.checkNotNull( collectionScope, "collectionScope is required" );
  Preconditions.checkNotNull( entityId, "entity id is required" );
  Clause inKey = QueryBuilder.in("key", getLogPartitionKey(collectionScope.getApplication(), entityId));
  Statement statement = QueryBuilder.select().all().from(TABLE_UNIQUE_VALUES_LOG)
    .where(inKey);
  return new AllUniqueFieldsIterator(session, statement, entityId);
}

代码示例来源:origin: kaaproject/kaa

@Override
public void removeNotificationsByTopicId(String topicId) {
 LOG.debug("Remove notifications by topic id {}", topicId);
 Delete.Where query = delete().from(getColumnFamilyName())
   .where(eq(NF_TOPIC_ID_PROPERTY, topicId))
   .and(QueryBuilder.in(
     NF_NOTIFICATION_TYPE_PROPERTY, getStringTypes(NotificationTypeDto.values())));
 execute(query);
 LOG.trace("Execute query {}", query);
}

代码示例来源:origin: apache/usergrid

@Override
public Map<String, Object> getTokenInfo(UUID tokenUUID){
  Preconditions.checkNotNull(tokenUUID, "token UUID is required");
  List<ByteBuffer> tokenProperties = new ArrayList<>();
  TOKEN_PROPERTIES.forEach( prop ->
    tokenProperties.add(DataType.serializeValue(prop, ProtocolVersion.NEWEST_SUPPORTED)));
  final ByteBuffer key = DataType.uuid().serialize(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED);
  final Clause inKey = QueryBuilder.eq("key", key);
  final Clause inColumn = QueryBuilder.in("column1", tokenProperties );
  final Statement statement = QueryBuilder.select().all().from(TOKENS_TABLE)
    .where(inKey)
    .and(inColumn)
    .setConsistencyLevel(cassandraConfig.getDataStaxReadCl());
  final ResultSet resultSet = session.execute(statement);
  final List<Row> rows = resultSet.all();
  Map<String, Object> tokenInfo = new HashMap<>();
  rows.forEach( row -> {
    final String name = (String)DataType.text()
      .deserialize(row.getBytes("column1"), ProtocolVersion.NEWEST_SUPPORTED);
    final Object value = deserializeColumnValue(name, row.getBytes("value"));
    if (value == null){
      throw new RuntimeException("error deserializing token info for property: "+name);
    }
    tokenInfo.put(name, value);
  });
  logger.trace("getTokenInfo, info: {}", tokenInfo);
  return tokenInfo;
}

代码示例来源:origin: apache/usergrid

private ByteBuffer getValueCQL( MapScope scope, String key, final ConsistencyLevel consistencyLevel ) {
  Clause in = QueryBuilder.in("key", getMapEntryPartitionKey(scope, key) );
  Statement statement = QueryBuilder.select().all().from(MAP_ENTRIES_TABLE)
    .where(in)
    .setConsistencyLevel(consistencyLevel);
  ResultSet resultSet = session.execute(statement);
  com.datastax.driver.core.Row row = resultSet.one();
  return row != null ? row.getBytes("value") : null;
}

代码示例来源:origin: apache/usergrid

@Override
public void delete( final MapScope scope, final String key ) {
  Statement deleteMapEntry;
  Clause equalsEntryKey = QueryBuilder.eq("key", getMapEntryPartitionKey(scope, key));
  deleteMapEntry = QueryBuilder.delete().from(MAP_ENTRIES_TABLE)
    .where(equalsEntryKey);
  session.execute(deleteMapEntry);
  // not sure which bucket the value is in, execute a delete against them all
  final int[] buckets = BUCKET_LOCATOR.getAllBuckets( scope.getName() );
  List<ByteBuffer> mapKeys = new ArrayList<>();
  for( int bucket :  buckets){
    mapKeys.add( getMapKeyPartitionKey(scope, bucket));
  }
  Statement deleteMapKey;
  Clause inKey = QueryBuilder.in("key", mapKeys);
  Clause column1Equals = QueryBuilder.eq("column1", DataType.text().serialize(key, ProtocolVersion.NEWEST_SUPPORTED));
  deleteMapKey = QueryBuilder.delete().from(MAP_KEYS_TABLE)
    .where(inKey).and(column1Equals);
  session.execute(deleteMapKey);
}

代码示例来源:origin: apache/usergrid

final Clause inKey = QueryBuilder.in("key", getPartitionKey(applicationId, type,
  field.getTypeName().toString(), field.getName(), field.getValue()) );

代码示例来源:origin: apache/usergrid

@Override
public MapKeyResults getAllKeys(final MapScope scope, final String cursor, final int limit ){
  final int[] buckets = BUCKET_LOCATOR.getAllBuckets( scope.getName() );
  final List<ByteBuffer> partitionKeys = new ArrayList<>(NUM_BUCKETS.length);
  for (int bucket : buckets) {
    partitionKeys.add(getMapKeyPartitionKey(scope, bucket));
  }
  Clause in = QueryBuilder.in("key", partitionKeys);
  Statement statement;
  if( isBlank(cursor) ){
    statement = QueryBuilder.select().all().from(MAP_KEYS_TABLE)
      .where(in)
      .setFetchSize(limit);
  }else{
    statement = QueryBuilder.select().all().from(MAP_KEYS_TABLE)
      .where(in)
      .setFetchSize(limit)
      .setPagingState(PagingState.fromString(cursor));
  }
  ResultSet resultSet = session.execute(statement);
  PagingState pagingState = resultSet.getExecutionInfo().getPagingState();
  final List<String> keys = new ArrayList<>();
  Iterator<Row> resultIterator = resultSet.iterator();
  int size = 0;
  while( resultIterator.hasNext() && size < limit){
    size++;
    keys.add((String)DataType.text().deserialize(resultIterator.next().getBytes("column1"), ProtocolVersion.NEWEST_SUPPORTED));
  }
  return new MapKeyResults(pagingState != null ? pagingState.toString() : null, keys);
}

代码示例来源:origin: kaaproject/kaa

@Override
public void removeByAppId(String appId) {
 LOG.debug("Remove endpoint profile by application id [{}]", appId);
 Statement deleteEps = delete().from(getColumnFamilyName())
   .where(in(EP_EP_KEY_HASH_PROPERTY, cassandraEpByAppIdDao.getEpIdsListByAppId(appId)));
 ByteBuffer[] epKeyHashList = cassandraEpByAppIdDao.getEpIdsListByAppId(appId);
 if (epKeyHashList != null) {
  for (ByteBuffer epKeyHash : epKeyHashList) {
   removeByKeyHashFromEpByEndpointGroupId(getBytes(epKeyHash));
  }
 }
 Statement deleteEpsByAppId = delete().from(EP_BY_APP_ID_COLUMN_FAMILY_NAME)
   .where(eq(EP_BY_APP_ID_APPLICATION_ID_PROPERTY, appId));
 executeBatch(deleteEps, deleteEpsByAppId);
 LOG.trace("Execute statements {}, {} like batch", deleteEps, deleteEpsByAppId);
}

代码示例来源:origin: hugegraph/hugegraph

private List<Select> ids2IdSelects(Select select, HugeKeys key,
                  List<Object> ids) {
  int size = ids.size();
  List<Select> selects = new ArrayList<>();
  for (int i = 0, j; i < size; i = j) {
    j = Math.min(i + MAX_ELEMENTS_IN_CLAUSE, size);
    Select idSelect = cloneSelect(select, this.table());
    idSelect.where(QueryBuilder.in(formatKey(key), ids.subList(i, j)));
    selects.add(idSelect);
  }
  return selects;
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
public void should_fail_if_in_clause_has_too_many_values() {
 List<Object> values = Collections.<Object>nCopies(65536, "a");
 select().all().from("foo").where(in("bar", values.toArray()));
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(
  groups = "unit",
  expectedExceptions = IllegalArgumentException.class,
  expectedExceptionsMessageRegExp = "Missing values for IN clause")
public void should_fail_if_in_clause_has_null_values() {
 select().all().from("foo").where(in("bar", (List<?>) null));
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(
  groups = "unit",
  expectedExceptions = IllegalArgumentException.class,
  expectedExceptionsMessageRegExp = "Missing values for IN clause")
public void should_fail_if_compound_in_clause_given_null_values() {
 select().all().from("foo").where(eq("k", 4)).and(in(ImmutableList.of("name"), null));
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(
  groups = "unit",
  expectedExceptions = IllegalArgumentException.class,
  expectedExceptionsMessageRegExp =
    "Too many values for IN clause, the maximum allowed is 65535")
public void should_fail_if_compound_in_clause_has_too_many_values() {
 List<Object> values = Collections.<Object>nCopies(65536, bindMarker());
 select().all().from("foo").where(eq("k", 4)).and(in(ImmutableList.of("name"), values));
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
public void should_fail_if_built_statement_has_too_many_values() {
 List<Object> values = Collections.<Object>nCopies(65535, "a");
 // If the excessive count results from successive DSL calls, we don't check it on the fly so
 // this statement works:
 BuiltStatement statement =
   select().all().from("foo").where(eq("bar", "a")).and(in("baz", values.toArray()));
 // But we still want to check it client-side, to fail fast instead of sending a bad query to
 // Cassandra.
 // getValues() is called on any RegularStatement before we send it (see
 // SessionManager.makeRequestMessage).
 statement.getValues(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE);
}

相关文章

微信公众号

最新文章

更多