private Statement createStatementToSaveFollowing(User user, Application app) {
    UUID userId = UUID.fromString(user.userId);
    UUID appId = UUID.fromString(app.applicationId);

    BatchStatement batch = new BatchStatement();

    Statement insertIntoAppFollowersTable =
        QueryBuilder.insertInto(Follow.TABLE_NAME_APP_FOLLOWERS)
            .value(APP_ID, appId)
            .value(USER_ID, userId)
            .value(APP_NAME, app.name)
            .value(USER_FIRST_NAME, user.firstName)
            .value(TIME_OF_FOLLOW, Instant.now().toEpochMilli());

    batch.add(insertIntoAppFollowersTable);

    Statement insertIntoUserFollowingsTable =
        QueryBuilder.insertInto(Follow.TABLE_NAME_USER_FOLLOWING)
            .value(APP_ID, appId)
            .value(USER_ID, userId)
            .value(APP_NAME, app.name)
            .value(USER_FIRST_NAME, user.firstName)
            .value(TIME_OF_FOLLOW, Instant.now().toEpochMilli());

    batch.add(insertIntoUserFollowingsTable);

    return batch;
  }
  @Test
  public void testBuiltStatementOptionValues() {

    MockSession session = new MockSession();
    Insert insert = QueryBuilder.insertInto("myTable");
    insert.values(new String[] {"arg"}, new Object[] {"stringvalue"});

    Insert.Options using = insert.using(timestamp(100));
    using.values(new String[] {"another"}, new Object[] {"value"});

    Operation operation = CassandraOperationFinalizer.get(insert);
    assertNotNull(operation);

    session.execute(insert);

    assertNotNull(operation.getLabel());
    assertEquals("OperationType", CassandraExternalResourceAnalyzer.TYPE, operation.getType());
    String cql = operation.get("cql", String.class);
    assertEquals("cql", insert.getQueryString(), cql);
    OperationMap params =
        operation.get(CassandraOperationFinalizer.PARAMS_VALUES, OperationMap.class);
    assertNotNull(params);
    assertEquals("params", params.size(), 2);
    assertNull(CassandraOperationFinalizer.remove(insert));
  }
  @Override
  public void migrate(Session session) throws Exception {
    Insert insert = QueryBuilder.insertInto("test1");
    insert.value("space", "web");
    insert.value("key", "google");
    insert.value("value", "google.com");

    session.execute(insert);
  }
 private void insertMetricIntoBatch(Metric metric, Map<RetentionTable, BatchStatement> map) {
   Object[] values = {metric.name(), metric.timestamp(), metric.value()};
   Optional<RetentionTable> table = environment.retentions().findAccessTableForMetric(metric);
   if (!table.isPresent()) {
     logger.warn("No retention defined - not outputting metric! {}", metric);
   } else {
     map.get(table.get())
         .add(QueryBuilder.insertInto(table.get().tableName()).values(COLUMNS, values));
   }
 }
  private void controlCassandra() {
    Insert insert = QueryBuilder.insertInto("usuario");
    insert.setConsistencyLevel(ConsistencyLevel.ONE);
    insert.value("id", UUID.randomUUID());
    insert.value("nombre", "Alison");
    insert.value("email", "gmailalgo");

    cassandraOperations.execute(insert);

    Select select = QueryBuilder.select().from("demo", "usuario");

    select.limit(100);

    List<usuario> results = cassandraOperations.select(select, usuario.class);

    results.forEach(r -> System.out.println(r));

    Map<String, String> p = new HashMap<String, String>();
    p.putIfAbsent("hola", "caracola");

    Insert insertSample = QueryBuilder.insertInto("sample");
    insertSample.setConsistencyLevel(ConsistencyLevel.ONE);
    insertSample.value("userid", UUID.randomUUID().toString());
    insertSample.value("todo", p);

    cassandraOperations.execute(insertSample);

    Select selectSample = QueryBuilder.select().from("demo", "sample");

    selectSample.limit(100);

    List<sample> resultsSample = cassandraOperations.select(selectSample, sample.class);

    for (sample s : resultsSample) {
      System.out.println(s);
      s.getTodo().entrySet().forEach(e -> System.out.println(" " + e));
    }
  }
Beispiel #6
0
 Indexer(
     Session session,
     @Nullable Integer indexTtl,
     @Nullable ConcurrentMap<PartitionKeyToTraceId, Pair<Long>> sharedState,
     IndexSupport index) {
   this.index = index;
   this.boundName = UPPER_CAMEL.to(LOWER_HYPHEN, index.getClass().getSimpleName());
   Insert insert =
       index.declarePartitionKey(
           QueryBuilder.insertInto(index.table())
               .value("ts", QueryBuilder.bindMarker("ts"))
               .value("trace_id", QueryBuilder.bindMarker("trace_id")));
   if (indexTtl != null) {
     insert.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_")));
   }
   this.prepared = session.prepare(insert);
   this.indexTtl = indexTtl;
   this.session = session;
   this.timestampCodec = new TimestampCodec(session);
   this.sharedState = sharedState;
 }
  @Test
  public void testBuiltStatementValue() {

    MockSession session = new MockSession();
    Insert insert = QueryBuilder.insertInto("myTable");
    insert.value("arg", "stringvalue");

    Operation operation = CassandraOperationFinalizer.get(insert);
    assertNotNull(operation);

    session.execute(insert);

    assertNotNull(operation.getLabel());
    assertEquals("OperationType", CassandraExternalResourceAnalyzer.TYPE, operation.getType());
    String cql = operation.get("cql", String.class);
    assertEquals("cql", insert.getQueryString(), cql);
    OperationMap params =
        operation.get(CassandraOperationFinalizer.PARAMS_VALUES, OperationMap.class);
    assertNotNull(params);
    assertEquals("params", params.size(), 1);
    assertNull(CassandraOperationFinalizer.remove(insert));
  }
  public void insert(String table, String[] names, Object[] values) {

    session.execute(QueryBuilder.insertInto(table).values(names, values));
  }
Beispiel #9
0
  public static void main(String[] args) {

    for (int i = 0; i < args.length; ++i) {
      if ("-endpoint".equals(args[i])) {
        endpoint = args[++i];
      } else if ("-keyspace".equals(args[i])) {
        keyspace = args[++i];
      } else if ("-table".equals(args[i])) {
        table = args[++i];
      } else {
        System.err.println("ConsistencyTest -endpoint hostname -keyspace keyspace -table table");
      }
    }
    if (endpoint == null || keyspace == null || table == null) {
      System.err.println("ConsistencyTest -endpoint hostname -keyspace keyspace -table table");
      System.exit(1);
    }

    String[] endpoints = endpoint.split(":");

    try {
      cluster =
          Cluster.builder()
              .addContactPoints(endpoints)
              .withRetryPolicy(DefaultRetryPolicy.INSTANCE)
              .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy()))
              .build();
      session = cluster.connect(keyspace);

      // work with ONE for both write and read
      long s1 = System.currentTimeMillis();
      Statement insert =
          QueryBuilder.insertInto(table)
              .value("user_id", 100)
              .value("fname", "john")
              .value("lname", "yamada")
              .value("number", 100);
      insert.setConsistencyLevel(ConsistencyLevel.ONE);
      session.execute(insert);
      long e1 = System.currentTimeMillis();
      System.out.println("write ONE time taken (ms) : " + (e1 - s1));

      long s2 = System.currentTimeMillis();
      Statement select =
          QueryBuilder.select().all().from(table).where(QueryBuilder.eq("user_id", 100));
      select.setConsistencyLevel(ConsistencyLevel.ONE);
      results = session.execute(select);
      for (Row row : results) {
        System.out.format(
            "%d %s %s %d\n",
            row.getInt("user_id"),
            row.getString("fname"),
            row.getString("lname"),
            row.getInt("number"));
      }
      long e2 = System.currentTimeMillis();
      System.out.println("read ONE time taken (ms) : " + (e2 - s2));

      Statement delete = QueryBuilder.delete().from(table).where(QueryBuilder.eq("user_id", 100));
      results = session.execute(delete);

      // work with QUORUM for both write and read
      long s3 = System.currentTimeMillis();
      Statement insert2 =
          QueryBuilder.insertInto(table)
              .value("user_id", 200)
              .value("fname", "john")
              .value("lname", "yamada")
              .value("number", 100);
      insert2.setConsistencyLevel(ConsistencyLevel.QUORUM);
      session.execute(insert2);
      long e3 = System.currentTimeMillis();
      System.out.println("write QUORUM time taken (ms) : " + (e3 - s3));

      long s4 = System.currentTimeMillis();
      Statement select2 =
          QueryBuilder.select().all().from(table).where(QueryBuilder.eq("user_id", 200));
      select2.setConsistencyLevel(ConsistencyLevel.QUORUM);
      results = session.execute(select2);
      for (Row row : results) {
        System.out.format(
            "%d %s %s %d\n",
            row.getInt("user_id"),
            row.getString("fname"),
            row.getString("lname"),
            row.getInt("number"));
      }
      long e4 = System.currentTimeMillis();
      System.out.println("read QUORUM time taken (ms) : " + (e4 - s4));

      Statement delete2 = QueryBuilder.delete().from(table).where(QueryBuilder.eq("user_id", 200));
      results = session.execute(delete2);

      // Clean up the connection by closing it
      cluster.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }