@Override public long removeByPattern(String regex) throws IOException { Statement statement = Delete.deleteFromCurrentBucket().where(regexpContains("meta().id", regex)); final N1qlQueryResult result = bucket.query(N1qlQuery.simple(statement)); if (logger.isDebugEnabled()) { logger.debug("Deleted documents using regex {}, result={}", regex, result); } return result.info().mutationCount(); } }
/** * Performs the {@link #delete(String, String)} (String, String)} operation via N1QL ("DELETE"). * * If this option should be used, the "-p couchbase.kv=false" property must be set. * * @param docId the document ID. * @return The result of the operation. */ private Status deleteN1ql(final String docId) throws Exception { String deleteQuery = "DELETE FROM `" + bucketName + "` USE KEYS [$1]"; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( deleteQuery, JsonArray.from(docId), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + deleteQuery + ", Errors: " + queryResult.errors()); } return Status.OK; }
/** * Run a {@link N1qlQuery#simple(Statement)} query. * * @param statement Statement. * @param <T> Entity type. * @return A list of results. * @see N1Q#from(Class) */ default <T> Observable<List<T>> query(final Statement statement) { return query(N1qlQuery.simple(statement)); }
/** * Creates a new {@link N1qlQuery} for the given class, this method build a query like: * * <pre> * select b.* from bucket b where b._class = 'model.Beer' * </pre> * * @param bucket Bucket name. * @param entityClass Entity class. * @return A query. */ public static GroupByPath from(final String bucket, final Class<?> entityClass) { String alias = String.valueOf(entityClass.getSimpleName().charAt(0)); return Select.select(alias + ".*") .from(i(bucket) + " " + alias) .where(path(alias, CLASS).eq(s(entityClass.getName()))); }
@Test public void shouldExecuteN1ql() { getBucket().query(N1qlQuery.simple("INSERT INTO " + TEST_BUCKET + " (KEY, VALUE) VALUES ('" + ID + "', " + DOCUMENT + ")")); N1qlQueryResult query = getBucket().query(N1qlQuery.simple("SELECT * FROM " + TEST_BUCKET + " USE KEYS '" + ID + "'")); Assert.assertTrue(query.parseSuccess()); Assert.assertTrue(query.finalSuccess()); List<N1qlQueryRow> n1qlQueryRows = query.allRows(); Assert.assertEquals(1, n1qlQueryRows.size()); Assert.assertEquals(DOCUMENT, n1qlQueryRows.get(0).value().get(TEST_BUCKET).toString()); }
/** * Execute native query. * * @param n1qlQuery * the n1ql query * @param em * the entity manager * @return the list */ public List executeNativeQuery(String n1qlQuery, EntityMetadata em) { N1qlQueryResult result = bucket .query(N1qlQuery.simple(n1qlQuery, N1qlParams.build().consistency(ScanConsistency.REQUEST_PLUS))); LOGGER.debug("Executed query : " + n1qlQuery + " on the " + bucket.name() + " Bucket"); validateQueryResults(n1qlQuery, result); return result.allRows(); }
public static boolean fillDB(CouchbaseCluster cluster) { Bucket couchbaseBucket = cluster.openBucket(BUCKET_NAME); couchbaseBucket.insert(JsonDocument.create("artist:vincent_van_gogh", VINCENT_VAN_GOGH)); N1qlQueryResult queryResult = couchbaseBucket.query(N1qlQuery.simple(String.format(QUERY, BUCKET_NAME), N1qlParams.build().consistency(ScanConsistency.REQUEST_PLUS))); couchbaseBucket.close(); return queryResult.info().resultCount() == 1; }
@After public void clear() { if (getCouchbaseContainer().isIndex() && getCouchbaseContainer().isQuery() && getCouchbaseContainer().isPrimaryIndex()) { getBucket().query( N1qlQuery.simple(String.format("DELETE FROM `%s`", getBucket().name()), N1qlParams.build().consistency(ScanConsistency.STATEMENT_PLUS))); } else { getBucket().bucketManager().flush(); } }
final List<HashMap<String, ByteIterator>> data = new ArrayList<HashMap<String, ByteIterator>>(recordcount); bucket.async() .query(N1qlQuery.parameterized( scanAllQuery, JsonArray.from(formatId(table, startkey), recordcount), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )) .doOnNext(new Action1<AsyncN1qlQueryResult>() {
@Override public <T> Observable<List<T>> query(final N1qlQuery query) { return bucket.query(query) .flatMap(aqr -> Observable.zip(aqr.rows().toList(), aqr.errors().toList(), aqr.finalSuccess().singleOrDefault(Boolean.FALSE), (rows, errors, finalSuccess) -> { if (!finalSuccess) { throw new QueryExecutionException( "execution of query resulted in exception: ", Try.apply(() -> errors.get(0)).orElse(null)); } List<T> value = new ArrayList<>(); for (AsyncN1qlQueryRow row : rows) { try { T v = converter.fromBytes(row.byteValue()); value.add(v); } catch (IOException ex) { throw new QueryExecutionException( "execution of query resulted in exception", null, ex); } } return value; })); }
public void createBucket(BucketSettings bucketSetting, UserSettings userSettings, boolean primaryIndex) { ClusterManager clusterManager = getCouchbaseCluster().clusterManager(clusterUsername, clusterPassword); // Insert Bucket BucketSettings bucketSettings = clusterManager.insertBucket(bucketSetting); try { // Insert Bucket user clusterManager.upsertUser(AuthDomain.LOCAL, bucketSetting.name(), userSettings); } catch (Exception e) { logger().warn("Unable to insert user '" + bucketSetting.name() + "', maybe you are using older version"); } if (index) { Bucket bucket = getCouchbaseCluster().openBucket(bucketSettings.name(), bucketSettings.password()); new CouchbaseQueryServiceWaitStrategy(bucket).waitUntilReady(this); if (primaryIndex) { bucket.query(Index.createPrimaryIndex().on(bucketSetting.name())); } } }
@Override public Observable<RawJsonDocument> call(AsyncN1qlQueryRow row) { String id = new String(row.byteValue()).trim(); return bucket.async().get(id.substring(1, id.length()-1), RawJsonDocument.class); } })
/** * Performs the {@link #insert(String, String, Map)} operation via N1QL ("INSERT"). * * If this option should be used, the "-p couchbase.kv=false" property must be set. * * @param docId the document ID * @param values the values to update the document with. * @return The result of the operation. */ private Status insertN1ql(final String docId, final Map<String, ByteIterator> values) throws Exception { String insertQuery = "INSERT INTO `" + bucketName + "`(KEY,VALUE) VALUES ($1,$2)"; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( insertQuery, JsonArray.from(docId, valuesToJsonObject(values)), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + insertQuery + ", Errors: " + queryResult.errors()); } return Status.OK; }
@PostConstruct private void postConstruct() { // Need to post-process travel data to add _class attribute List<Airline> airlinesWithoutClassAttribute = couchbaseOperations.findByN1QL(N1qlQuery.simple( // "SELECT META(`travel-sample`).id AS _ID, META(`travel-sample`).cas AS _CAS, `travel-sample`.* " + // "FROM `travel-sample` " + // "WHERE type = \"airline\" AND _class IS MISSING;"), Airline.class); airlinesWithoutClassAttribute.forEach(couchbaseOperations::save); } }
/** * Performs the {@link #upsert(String, String, Map)} operation via N1QL ("UPSERT"). * * If this option should be used, the "-p couchbase.upsert=true -p couchbase.kv=false" properties must be set. * * @param docId the document ID * @param values the values to update the document with. * @return The result of the operation. */ private Status upsertN1ql(final String docId, final Map<String, ByteIterator> values) throws Exception { String upsertQuery = "UPSERT INTO `" + bucketName + "`(KEY,VALUE) VALUES ($1,$2)"; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( upsertQuery, JsonArray.from(docId, valuesToJsonObject(values)), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + upsertQuery + ", Errors: " + queryResult.errors()); } return Status.OK; }
@PostConstruct private void postConstruct() { // Need to post-process travel data to add _class attribute CouchbaseOperations couchbaseOperations = couchbaseOperationsProvider.getIfUnique(); List<Airline> airlinesWithoutClassAttribute = couchbaseOperations.findByN1QL(N1qlQuery.simple( // "SELECT META(`travel-sample`).id AS _ID, META(`travel-sample`).cas AS _CAS, `travel-sample`.* " + // "FROM `travel-sample` " + // "WHERE type = \"airline\" AND _class IS MISSING;"), Airline.class); airlinesWithoutClassAttribute.forEach(couchbaseOperations::save); } }
/** * Performs the {@link #update(String, String, Map)} operation via N1QL ("UPDATE"). * * If this option should be used, the "-p couchbase.kv=false" property must be set. * * @param docId the document ID * @param values the values to update the document with. * @return The result of the operation. */ private Status updateN1ql(final String docId, final Map<String, ByteIterator> values) throws Exception { String fields = encodeN1qlFields(values); String updateQuery = "UPDATE `" + bucketName + "` USE KEYS [$1] SET " + fields; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( updateQuery, JsonArray.from(docId), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + updateQuery + ", Errors: " + queryResult.errors()); } return Status.OK; }
/** * Executes a plain un-parameterized N1QL kernelTransaction. * * @param statement the raw kernelTransaction string to execute * @return the list of {@link JsonObject}s retrieved by this query * @see N1qlQuery#simple(Statement) */ public List<JsonObject> executeStatement(String statement) { SimpleN1qlQuery query = N1qlQuery.simple(statement); return executeQuery(query); }
throws Exception { String readQuery = "SELECT " + joinFields(fields) + " FROM `" + bucketName + "` USE KEYS [$1]"; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( readQuery, JsonArray.from(docId), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + readQuery + ", Errors: " + queryResult.errors()); row = queryResult.rows().next(); } catch (NoSuchElementException ex) { return Status.NOT_FOUND; JsonObject content = row.value(); if (fields == null) {
String scanSpecQuery = "SELECT " + joinFields(fields) + " FROM `" + bucketName + "` WHERE meta().id >= '$1' LIMIT $2"; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( scanSpecQuery, JsonArray.from(formatId(table, startkey), recordcount), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new RuntimeException("Error while parsing N1QL Result. Query: " + scanSpecQuery + ", Errors: " + queryResult.errors()); JsonObject value = row.value(); if (fields == null) { value = value.getObject(bucketName);