Search in sources :

Example 16 with MutationResult

use of com.couchbase.client.java.kv.MutationResult in project couchbase-jvm-clients by couchbase.

the class KeyValueCollectionIntegrationTest method recognizesCollectionAfterCreation.

@Test
@IgnoreWhen(clusterTypes = ClusterType.CAVES)
void recognizesCollectionAfterCreation() {
    String collId = UUID.randomUUID().toString().substring(0, 10);
    CollectionSpec collectionSpec = CollectionSpec.create(collId, CollectionIdentifier.DEFAULT_SCOPE);
    bucket.collections().createCollection(collectionSpec);
    Collection collection = bucket.collection(collId);
    String id = UUID.randomUUID().toString();
    String content = "bar";
    MutationResult upsertResult = collection.upsert(id, content);
    GetResult getResult = collection.get(id);
    assertEquals(upsertResult.cas(), getResult.cas());
    assertEquals(content, getResult.contentAs(String.class));
}
Also used : GetResult(com.couchbase.client.java.kv.GetResult) CollectionSpec(com.couchbase.client.java.manager.collection.CollectionSpec) MutationResult(com.couchbase.client.java.kv.MutationResult) IgnoreWhen(com.couchbase.client.test.IgnoreWhen) JavaIntegrationTest(com.couchbase.client.java.util.JavaIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 17 with MutationResult

use of com.couchbase.client.java.kv.MutationResult in project couchbase-jvm-clients by couchbase.

the class KeyValueIntegrationTest method appendAsync.

@Test
void appendAsync() throws ExecutionException, InterruptedException {
    String id = UUID.randomUUID().toString();
    byte[] helloBytes = "Hello, ".getBytes(UTF_8);
    byte[] worldBytes = "World!".getBytes(UTF_8);
    byte[] helloWorldBytes = "Hello, World!".getBytes(UTF_8);
    assertThrows(ExecutionException.class, () -> collection.async().binary().append(id, helloBytes).get());
    MutationResult upsert = collection.upsert(id, helloBytes, upsertOptions().transcoder(RawBinaryTranscoder.INSTANCE));
    assertTrue(upsert.cas() != 0);
    assertArrayEquals(helloBytes, collection.get(id, getOptions().transcoder(RawBinaryTranscoder.INSTANCE)).contentAs(byte[].class));
    MutationResult append = collection.async().binary().append(id, worldBytes).get();
    assertTrue(append.cas() != 0);
    assertNotEquals(append.cas(), upsert.cas());
    assertArrayEquals(helloWorldBytes, collection.get(id, getOptions().transcoder(RawBinaryTranscoder.INSTANCE)).contentAs(byte[].class));
}
Also used : MutationResult(com.couchbase.client.java.kv.MutationResult) JavaIntegrationTest(com.couchbase.client.java.util.JavaIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 18 with MutationResult

use of com.couchbase.client.java.kv.MutationResult in project couchbase-elasticsearch-connector by couchbase.

the class BasicReplicationTest method createDeleteReject.

@Test
public void createDeleteReject() throws Throwable {
    try (TestCouchbaseClient cb = new TestCouchbaseClient(commonConfig)) {
        final Bucket bucket = cb.createTempBucket(couchbase);
        final Collection collection = bucket.defaultCollection();
        final ImmutableConnectorConfig config = withBucketName(commonConfig, bucket.name());
        try (TestEsClient es = new TestEsClient(config);
            AsyncTask connector = AsyncTask.run(() -> ElasticsearchConnector.run(config))) {
            assertIndexInferredFromDocumentId(bucket, es);
            // Create two documents in the same vbucket to make sure we're not conflating seqno and revision number.
            // This first one has a seqno and revision number that are the same... not useful for the test.
            final String firstKeyInVbucket = forceKeyToPartition("createdFirst", 0, 1024).get();
            upsertWithRetry(bucket, JsonDocument.create(firstKeyInVbucket, JsonObject.create()));
            // Here's the document we're going to test! Its seqno should be different than document revision.
            final String blueKey = forceKeyToPartition("color:blue", 0, 1024).get();
            final MutationResult upsertResult = upsertWithRetry(bucket, JsonDocument.create(blueKey, JsonObject.create().put("hex", "0000ff")));
            final JsonNode content = es.waitForDocument(CATCH_ALL_INDEX, blueKey);
            System.out.println(content);
            final long expectedDocumentRevision = 1;
            final JsonNode meta = content.path("meta");
            assertEquals(blueKey, meta.path("id").textValue());
            assertEquals(expectedDocumentRevision, meta.path("revSeqno").longValue());
            assertTrue(meta.path("lockTime").isIntegralNumber());
            assertEquals(0, meta.path("lockTime").longValue());
            assertTrue(meta.path("expiration").isIntegralNumber());
            assertEquals(0, meta.path("expiration").longValue());
            assertThat(meta.path("rev").textValue()).startsWith(expectedDocumentRevision + "-");
            assertTrue(meta.path("flags").isIntegralNumber());
            assertEquals(upsertResult.cas(), meta.path("cas").longValue());
            MutationToken mutationToken = upsertResult.mutationToken().orElseThrow(() -> new AssertionError("expected mutation token"));
            assertEquals(mutationToken.sequenceNumber(), meta.path("seqno").longValue());
            assertEquals(mutationToken.partitionID(), meta.path("vbucket").longValue());
            assertEquals(mutationToken.partitionUUID(), meta.path("vbuuid").longValue());
            assertEquals("0000ff", content.path("doc").path("hex").textValue());
            // Make sure deletions are propagated to elasticsearch
            collection.remove(blueKey);
            es.waitForDeletion(CATCH_ALL_INDEX, blueKey);
            // Create an incompatible document (different type for "hex" field, Object instead of String)
            final String redKey = "color:red";
            upsertWithRetry(bucket, JsonDocument.create(redKey, JsonObject.create().put("hex", JsonObject.create().put("red", "ff").put("green", "00").put("blue", "00"))));
            assertDocumentRejected(es, CATCH_ALL_INDEX, redKey, "mapper_parsing_exception");
            // Elasticsearch doesn't support BigInteger fields. This error surfaces when creating the index request,
            // before the request is sent to Elasticsearch. Make sure we trapped the error and converted it to a rejection.
            final String bigIntKey = "veryLargeNumber";
            upsertWithRetry(bucket, JsonDocument.create(bigIntKey, JsonObject.create().put("number", new BigInteger("17626319910530664276"))));
            assertDocumentRejected(es, CATCH_ALL_INDEX, bigIntKey, "mapper_parsing_exception");
        }
    }
}
Also used : ImmutableConnectorConfig(com.couchbase.connector.config.es.ImmutableConnectorConfig) AsyncTask(com.couchbase.connector.cluster.consul.AsyncTask) JsonNode(com.fasterxml.jackson.databind.JsonNode) Bucket(com.couchbase.client.java.Bucket) MutationToken(com.couchbase.client.core.msg.kv.MutationToken) Collection(com.couchbase.client.java.Collection) BigInteger(java.math.BigInteger) MutationResult(com.couchbase.client.java.kv.MutationResult) Test(org.junit.Test)

Example 19 with MutationResult

use of com.couchbase.client.java.kv.MutationResult in project couchbase-jvm-clients by couchbase.

the class RateLimitingIntegrationTest method searchRateLimitMaxEgress.

@Test
@IgnoreWhen(missesCapabilities = Capabilities.SEARCH)
void searchRateLimitMaxEgress() throws Exception {
    String username = "searchRateLimitEgress";
    Limits limits = new Limits();
    limits.searchLimits = new SearchLimits(10, 100, 10, 1);
    createRateLimitedUser(username, limits);
    adminCluster.searchIndexes().upsertIndex(new SearchIndex("ratelimits-egress", config().bucketname()));
    Cluster cluster = createTestCluster(username);
    try {
        cluster.waitUntilReady(Duration.ofSeconds(10));
        String content = repeatString(1024 * 1024, "a");
        MutationResult mutationResult = cluster.bucket(config().bucketname()).defaultCollection().upsert("fts-egress", JsonObject.create().put("content", content), UpsertOptions.upsertOptions().timeout(Duration.ofSeconds(10)));
        RateLimitedException ex = assertThrows(RateLimitedException.class, () -> {
            for (int i = 0; i < 10; i++) {
                try {
                    cluster.searchQuery("ratelimits-egress", SearchQuery.wildcard("a*"), SearchOptions.searchOptions().timeout(Duration.ofSeconds(10)).fields("content").consistentWith(MutationState.from(mutationResult.mutationToken().get())).highlight(HighlightStyle.HTML, "content"));
                } catch (TimeoutException e) {
                // continue
                } catch (CouchbaseException e) {
                    if (e.getMessage().contains("no planPIndexes")) {
                        continue;
                    }
                    throw e;
                }
            }
        });
        assertTrue(ex.getMessage().contains("egress_mib_per_min"));
    } finally {
        cluster.disconnect();
        adminCluster.users().dropUser(username);
        adminCluster.searchIndexes().dropIndex("ratelimits-egress");
    }
}
Also used : CouchbaseException(com.couchbase.client.core.error.CouchbaseException) SearchIndex(com.couchbase.client.java.manager.search.SearchIndex) RateLimitedException(com.couchbase.client.core.error.RateLimitedException) MutationResult(com.couchbase.client.java.kv.MutationResult) UnambiguousTimeoutException(com.couchbase.client.core.error.UnambiguousTimeoutException) TimeoutException(com.couchbase.client.core.error.TimeoutException) IgnoreWhen(com.couchbase.client.test.IgnoreWhen) JavaIntegrationTest(com.couchbase.client.java.util.JavaIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 20 with MutationResult

use of com.couchbase.client.java.kv.MutationResult in project couchbase-jvm-clients by couchbase.

the class SearchIntegrationTest method searchMatchOperatorAndHit.

@Test
void searchMatchOperatorAndHit() throws Throwable {
    String missId = UUID.randomUUID().toString();
    String hitId = UUID.randomUUID().toString();
    MutationResult insertResult1 = collection.insert(missId, mapOf("fields", mapOf("name", "billy")));
    MutationResult insertResult2 = collection.insert(hitId, mapOf("fields", mapOf("name", "billy", "surname", "kid")));
    try {
        runWithRetry(Duration.ofSeconds(30), () -> {
            SearchResult result = cluster.searchQuery(indexName, match("billy kid").operator(MatchOperator.AND), searchOptions().consistentWith(MutationState.from(insertResult1.mutationToken().get(), insertResult2.mutationToken().get())));
            List<String> actualDocIds = result.rows().stream().map(SearchRow::id).collect(toList());
            assertEquals(listOf(hitId), actualDocIds);
        });
    } finally {
        collection.remove(missId);
        collection.remove(hitId);
    }
}
Also used : SearchResult(com.couchbase.client.java.search.result.SearchResult) SearchQuery.queryString(com.couchbase.client.java.search.SearchQuery.queryString) MutationResult(com.couchbase.client.java.kv.MutationResult) JavaIntegrationTest(com.couchbase.client.java.util.JavaIntegrationTest) Test(org.junit.jupiter.api.Test)

Aggregations

MutationResult (com.couchbase.client.java.kv.MutationResult)42 JavaIntegrationTest (com.couchbase.client.java.util.JavaIntegrationTest)40 Test (org.junit.jupiter.api.Test)40 JsonObject (com.couchbase.client.java.json.JsonObject)16 IgnoreWhen (com.couchbase.client.test.IgnoreWhen)13 GetResult (com.couchbase.client.java.kv.GetResult)11 SearchQuery.queryString (com.couchbase.client.java.search.SearchQuery.queryString)5 SearchResult (com.couchbase.client.java.search.result.SearchResult)5 DocumentNotFoundException (com.couchbase.client.core.error.DocumentNotFoundException)4 TimeoutException (com.couchbase.client.core.error.TimeoutException)3 Bucket (com.couchbase.client.java.Bucket)2 Collection (com.couchbase.client.java.Collection)2 ExistsResult (com.couchbase.client.java.kv.ExistsResult)2 QueryOptions (com.couchbase.client.java.query.QueryOptions)2 QueryResult (com.couchbase.client.java.query.QueryResult)2 ReactiveQueryResult (com.couchbase.client.java.query.ReactiveQueryResult)2 CasMismatchException (com.couchbase.client.core.error.CasMismatchException)1 CouchbaseException (com.couchbase.client.core.error.CouchbaseException)1 DocumentExistsException (com.couchbase.client.core.error.DocumentExistsException)1 RateLimitedException (com.couchbase.client.core.error.RateLimitedException)1